Tensorflow: 会话。Session()与InteractiveSession()

Tensorflow中利用会话的方式对已经设计的计算模型进行运算,而会话一般有两种种应用模式:tf.Session(),tf.InteractiveSession()

第一种:方式一

import tensorflow as tf

a=tf.constant([1.0,2.0],name='a')
# 创建一个会话。
sess = tf.Session()
# 使用这个创建好的会话来得到关心的运算的结果
print(sess.run(a))
# 关闭会话释放本次运行的资源
sess.close()

第一种:方式二

import tensorflow as tf

a=tf.constant([1.0,2.0],name='a')

# 创建一个会话。
with tf.Session() as sess:
    print(sess.run(a))
# 不需要再调用“Session.close()”函数来关闭会话。


第二种:

在交互环境下,通过设置默认会话的方法来获取张量的取值更加方便。

 
 
import tensorflow as tf

a=tf.constant([1.0,2.0],name='a')

# 使用InteractiveSession代替Session类,使用Tensor.eval()和Operation.run() 方法
# 代替 Session.run()。这样可以避免使用一个变量来持有会话。
sess = tf.InteractiveSession()
print(a.eval())
sess.close()

 
 

以上结果都为:

扫描二维码关注公众号,回复: 1781752 查看本文章



猜你喜欢

转载自blog.csdn.net/lanluyug/article/details/79755229