三、会话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))

输出:python

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

11

②会话资源

会话拥有不少资源,如tf.Variable,tf.QueueBase和tf.ReaderBase等,会话结束后须要进行资源释放后端

  • 使用方法 

   一、sess = tf.Session(),sess.run(),sess.close()app

   二、使用上下文管理器测试

      with tf.Session() as sess:this

        sess.run()spa

 

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)

输出:code

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方法

相关文章
相关标签/搜索