我遵循本教程:
https://www.tensorflow.org/versions/r0.9/tutorials/mnist/beginners/index.html#mnist-for-ml-beginners
我希望能够做的是传入一个测试图像x - 作为一个numpy数组,并查看最终的softmax分类值 - 可能是另一个numpy数组。我在网上找到的关于测试张量流模型的一切都可以通过传入测试值和测试标签以及输出精度来实现。在我的例子中,我想根据测试值输出模型标签。
这就是我想要的: 导入张量流为tf 导入numpy为np 来自skimage导入颜色,io
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
#so now its trained successfully, and W and b should be the stored "model"
#now to load in a test image
greyscale_test = color.rgb2gray(io.imread('4.jpeg'))
greyscale_expanded = np.expand_dims(greyscale_test,axis=0) #now shape (1,28,28)
x = np.reshape(greyscale_expanded,(1,784)) #now same dimensions as mnist.train.images
#initialize the variable
init_op = tf.initialize_all_variables()
#run the graph
with tf.Session() as sess:
sess.run(init_op) #execute init_op
print (sess.run(feed_dict={x:x})) #this is pretty much just a shot in the dark. What would go here?
现在它导致了这个:
TypeError Traceback (most recent call last)
<ipython-input-116-f232a17507fb> in <module>()
36 sess.run(init_op) #execute init_op
---> 37 print (sess.run(feed_dict={x:x})) #this is pretty much just a shot in the dark. What would go here?
TypeError: unhashable type: 'numpy.ndarray'
因此,在训练时,sess.run会传递一个train_step和一个feed_dict。当我试图评估张量x时,这是否会出现在饲料字典中?我甚至会使用sess.run?(似乎我必须),但train_step会是什么?有没有&#34; test_step&#34;或&#34; evaluate_step&#34;?
答案 0 :(得分:3)
您正在获取TypeError
,因为您使用(可变)numpy.ndarray
作为词典的键,但键应为tf.placeholder
且值为{{ {1}}数组。
以下调整可解决此问题:
numpy
如果您只想对模型进行推理,则会打印带有预测的x_placeholder = tf.placeholder(tf.float32, [None, 784])
# ...
x = np.reshape(greyscale_expanded,(1,784))
# ...
print(sess.run([inference_step], feed_dict={x_placeholder:x}))
数组。
如果您想评估您的模型(例如计算准确度),您还需要输入相应的地面实况标签numpy
,如下所示:
y
在您的情况下,accuracy = sess.run([accuracy_op], feed_dict={x_placeholder:x, y_placeholder:y}
可以定义如下:
accuracy_op
此处,correct_predictions = tf.equal(tf.argmax(predictions, 1), tf.cast(labels, tf.int64))
accuracy_op = tf.reduce_mean(tf.cast(correct_predictions, tf.float32))
是模型的输出张量。
答案 1 :(得分:0)
你的tf.Session.run op需要一个提取 tf.Session.run(fetches,feed_dict = None,options = None,run_metadata = None)
https://www.tensorflow.org/versions/r0.9/api_docs/python/client.html#session-management
print(sess.run(train_step,feed_dict = {x:x}))但是它还需要一个y_的feed_dict
你的意思是: