tensorflow - 在 Google ML Engine 上以 .model .json 和 .h5 形式部署 Keras/Tensorflow CNN 的最简单方法是什么?
问题描述
我无法使用 Keras CNN (VGGNet) 模型执行预测。它是一个多类分类,以 96x96x3 的图像张量作为输入,产生大小为 114(类)的概率向量。它被 Google ML Engine 接受为有效模型,并且预测输入 image.json 格式正确(与张量有一行),但调用 gcloud ml-engine predict 会出现以下错误:
"error": "Prediction failed: Error during model execution: AbortionError(code=StatusCode.INVALID_ARGUMENT, details=\"您必须为占位符张量 'Placeholder_1' 提供一个值,其 dtype 为 float 和 shape [?,114]\n\t [[节点: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 类,以及您是否没有正确更改形状;因为 tf.Variable 会限制您在创建变量后更改其形状的能力。
如果不是这种情况,请提供有关您的模型的更多详细信息。
推荐阅读
- python - pyqtdeploy 问题与如何进行
- database - vb.net在access数据库中重命名表
- c++ - 如何在不需要 if 测试的情况下让 C++ signalling_nan() 抛出异常?
- javascript - 引导 hidden.bs.collapse 事件在 collapse('show') 和 collapse('hide') 上触发
- matlab - 如何解决 Matlab 函数 csaps 的非平滑结果
- android - 在 Android 中为 diffie-hellman 生成密钥需要太长时间
- google-sheets - Google 表格 IMPORTHTML“无法获取数据”
- azure - Azure Synapse Analytics - 数据流 - 输出到多个文件
- javascript - React - 编写函数以获得最佳性能的最佳方法是什么
- ios - 当没有超类初始化适合时如何初始化子类