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

本文探讨了TensorFlow中的tf.Graph和tf.Session().run()的使用,强调了通过Session运行变量值的耗时问题。文章指出,虽然Tensor.eval()等效于Session.run(),但在处理复杂场景时,应避免频繁使用Session.run()获取数据。同时,介绍了Session作为context manager的优势以及Session.run()与Tensor.eval()的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

                       
  • 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.youkuaiyun.com/jiangjunshow

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值