我从一个.pb
文件中加载了一个AlexNet,并试图在推理模式下运行它,但是出现了这个错误:
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'graph_def/Placeholder' with dtype float and shape [?,227,227,3]
[[Node: graph_def/Placeholder = Placeholder[dtype=DT_FLOAT, shape=[?,227,227,3], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
这是我的代码:
import tensorflow as tf
from tensorflow.python.platform import gfile
import numpy as np
import cv2
#mean of imagenet dataset in BGR
imagenet_mean = np.array([104., 117., 124.], dtype=np.float32)
image = cv2.imread("test.jpg")
GRAPH_PB_PATH = 'alexnet_frozen.pb'
#placeholder for input and dropout rate
x = tf.placeholder(tf.float32, [1, 227, 227, 3])
keep_prob = tf.placeholder(tf.float32)
with tf.Session() as sess:
with gfile.FastGFile(GRAPH_PB_PATH, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
sess.graph.as_default()
tf.import_graph_def(graph_def, name='graph_def')
# Initialize all variables
sess.run(tf.global_variables_initializer())
# Convert image to float32 and resize to (227x227)
img = cv2.resize(image.astype(np.float32), (227, 227))
# Subtract the ImageNet mean
img -= imagenet_mean
# Reshape as needed to feed into model
img = img.reshape((1, 227, 227, 3))
softmax_op = sess.graph.get_operation_by_name("graph_def/Softmax")
# Run the session and calculate the class probability
probs = sess.run(softmax_op, feed_dict={x: img, keep_prob: 1})
以某种方式,除了我定义的两个占位符外,还有第三个占位符,其形状为[-1, 227, 227, 3]
。在运行时,我可以在会话图的nodes_by_id
列表中看到它。但是我不知道它来自哪里,或者是什么导致我的错误。