关于python:如何在tensorflow中打印张量的值mnist_softmax.py

How to print the value of a tensor in tensorflow mnist_softmax.py

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

下面是代码:

1
2
3
4
5
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上找到。

以下是输出:

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

我也尝试过使用sess.run(y)y.eval(),但是在尝试时会收到如下错误:

1
2
3
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: ...


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

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

MNIST示例包含以下几行:

1
2
3
4
5
# 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() op是一种定义计算符号参数的方式:它本身没有任何值,但是它表示x必须是具有784列的浮点值矩阵。

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

1
2
3
4
5
6
7
def y(x):
    W = ...
    b = ...
    return softmax(matmul(x, W), b)

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

如何为参数指定值?在TensorFlow中,您可以通过输入占位符的值来实现此目的(就像在训练循环和准确性计算中一样):

1
2
3
4
5
6
# 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_定义为tf.placeholder()。由于技术原因,即使您输入占位符的值,也无法直接对其进行评估。但是,这样做并不是特别有用!取而代之的是,您可以仅打印将要输入的值。