TensorFlow中Session的使用

TensorFlow中Session的使用

TensorFlow中只有让Graph(计算图)上的节点在Session(会话)中执行,才会得到结果。Session的开启涉及真实的运算,因此比较消耗资源。在使用结束后,务必关闭Session。

import tensorflow as tf
a = tf.constant(1, dtype=tf.int8)
b = tf.constant(2, dtype=tf.int8)
res= a + b
sess = tf.Session()
sess.run(res)#执行运算
sess.close()#手动关闭session

上述这种方式需要手动关闭Session,比较繁琐。我们可以采用另一种形式,可以不用手动关闭会话。实质就是指定Session的有效范围,离开有效范围自动失效。

import tensorflow as tf
a = tf.constant(1, dtype=tf.int8)
b = tf.constant(2, dtype=tf.int8)
res= a + b
with tf.Session() as sess:#运算结束后session自动关闭
    sess.run(res)

有的开发者可能会认为每次都要sess.run比较麻烦,我们可以使用张量的eval()方法:

import tensorflow as tf
a = tf.constant(1, dtype=tf.int8)
b = tf.constant(2, dtype=tf.int8)
res= a + b
with tf.Session() as sess:#运算结束后session自动关闭
    print res.eval()

我们也可以在运算的时候指定默认的Session,例如:

import tensorflow as tf
a = tf.constant(1, dtype=tf.int8)
b = tf.constant(2, dtype=tf.int8)
res= a + b
sess = tf.InteractiveSession()
print sess.eval()#如果调用tf.Session(),则该语句必须是sess.eval(session=sess),因为默认Session需要指定

猜你喜欢

转载自blog.csdn.net/androidchanhao/article/details/79595004