【深度学习】TensorFlow——理解会话

 1 # 会话---执行op的类
 2 # 本质:连接前台程序与底层C++代码的纽带
 3 # 两种形式
 4 # tf.Session() :用于完整的程序中
 5 # tf.InteractiveSession() :应用于交互环境
 6 
 7 # 会话使用--完整流程
 8 # 1、会话初始化
 9 # __init__
10 # 2、会话执行
11 # ss.run()
12 # 3、关闭会话
13 # ss.close()
14 
15 # 不使用上面的方式,使用with托管
16 import tensorflow as tf
17 
18 con_a = tf.constant(3, name="con_a")
19 con_b = tf.constant(3, name="con_b")
20 
21 con_sum = tf.add(con_a, con_b, name="add")
22 
23 print("con_a:", con_a)
24 print("con_b:", con_b)
25 print("con_sum:", con_sum)
26 
27 # 构建一个占位op
28 plt = tf.placeholder(shape=[2, 2], dtype=tf.int32)
29 hh = tf.placeholder(shape=[2, 2], dtype=tf.int32)
30 
31 # c = 1.0
32 # a = "hello world"
33 
34 # 开启会话 执行图
35 # 会话初始化的时候
36 # 参数 target : 可以指定云端的设备进行执行会话
37 # 参数 graph :可以指定想要执行的图
38 # 参数 config: 可以打印设备信息
39 with tf.Session() as ss:
40     # fetches 参数
41     # print("运行结果:
", ss.run(con_sum))
42     # print("运行结果:
", ss.run([con_a,con_b,con_sum]))
43     # print("运行结果:
", ss.run((con_a,con_b,con_sum)))
44     # run 必须是一个op 或者是一个op列表、或者op元组
45     # feed_dict  跟占位op一块使用对 占位op进行填值
46     print(ss.run([plt, hh], feed_dict={plt: [[1, 2], [3, 4]], hh: [[1, 2], [3, 4]]}))
47     # print("运行结果:
", ss.run(c)) # 错误的
48     # ss.run(a) # 错误的
49 
50 # 如果安装GPU 的同学-设置使用GPU
51 # tf.DeviceSpec(device_type="GPU", device_index=0)
52 
53 # with tf.Session(config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=True)) as ss:
54 #     print("运行结果:
", ss.run(con_sum))
原文地址:https://www.cnblogs.com/Tree0108/p/12116292.html