[英]Prediction Failed on keras model in Google ML-Engine
我目前正在完成一個教程,其中涵蓋在 Google 的雲服務上使用基於 Keras 的模型及其 ML-Engine。
在這個階段,我的模型可以很好地用於本地預測等,並成功地將導出的模型放入 GC-bucket 中。 我也成功創建了谷歌雲ML-Engine模型。
當我嘗試從雲托管模型運行預測時,會產生以下錯誤。
錯誤:
C:\mydir>gcloud ml-engine predict --model=[mymodel] --json-instances=sample_input_prescaled.json
{
"error": "Prediction failed: Error during model execution: AbortionError(code=StatusCode.FAILED_PRECONDITION, details=\"Attempting to use uninitialized value dense_4/bias\n\t [[Node: dense_4/bias/read = Identity[T=DT_FLOAT, _class=[\"loc:@dense_4/bias\"], _output_shapes=[[1]], _device=\"/job:localhost/replica:0/task:0/cpu:0\"](dense_4/bias)]]\")"
}
我可以看到這個錯誤是指一個未初始化的值“dense_4”,它看起來像 Keras 模型中的最后一層,但我不確定這是否/為什么會導致過程中斷?
有沒有人對此錯誤消息的原因有所了解?
下面是我在教程中使用的 keras 模型,以及用於測試預測的 json 文件。
導出模型.py
import pandas as pd
import keras
from keras.models import Sequential
from keras.layers import *
import tensorflow as tf
training_data_df = pd.read_csv("sales_data_training_scaled.csv")
X = training_data_df.drop('total_earnings', axis=1).values
Y = training_data_df[['total_earnings']].values
# Define the model
model = Sequential()
model.add(Dense(50, input_dim=9, activation='relu'))
model.add(Dense(100, activation='relu'))
model.add(Dense(50, activation='relu'))
model.add(Dense(1, activation='linear'))
model.compile(loss='mean_squared_error', optimizer='adam')
# Create a TensorBoard logger
logger = keras.callbacks.TensorBoard(
log_dir='logs',
histogram_freq=5,
write_graph=True
)
# Train the model
model.fit(
X,
Y,
epochs=50,
shuffle=True,
verbose=2
)
# Load the separate test data set
test_data_df = pd.read_csv("sales_data_test_scaled.csv")
X_test = test_data_df.drop('total_earnings', axis=1).values
Y_test = test_data_df[['total_earnings']].values
test_error_rate = model.evaluate(X_test, Y_test, verbose=0)
print("The mean squared error (MSE) for the test data set is: {}".format(test_error_rate))
model_builder = tf.saved_model.builder.SavedModelBuilder("exported_model")
inputs = {
'input': tf.saved_model.utils.build_tensor_info(model.input)
}
outputs = {
'earnings': tf.saved_model.utils.build_tensor_info(model.output)
}
signature_def = tf.saved_model.signature_def_utils.build_signature_def(
inputs=inputs,
outputs=outputs,
method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME
)
model_builder.add_meta_graph_and_variables(
K.get_session(),
tags=[tf.saved_model.tag_constants.SERVING],
signature_def_map={
tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: signature_def
}
)
model_builder.save()
sample_input_prescaled.json
{ "輸入": [0.4999, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5] }
按照相同的教程,我發現發生了變化:
inputs = {
'input': tf.saved_model.utils.build_tensor_info(model.input)
}
outputs = {
'earnings': tf.saved_model.utils.build_tensor_info(model.input)
}
到:
inputs = {
'input': tf.compat.v1.saved_model.utils.build_tensor_info(model.input)
}
outputs = {
'earnings': tf.compat.v1.saved_model.utils.build_tensor_info(model.output)
}
導出模型時,為我解決了問題,不推薦使用前者。
希望這可以幫助。
帶有以下輸入的上述代碼對我有用。
X = np.random.rand(1000,9)
Y = np.random.rand(1000,1)
然后我使用了以下代碼。
from keras import backend as K
sess = K.get_session()
input_tensor = model.input
output_tensor = model.output
output_tensor.eval(feed_dict={input_tensor: np.random.rand(1,9)},
session=sess)
接下來,我導出模型。 在使用服務功能之前,請確保導出的模型適合您。
export_dir = ...
with tf.Session(graph=tf.Graph()) as sess:
tf.saved_model.loader.load(sess, [tag_constants.TRAINING], export_dir)
它奏效了。 然后,我在 task.py 中使用以下服務函數來提供 JSON 輸入,並再次起作用。
def json_serving_input_fn():
inputs = {}
for feat in 9:
inputs[feat.name] = tf.placeholder(shape=[None], dtype=feat.dtype)
return tf.estimator.export.ServingInputReceiver(inputs, inputs)
所以,我懷疑您的輸入沒有正確輸入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.