A session may own resources, such as variables, queues, and readers. It is important to release these resources when they are no longer required.
with as语句在资源不再使用后才能使用,但是我在mnist初步入门的那个代码中使用后却报了一大堆错误,这是为啥?
import tensorflow.examples.tutorials.mnist.input_data as input_data
import tensorflow as tf
mnist = input_data.read_data_sets('MNIST_data/',one_hot = True)
#mnist.train
#mnist.test
#mnist.train.images [60000,784]
#mnist.train.labels [60000,10]
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("float",[None,10])
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
init = tf.global_variables_initializer()
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})
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,"float"))
output = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels})
print(output)
sess.close()
_
斜体部分 我用with tf.Session() as sess:…………代替后报错了,
是不是因为之前用了sess = tf.Sesssion()的缘故??
还有 , 像在上面代码中多次用到sess.run(),是不是不能随便用with as语句了呢?