首页 > 解决方案 > 如何向 Keras 制作的 ML Engine 模型发送 POST 请求?

问题描述

我做了一个 Keras 模型

model = Sequential() 
model.add(Dense(12, input_dim=7, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

在当地训练

# Compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# Fit the model
model.fit(X_train, Y_train, epochs=150, batch_size=10)

测试它可以工作

example = np.array([X_test.iloc[0]])    
model.predict(example)

使用此功能保存它

def to_savedmodel(model, export_path):
"""Convert the Keras HDF5 model into TensorFlow SavedModel."""
builder = saved_model_builder.SavedModelBuilder(export_path)
signature = predict_signature_def(inputs={'input': model.inputs[0]},
                                outputs={'income': model.outputs[0]})
K.clear_session()
sess = K.get_session()
builder.add_meta_graph_and_variables(
        sess=sess,
        tags=[tag_constants.SERVING],
        signature_def_map={
            signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: signature}
    )
sess.close()
K.clear_session()
builder.save()

该模型现在以 GC 存储.pb格式保存。

我在 ML Engine 中制作了一个新模型并部署了第一个版本。当我尝试POST使用此 json 通过 HTTP 请求使用它时body

{
  "instances": [{
    "input": [1, 2, 3, 4, 5, 6, 7 ]
  }]
}

我得到这个错误:

{
    "error": "Prediction failed: Error during model execution: AbortionError(code=StatusCode.NOT_FOUND, details=\"FeedInputs: unable to find feed output dense_34_input:0\")"
}

知道如何发送正确的正文或正确保存模型吗?

标签: kerasgoogle-cloud-platformgoogle-cloud-ml

解决方案


谢谢sdcbr。你为我指明了正确的方向。保存模型的函数正在丢弃我训练过的模型。我改变了它,现在运行良好:

def to_savedmodel(fname, export_path):
    with tf.Session() as sess:
        K.set_session(sess)
    model = load_model(fname)
    sess.run(tf.initialize_all_variables())
    K.set_learning_phase(0)
    builder = SavedModelBuilder(export_path)
    signature = predict_signature_def(
        inputs={"inputs": model.input},
        outputs={"outputs": model.output}) 
builder.add_meta_graph_and_variables(
        sess=sess,
        tags=[tag_constants.SERVING],
        signature_def_map={
            'predict': signature})
    builder.save()

推荐阅读