尝试使用以下代码设置Gcloud ML引擎:
import numpy as np
import tensorflow as tf
x = tf.placeholder('float', shape=[None, 3], name='x')
w = tf.Variable(tf.zeros([3, 2]))
y = tf.nn.softmax(tf.matmul(x, w), name='y')
sess = tf.Session()
sess.run(tf.global_variables_initializer())
tensor_info_x = tf.saved_model.utils.build_tensor_info(x)
tensor_info_y = tf.saved_model.utils.build_tensor_info(y)
prediction_signature = (
tf.saved_model.signature_def_utils.build_signature_def(
inputs={'inputs': tensor_info_x},
outputs={'scores': tensor_info_y},
method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME)
)
export_path = './test_exports'
builder = tf.saved_model.builder.SavedModelBuilder(export_path)
legacy_init_op = tf.group(tf.tables_initializer(), name='legacy_init_op')
builder.add_meta_graph_and_variables(
sess, [tf.saved_model.tag_constants.SERVING],
signature_def_map={
'predict_images':
prediction_signature
},
legacy_init_op=legacy_init_op)
builder.save()
我用于预测的示例输入JSON文件是:
{ "inputs" : [[ 0.32439028, 0.07830289, 0.30881251], [ 0.32439028, 0.07830289, 0.30881251]] }
如您所见,输入数组的形状为(2,3)。但是,当将其作为模型的输入时,我面临一个错误:
不能为Tensor u'x提供形状值(1,2,3):0',它有 shape'(?,3)'(错误代码:2)
为了进一步测试,在给出大小(1,3)的输入时,模型完美地工作。知道如何添加额外的维度吗?
编辑:
用于测试的命令:
gcloud ml-engine local predict --model-dir=./test_exports --json-instances inputs.json
答案 0 :(得分:0)
ML Engine预测一批输入,而不仅仅是一个。因此,您应将服务输入占位符更改为[无,2,3]
顺便说一下,让你的模型流程批量处理也会更好。
答案 1 :(得分:0)
为任何工作的人发布解决方案。
以问题中所示的例子为例,ml引擎给模型的输入形状为[1,N,m],其中N是输入数,m是特征尺寸。因此,要将输入转换为此格式,请使用tf.squeeze()
,如下所示:
x = tf.placeholder('float', shape=[1, None, 3], name='x')
x_exp = tf.squeeze(x, axis=0)
现在您可以使用x_exp
进行进一步处理。