TensorFlow 学习(二)—— tf Graph tf Session 与 tf Session run

                       
  • session:
    • with tf.Session() as sess:/ tf.InteractiveSession()

    • 初始化:

      • tf.global_variables_initializer()
      with tf.Session() as sess: sess.run(tf.global_variables_initializer())
             
             
      • 1
      • 2

0. tf.Graph

  • 命名空间与 operation name(oper.name 获取操作名):

    c_0 = tf.constant(0, name="c")  # => operation named "c"print(c_0.name)# Already-used names will be "uniquified".c_1 = tf.constant(2, name="c")  # => operation named "c_1"# Name scopes add a prefix to all operations created in the same context.with tf.name_scope("outer"):    c_2 = tf.constant(2, name="c")  # => operation named "outer/c"    # Name scopes nest like paths in a hierarchical file system.    with tf.name_scope("inner"):        c_3 = tf.constant(3, name="c")  # => operation named "outer/inner/c"    # Exiting a name scope context will return to the previous prefix.    c_4 = tf.constant(4, name="c")  # => operation named "outer/c_1"    # Already-used name scopes will be "uniquified".    with tf.name_scope("inner"):        c_5 = tf.constant(5, name="c")  # => operation named "outer/inner_1/c"
         
         
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

1. 使用 tf.Session().run() 读取变量的值十分耗时

#CODING: UTF-8import timeimport tensorflow as tfN = 100000x = tf.constant([1.])b = 1.with tf.Session() as sess: sess.run(tf.initialize_all_variables())  t1 = time.time() for _ in range(N):  y = sess.run(x) print('使用sess.run() 读取变量数据耗时', time.time()-t1) t2 = time.time() for _ in range(N):  a = b print('直接赋值耗时', time.time()-t2)
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

2. tf.Session().run() 与 Tensor.eval()

假设 x 为 tf 下的一个 Tensor 对象,t.eval() 执行的动作就是 tf.Session().run(t) 。

import tensorflow as tfx = tf.constant([5.])print(tf.Session().run(x))with tf.Session(): print(x.eval())
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

在第二个例子中,session的作用就象context manager,context manager在with块的生存期,将session作为默认的 session。对简单应用的情形(如单元测试),context manager的方法可以得到更简洁的代码;如果你的代码要处理多个graph和 session,更直白的方式可能是显式调用Session.run()。

           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

猜你喜欢

转载自blog.csdn.net/qq_43679627/article/details/87292798