2018-03-17 02:50

# TensorFlow中with as语句的使用问题

5

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.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))

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()
_

• 点赞
• 写回答
• 关注问题
• 收藏
• 复制链接分享
• 邀请回答

#### 1条回答

• 是这样的，with tf.Session() as sess语句相当于在这段代码开始时执行sess=tf.Session()，在结束时执行sess.close()
因此正确的写法应该是这样的

``````import tensorflow.examples.tutorials.mnist.input_data as input_data
import tensorflow as tf

#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))

init = tf.global_variables_initializer()

with tf.Session() as sess:
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"))

# 另外，此处你的feed_dict写错了，应该为y_，而不是y
output = sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})
print(output)

``````
点赞 2 评论 复制链接分享