在 Google ML Engine 上以 .model .json 和 .h5 形式部署 Keras/Tensorflow CNN 的最简单方法是什么?

What is the simplest way of deploying a Keras/Tensorflow CNN available as .model .json and .h5 on Google ML Engine?

我在使用 Keras CNN (VGGNet) 模型执行预测时遇到问题。它是一个多重 class-class 化,将 96x96x3 图像张量作为输入,产生大小为 114 (classes) 的概率向量。它被 Google ML Engine 接受为有效模型并且预测输入 image.json 格式正确(一行带有张量),但调用 gcloud ml-engine predict 会出现以下错误:

"error": "Prediction failed: Error during model execution: AbortionError(code=StatusCode.INVALID_ARGUMENT, details=\"You must feed a value for placeholder tensor 'Placeholder_1' with dtype float and shape [?,114]\n\t [[Node: Placeholder_1 = Placeholderdtype=DT_FLOAT, shape=[?,114], _device=\"/job:localhost/replica:0/task:0/device:CPU:0\"]]\")"

我的预测输入image.json包含

{"x": [ [ [ [ 1.0, 1.0, 1.0 ], ..., [ 1.0, 1.0, 1.0 ] ] ] ]}

生成save_model.pb文件的代码是

def build_graph(x):

  model = load_model("my-model.model")
  labels = pickle.loads(open("labels.pickle", "rb").read())

  # classify the input image
  probabilities = model.predict(x)

  outputs = tf.convert_to_tensor(probabilities)
  saver = tf.train.Saver()

  return outputs, saver

image_path = "testset/testimage.png"
# preprocess the image for classification
image = cv2.imread(image_path)
image = cv2.resize(image, (96, 96))
image = image.astype("float") / 255.0
image = img_to_array(image)
image = np.expand_dims(image, axis=0)

# Do training
with tf.Graph().as_default() as prediction_graph:
  x = image
  outputs = tf.placeholder(tf.float32, shape=[None, 114])
  outputs, saver = build_graph(x)

with tf.Session(graph=prediction_graph) as sess:
  sess.run([tf.local_variables_initializer(), tf.tables_initializer()])
  x = tf.placeholder(tf.float32, shape=[None, 96, 96, 3])
  sess.run(outputs, {x: image})

# export model
export_dir = "export3"
tf.saved_model.simple_save(
    sess,
    export_dir,
    inputs={"x": tf.placeholder(tf.float32, shape=[None, 96, 96, 3])},
    outputs={"y": tf.placeholder(tf.float32, shape=[None, 114])}
)

我在这里错过了什么?有没有更简单的工作方式?该模型还可以作为 .json 和由

生成的 .h5 文件提供
# serialize model to JSON
model_json = model.to_json()
with open("my-model.json", "w") as json_file:
json_file.write(model_json)
# serialize weights to HDF5
model.save_weights("my-model.h5")

感谢您的帮助!

不知何故,[None, 114] 的预期输出形状未实现。

我了解到在expand_dims之后,图像的形状是[1,96,96]。但是由于我不知道你的模型中有什么,所以我不知道你如何获得大小为 114 的概率向量。

考虑到之前的说明,一个模糊的建议是检查您是否在模型中使用 tf.Variable class 以及您是否没有正确更改形状;因为 tf.Variable 限制了您在创建变量后更改其形状的能力。

如果不是这种情况,请提供有关您的模型的更多详细信息。