首页 > 解决方案 > 在 google ml-engine 中使用经过训练的 keras 模型

问题描述

我正在尝试将 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 或两者都有问题?但我不知道是什么。如果有人能告诉我出了什么问题,将不胜感激:)

标签: pythontensorflowkerasgoogle-cloud-ml

解决方案


您不应该尝试解析 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]

推荐阅读