尽管许多地方声称我们可以通过tf.session.run()或tensor.eval()获得张量值,但我们如何解释以下代码。
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
sess = tf.InteractiveSession()
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)
tf.global_variables_initializer().run()
XX=x
#WW = tf.convert_to_tensor(sess.run(w))
WW = w
print("WW==w?",sess.run(w)==sess.run(WW))
YY = tf.nn.softmax(tf.matmul(XX,WW)+b)
YY_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy_ = tf.reduce_mean(-tf.reduce_sum(YY_ * tf.log(YY), reduction_indices=[1]))
train_step_ = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy_)
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
train_step.run({x: batch_xs, y_: batch_ys})
train_step_.run({x: batch_xs, YY_: batch_ys})
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
correct_prediction_ = tf.equal(tf.argmax(YY, 1), tf.argmax(YY_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
accuracy_ = tf.reduce_mean(tf.cast(correct_prediction_, tf.float32))
print(accuracy.eval({x:mnist.test.images, y_:mnist.test.labels}))
print(accuracy_.eval({XX:mnist.test.images, YY_:mnist.test.labels}))
如果我保持WW = w。好的,可以。我得到了预期的结果。但是,如果我想通过sess.run()获取张量的值,然后通过tf.convert_to_tensor()将此数组转换为张量,尽管“ WW = w”会输出所有“ True”值,但我不会获得预期值。
这种现象背后的真正原因是什么,我该如何解决这个问题。