深度学习之tensorflow框架(中)

会话

  • 开启会话
    • tf.Session用于完整的程序中
    • tf.InteractiveSession用于交互式上下文中的tensorflow
  • 查看张量的值
    • 都必须在会话里面
    • c_new_value=new_sess.run(c_new)
    • print("c_new_value:\n",c_new_value)
    • print("a_new_value:\n",a_new.eval())
    • def session_demo():
          """
          会话的演示
          :return:
          """
          a_t = tf.constant(2, name="a_t")
          b_t = tf.constant(3, name="b_t")
          c_t = tf.add(a_t, b_t, name="c_t")
          print("a_t:\n", a_t)
          print("b_t:\n", b_t)
          print("tensorflow加法运算的结果:\n", c_t)
      
          # 查看默认图
          # 方法1:调用方法
          default_g = tf.compat.v1.get_default_graph()
          print("default_g:\n", default_g)
          # 方法2:查看属性
          print("a_t的图属性:\n", a_t.graph)
          print("c_t的图属性:\n", c_t.graph)
      
          # 开启会话
          with tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(allow_soft_placement=True,log_device_placement=True)) as sess:
              # c_t_value = sess.run(c_t)
              # print("c_t_value:\n", c_t_value)
              abc = sess.run([a_t,b_t,c_t])
              print("abc:\n",abc)
              print("sess的图属性:\n", sess.graph)
          return None
      
      
      def feed_demo():
          """
          feed操作
          :return:
          """
          a=tf.compat.v1.placeholder(dtype=tf.float32)
          b=tf.compat.v1.placeholder(dtype=tf.float32)
          sum_ab=tf.add(a,b)
          print("a:\n",a)
          print("b:\n",b)
          print("sum_ab:\n",sum_ab)
      
          with tf.compat.v1.Session() as sess:
              sum_ab_value=sess.run(sum_ab,feed_dict={a:3.9,b:3.5})
              print("sum_ab_value:\n",sum_ab_value)
      
          return None

相关推荐