我正在尝试使用带有张量流的gcloud ml-engine,更确切地说,我想使用已经训练过的keras模型。
我设法用scikit学习模型做到这一点,但这里不一样......
首先,我用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引擎中使用它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文件上传到目录DEPLOYMENT_SOURCE中的GCS
当我尝试使用此命令使用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或者serve_input_receiver_fn或两者都有问题,但是我找不到什么。如果有人能告诉我有什么问题,我将不胜感激:)
您不应该尝试解析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]