Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Tensorflow中的'tf.estimator.estimator'保存的模型进行预测_Tensorflow_Tensorflow Estimator - Fatal编程技术网

用Tensorflow中的'tf.estimator.estimator'保存的模型进行预测

用Tensorflow中的'tf.estimator.estimator'保存的模型进行预测,tensorflow,tensorflow-estimator,Tensorflow,Tensorflow Estimator,我正在使用tf.estimator.estimator来训练一个模型: def model_fn(特性、标签、模式、参数、配置): 输入图像=特征[“输入图像”] 评估度量操作={} 预测={} #创建模型 使用tf.name_范围('Model'): W=tf.Variable(tf.zero([784,10]),name=“W”) b=tf.变量(tf.零([10]),name=“b”) logits=tf.nn.softmax(tf.matmul(输入图像,W,name=“matmul”)

我正在使用
tf.estimator.estimator
来训练一个模型:

def model_fn(特性、标签、模式、参数、配置):
输入图像=特征[“输入图像”]
评估度量操作={}
预测={}
#创建模型
使用tf.name_范围('Model'):
W=tf.Variable(tf.zero([784,10]),name=“W”)
b=tf.变量(tf.零([10]),name=“b”)
logits=tf.nn.softmax(tf.matmul(输入图像,W,name=“matmul”)+b,name=“logits”)
损失=无
列车运行=无
如果模式!=tf.estimator.ModeKeys.PREDICT:
损失=tf.reduce_平均值(tf.nn.softmax_交叉_熵_与逻辑(标签=标签,逻辑=逻辑))
列车运行=tf.contrib.layers.Optimization\u损耗(损耗=损耗,
global\u step=tf.contrib.framework.get\u global\u step(),
学习率=参数[“学习率”],
优化器=参数[“优化器”])
#添加预测
class=tf.as_字符串(tf.argmax(输入=logits,axis=1,name=“class”))
使用tf.name_范围(“预测”):
预测[“logits”]=logits
预测[“类”]=类
export_outputs={“classes”:tf.estimator.export.ClassificationOutput(classes=classes)}
export_outputs={“classes”:tf.estimator.export.PredictOutput({“labels”:classes})}
spec=tf.estimator.estimator spec(mode=mode,
预测=预测,
损失=损失,
列车运行=列车运行,
评估度量操作=评估度量操作,
导出输出=导出输出,
培训主任挂钩=无,
培训挂钩=无,
脚手架(无)
退货规格
def输入_fn(数据集,n=10):
返回dataset.images[:n],dataset.labels[:n]
模型参数={“学习率”:1e-3,
“优化器”:“Adam”}
#run\u path=os.path.join(运行\u path,datetime.now().strftime(“%Y-%m-%d-%H-%m-%S”))
run\u path=os.path.join(运行路径“run1”)
如果os.path.存在(运行路径):
shutil.rmtree(运行路径)
estimator=tf.estimator.estimator(model_fn=model_fn,model_dir=run_path,params=model_params)
#训练
输入值=λ:输入值(mnist.train,n=15)
列车估计器(输入=输入,步长=1000)
训练期间正确保存模型和重量

现在我想在另一个脚本中重新加载模型+权重,以便进行预测

但是我不知道如何指定输入,因为我在
model\u fn
函数中没有对它的引用

#获取一些数据进行预测
输入数据=列表测试图像[:5]
tf.reset_default_graph()
run\u path=os.path.join(运行路径“run1”)
#加载模型(图形)
输入检查点=os.path.join(运行路径“model.ckpt-1000”)
saver=tf.train.import_meta_图形(输入检查点+'.meta',清除设备=True)
#恢复重量
sess=tf.InteractiveSession()
saver.restore(sess、输入检查点)
graph=sess.graph
#获取要计算以进行预测的op
predict\u op=graph.通过名称(“predicts/class”)获取操作
#预测=sess.run(预测操作、馈送指令=??)
下面是返回的
图形。获取集合(“变量”)

然后我尝试加载模型并进行预测,但我不知道如何将我的numpy图像输入模型:

preds=sess.run(“class”,feed\u dict={“input\u image”:input\u data})
以及例外错误:

/home/hadim/local/conda/envs/ws/lib/python3.6/site-packages/tensorflow/python/client/session.py运行(self、fetches、feed、dict、options、run\u元数据)
776尝试:
777结果=self.\u运行(无、取数、输入、选项、,
-->778运行(元数据)
779如果运行\u元数据:
780 proto_data=tf_session.tf_GetBuffer(run_metadata_ptr)
/home/hadim/local/conda/envs/ws/lib/python3.6/site-packages/tensorflow/python/client/session.py in_运行(self、handle、fetches、feed_dict、options、run_元数据)
931例外情况除外,如e:
932 raise TypeError('无法将feed_dict键解释为张量:'
-->933+e.args[0])
934
935如果存在(副进纸值,操作张量):
TypeError:无法将feed_dict键解释为张量:“input_image”名称看起来像(无效)操作名称,而不是张量。张量名称的形式必须为“:”。

输入张量的名称可能是
input\u image:0

您可以通过调用以下命令列出已保存模型的签名:

打印(estimator.signature\u def[tf.已保存的\u模型.签名\u常数.默认值\u服务\u签名\u def\u密钥])


这应该列出预期的输入/输出张量。

我正在使用tf.contrib.learn.Estimator。 如我所见,语法和方法签名几乎相同,因此我认为差异与几个Tensorflow版本有关。 因此,您可以像往常一样使用以下内容创建估计器

estimator = learn.Estimator(
         model_fn=your_model,
         model_dir="tmp",
         config=tf.contrib.learn.RunConfig(
             save_checkpoints_steps=10,
             save_summary_steps=10,
             save_checkpoints_secs=None
         )
     )
然后,您以estimator.fit(输入函数=input函数,步长=100)的方式进行训练。

然后您可以进行预测调用

estimator .predict(prediction)
莫特,有一个技巧,和Tensorflow的有关。调用
predict
无法正确初始化估计器,因此需要调用

estimator.evaluate(x=prediction, y=label_array, steps=1)
在调用
预测之前


希望,这有帮助。

至于类型错误,我用这种方法解决

首先,命名占位符:

feature_spec = {"input_image": tf.placeholder(dtype=tf.float32, shape=[None, 784], name='input_image')}
然后你可以这样使用它:

feed_dict={"input_image:0": input_data}
with tf.Session(graph=tf.Graph()) as sess:
    meta_graph_def = tf.saved_model.loader.load(sess, [tf.saved_model.tag_constants.SERVING], model_path)
    signature = meta_graph_def.signature_def
    x_tensor_name = signature['classes'].inputs['input_image'].name
    y_tensor_name = signature['classes'].outputs['labels'].name
    x = sess.graph.get_tensor_by_name(x_tensor_name)
    y = sess.graph.get_tensor_by_name(y_tensor_name)
    predictions = sess.run(y, {x: mnist.test.images[:5]})
希望它能帮助别人


编辑

在这个问题中,在
estimator.export\u savedmodel(…)
您可以这样做:

feed_dict={"input_image:0": input_data}
with tf.Session(graph=tf.Graph()) as sess:
    meta_graph_def = tf.saved_model.loader.load(sess, [tf.saved_model.tag_constants.SERVING], model_path)
    signature = meta_graph_def.signature_def
    x_tensor_name = signature['classes'].inputs['input_image'].name
    y_tensor_name = signature['classes'].outputs['labels'].name
    x = sess.graph.get_tensor_by_name(x_tensor_name)
    y = sess.graph.get_tensor_by_name(y_tensor_name)
    predictions = sess.run(y, {x: mnist.test.images[:5]})

我使用
tensorflow.contrib.predictor成功预测