我的训练好的神经网络无法正常工作。我想将一个numpy数组(本质上是一张图片)输入到我的训练网络中。
with tf.Session() as sess: # 从文件中恢复图
with tf.gfile.FastGFile(graph_path, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(graph_def, name='')
softmax_tensor = sess.graph.get_tensor_by_name('y_pred:0')
predictions = sess.run(softmax_tensor, {'DecodeJpeg/contents:0': image_data})
我总是得到这个错误:
TypeError: 无法将feed_dict的键解释为张量:名称’DecodeJpeg/contents:0’指的是一个不存在的张量。操作’DecodeJpeg/contents’在图中不存在。
我尝试了许多不同的键来解决这个问题,但始终无法正确设置。我使用数据集API训练了网络,这意味着我没有可以填充的tf.placeholder。相反,网络是通过数据集上的迭代器来接收张量对象的输入。tfrecord文件是使用谷歌的这个脚本创建的
我的模型函数的开始部分:
input_layer = tf.reshape(features["image"], [-1, _DEFAULT_IMAGE_SIZE, _DEFAULT_IMAGE_SIZE, 3])
结尾部分的摘录:
predictions = { # 生成预测(用于PREDICT和EVAL模式)
"classes": tf.argmax(input=logits, axis=1),
# 将`softmax_tensor`添加到图中。它用于PREDICT和`logging_hook`。
"probabilities": tf.nn.softmax(logits, name="y_pred")}
if mode == tf.estimator.ModeKeys.PREDICT:
return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)
# 计算损失(用于TRAIN和EVAL模式)
onehot_labels = tf.one_hot(indices=tf.cast(labels, tf.int32), depth=2)
loss = tf.losses.softmax_cross_entropy(onehot_labels=onehot_labels, logits=logits)
这是拓扑结构
我如何获得这些预测/如何将图片输入到网络中?
回答:
你可以为你的输入层命名,然后像处理softmax张量那样通过名称获取它,然后将你的numpy数组输入进去。看起来像这样:
# 首先,为你的输入张量命名
input_layer = tf.reshape(features["image"], [-1, _DEFAULT_IMAGE_SIZE, _DEFAULT_IMAGE_SIZE, 3], name='input_layer')
...
predictions = sess.run('y_pred:0', {'input_layer:0': image_data})
只要image_data的形状是[1, _DEFAULT_IMAGE_SIZE, _DEFAULT_IMAGE_SIZE, 3],这应该可以工作。
关于为什么你无法通过名称访问DecodedJpeg张量的解释是,tf.Dataset操作不在主图中。