理论上来说,我们是可以用tf.session.run() 或者tensor.eval()来取得tensor的value的value。同样,我们也可以用convert_to_tensor()将数组转换为tensor。然而,下面的这段代码,以及运行结果该怎么解释?
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() 以及convert_to_tensor()的方法,
WW = tf.convert_to_tensor(sess.run(w))
原理上来说,WW的value现在其实是等于w的value。但是为什么输出的结果差别很大?