如何将POST请求发送到Keras制造的ML引擎模型?

时间:2018-07-28 00:23:01

标签: keras google-cloud-platform google-cloud-ml

我制作了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()

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

我在ML Engine中创建了一个新模型,并部署了第一个版本。 当我尝试使用此json POST

通过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\")"
}

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

1 个答案:

答案 0 :(得分:2)

感谢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()