会话
- 开启会话
- tf.Session用于完整的程序中
- tf.InteractiveSession用于交互式上下文中的tensorflow
- 查看张量的值
- 都必须在会话里面
- c_new_value=new_sess.run(c_new)
- print("c_new_value: ",c_new_value)
- print("a_new_value: ",a_new.eval())
-
1 def session_demo(): 2 """ 3 会话的演示 4 :return: 5 """ 6 a_t = tf.constant(2, name="a_t") 7 b_t = tf.constant(3, name="b_t") 8 c_t = tf.add(a_t, b_t, name="c_t") 9 print("a_t: ", a_t) 10 print("b_t: ", b_t) 11 print("tensorflow加法运算的结果: ", c_t) 12 13 # 查看默认图 14 # 方法1:调用方法 15 default_g = tf.compat.v1.get_default_graph() 16 print("default_g: ", default_g) 17 # 方法2:查看属性 18 print("a_t的图属性: ", a_t.graph) 19 print("c_t的图属性: ", c_t.graph) 20 21 # 开启会话 22 with tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(allow_soft_placement=True,log_device_placement=True)) as sess: 23 # c_t_value = sess.run(c_t) 24 # print("c_t_value: ", c_t_value) 25 abc = sess.run([a_t,b_t,c_t]) 26 print("abc: ",abc) 27 print("sess的图属性: ", sess.graph) 28 return None 29 30 31 def feed_demo(): 32 """ 33 feed操作 34 :return: 35 """ 36 a=tf.compat.v1.placeholder(dtype=tf.float32) 37 b=tf.compat.v1.placeholder(dtype=tf.float32) 38 sum_ab=tf.add(a,b) 39 print("a: ",a) 40 print("b: ",b) 41 print("sum_ab: ",sum_ab) 42 43 with tf.compat.v1.Session() as sess: 44 sum_ab_value=sess.run(sum_ab,feed_dict={a:3.9,b:3.5}) 45 print("sum_ab_value: ",sum_ab_value) 46 47 return None