如何在张量流mnist_softmax.py中打印张量值

时间:2016-05-06 03:08:56

标签: python tensorflow

我刚尝试在TensorFlow 0.8中运行mnist_softmax.py。 我想在模型测试步骤之前观察yy_的值。

以下是代码:

print(y)  # added by me
print(y_)  # added by me

# Test trained model
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))

完整的代码可在GitHub上找到。

以下是输出:

Tensor("Softmax:0", shape=(?, 10), dtype=float32)
Tensor("Placeholder_1:0", shape=(?, 10), dtype=float32)

我还尝试使用sess.run(y)y.eval(),但是当我尝试使用时出现这样的错误:

tensorflow.python.framework.errors.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype float
         [[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
Caused by op u'Placeholder', defined at: ...

1 个答案:

答案 0 :(得分:4)

TL; DR: yy_张量均取决于tf.placeholder()操作,因此他们要求您提供评估它们时的输入值。您可以通过输入一批输入来打印一批输入数据上的softmax输出:

batch_xs, _ = mnist.train.next_batch(100)
print(y.eval({x: batch_xs}))

MNIST示例包含以下行:

# Create the model
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)

请注意,您尝试打印的第一个张量yx的函数,其定义为tf.placeholder()tf.placeholder()操作是一种为计算定义符号argument的方法:它本身没有任何值,但它表示x必须是浮点矩阵带有784列的点值。

在不为y提供值的情况下运行/评估x就像编写以下Python函数并在没有所有参数的情况下调用它一样:

def y(x):
    W = ...
    b = ...
    return softmax(matmul(x, W), b)

# This would fail with an error.
print(y())

如何为参数指定值?在TensorFlow中,您可以通过提供占位符的值(例如training loopaccuracy calculation)来执行此操作:

# Get a batch of input data to feed to the computation.
batch_xs, _ = mnist.train.next_batch(100)

print(sess.run(y, feed_dict={x: batch_xs}))
# or
print(y.eval({x: batch_xs}))

张量y_ 定义为 a tf.placeholder()。由于技术原因,您无法直接评估占位符,即使您为其提供了值。但是,这样做并不是特别有用!相反,您只需打印您可能已经输入的值。