【问题标题】:Using trained keras model in google ml-engine在 google ml-engine 中使用经过训练的 keras 模型
【发布时间】:2019-03-03 02:47:10
【问题描述】:

我正在尝试将 gcloud ml-engine 与 tensorflow 一起使用,更准确地说,我想使用已经训练好的 keras 模型。

我设法使用 sciktlearn 模型做到了这一点,但这里不一样......

首先我用 Keras 训练一个简单的模型

import numpy as np
from tensorflow import keras

# Creating the dataset
X = np.random.random((500,9))
y = (np.random.random(500)>0.5).astype(int)

# Splitting 
idx_train, idx_test = np.arange(400), np.arange(400,500)
X_train, X_test = X[idx_train], X[idx_test]
y_train, y_test = y[idx_train], y[idx_test]



def define_model():    
    input1 = keras.layers.Input(shape=(9,),name="values")
    hidden = keras.layers.Dense(50, activation='relu', name="hidden")(input1)

    preds = keras.layers.Dense(1, activation='sigmoid', name="labels")(hidden)

    model = keras.models.Model(inputs=input1, 
                  outputs=preds)

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

    return model

model = define_model()
model.fit(X_train, y_train,
          batch_size=10, 
          epochs=10, validation_split=0.2)

我读到我需要一个 SavedModel 才能在此处的 ml-engine 中使用它 https://cloud.google.com/ml-engine/docs/tensorflow/deploying-models

看来我必须将其转换为估算器

model.save("./model_trained_test.h5")
estimator_model = keras.estimator.model_to_estimator(keras_model_path="./model_trained_test.h5")

我设法用这个估算器做出预测

def input_function(features,labels=None,shuffle=False):
    input_fn = tf.estimator.inputs.numpy_input_fn(
        x={"values": features},
        y=labels,
        shuffle=shuffle
    )
    return input_fn
score = estimator_model.evaluate(input_function(X_test, labels=y_test.reshape(-1,1)))

为了将其导出到 SavedModel,我需要一个 serving_input_receiver_fn。我在互联网上没有找到我的情况的示例,这对我来说似乎很简单,所以我尝试了这个功能,然后我将模型保存在“here_are_estimators”文件夹中

feature_spec = {'values': tf.FixedLenFeature(9, dtype=tf.float32)}

def serving_input_receiver_fn():

    serialized_tf_example = tf.placeholder(dtype=tf.string,
                                           shape=[None],
                                           name='input_tensors')
    receiver_tensors = {'examples': serialized_tf_example}
    features = tf.parse_example(serialized_tf_example, feature_spec)
    return tf.estimator.export.ServingInputReceiver(features, receiver_tensors)

estimator_model.export_savedmodel("./here_are_estimators",
                                  serving_input_receiver_fn=serving_input_receiver_fn)

我的 input.json 看起来像这样

{"examples":[{"values":[[0.2,0.3,0.4,0.5,0.9,1.5,1.6,7.3,1.5]]}]}

我将生成文件的内容、一个变量文件夹和一个saved_model.pb文件上传到GCS的DEPLOYMENT_SOURCE目录下

当我尝试使用 gcloud 运行本地预测时:

gcloud ml-engine local predict --model-dir $DEPLOYMENT_SOURCE --json-instances="input.json" --verbosity debug --framework tensorflow

我有这个错误

cloud.ml.prediction.prediction_utils.PredictionError: Failed to run the provided model: Exception during running the graph: Cannot feed value of shape (1, 1) for Tensor 'input_tensors:0', which has shape '(?,)' (Error code: 2)

我猜我的 input.json 或 serving_input_receiver_fn 或两者都有问题?但我不知道是什么问题。如果有人能告诉我出了什么问题,将不胜感激:)

【问题讨论】:

    标签: python tensorflow keras google-cloud-ml


    【解决方案1】:

    您不应该尝试解析 tf.Example,因为您正在发送 JSON。试试这个导出:

    def serving_input_receiver_fn(): 
        inputs = {"values": tf.placeholder(dtype=tf.float32,
                                           shape=[None, 9],
                                           name='input_tensors')}
        return tf.estimator.export.ServingInputReceiver(inputs, inputs) 
    
    estimator_model.export_savedmodel("./here_are_estimators", serving_input_receiver_fn=serving_input_receiver_fn)
    

    输入应如下所示:

    {"values":[0.2,0.3,0.4,0.5,0.9,1.5,1.6,7.3,1.5]}
    

    还有一个更简洁的“速记”:

    [0.2,0.3,0.4,0.5,0.9,1.5,1.6,7.3,1.5]
    

    【讨论】:

    • 感谢您的帮助!这可行,但实际输入应该是: [0.2,0.3,0.4,0.5,0.9,1.5,1.6,7.3,1.5] 。也许您可以为未来的读者编辑您的答案。
    • @LouisDacquet:你指的是shortand还是“values”字典?我更新了绝对错误的 values dict,但我认为简写是正确的(如果我错了,请纠正我)。
    • 谢谢,但是这对于速记是一样的,正确的值是 [0.2,0.3,0.4,0.5,0.9,1.5,1.6,7.3,1.5]
    猜你喜欢
    • 2018-03-24
    • 1970-01-01
    • 2017-07-28
    • 1970-01-01
    • 2019-05-28
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多