3、会话tf.Session()

①tf.Session()

运行TensorFlow操作图的类,使用默认注册的图(可以指定运行图)

 1 import os
 2 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' #去掉警告,将警告级别提升
 3 
 4 # 创建一张图
 5 g = tf.Graph()
 6 
 7 with g.as_default(): #作为默认图
 8     c = tf.constant(11)
 9     print(c.graph)
10 
11 a = tf.constant(2)   #定义一个常量
12 b = tf.constant(4)
13 sum = tf.add(a,b)    #加法操作
14 gr = tf.get_default_graph()
15 
16 #一个会话只能使用一张图,默认是注册图,即图gr
17 # with tf.Session() as sess:  #上下文管理
18 #     print(sess.run(sum))   #run运行加法op
19 #     print(sess.run(c))  # (Tensor Tensor("Const:0", shape=(), dtype=int32) is not an element of this graph.)
20 
21 #在会话中指定图运行
22 with tf.Session(graph=g) as sess:  #上下文管理
23     print(sess.run(c))

输出:

<tensorflow.python.framework.ops.Graph object at 0x000002486656CD30>

11

②会话资源

会话拥有很多资源,如tf.Variable,tf.QueueBase和tf.ReaderBase等,会话结束后需要进行资源释放

  • 使用方法 

   1、sess = tf.Session(),sess.run(),sess.close()

   2、使用上下文管理器

      with tf.Session() as sess:

        sess.run()

tensorflow可以分为前端系统(定义程序的图的结构)和后端系统(运算图的结构,用cpu,gpu进行运算)

会话的功能:

  • 运算图的结构
  • 分配资源计算
  • 掌握资源(变量的资源,队列,线程),所以一旦会话结束,所有的资源将不能再使用

③打印设备信息

config=tf.ConfigProto(log_device_placement=True)
with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess:  #上下文管理
    # print(sess.run(sum))   #run运行加法op
    print("a.graph:",a.graph)

输出:

Device mapping:
/job:localhost/replica:0/task:0/device:GPU:0 -> device: 0, name: GeForce GTX 1650, pci bus id: 0000:01:00.0, compute capability: 7.5

④交互式操作  tf.InteractiveSession()

在命令行进行测试时使用

只要有会话的上下文环境,就可以使用操作方便的eval()

1 a = tf.constant(2)   #定义一个常量
2 b = tf.constant(4)
3 sum1 = tf.add(a,b)    #加法操作
4 
5 with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess:  #上下文管理
6     print(sess.run(sum1))   #run运行加法op
7     print(sum1.eval())

输出:

Device mapping:
/job:localhost/replica:0/task:0/device:GPU:0 -> device: 0, name: GeForce GTX 1650, pci bus id: 0000:01:00.0, compute capability: 7.5
Add: (Add): /job:localhost/replica:0/task:0/device:GPU:0
Const: (Const): /job:localhost/replica:0/task:0/device:GPU:0
Const_1: (Const): /job:localhost/replica:0/task:0/device:GPU:0
6
6

⑤会话中的run方法

猜你喜欢

转载自www.cnblogs.com/pengzhonglian/p/11838890.html
今日推荐