1. 程式人生 > >TensorFlow 學習 二 tf Session 與 tf Session run

TensorFlow 學習 二 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

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()。

  • <a href=“http://blog.csdn.net/lujiandong1/article/details/53487572”, target="_blank">session.run()是非常耗時的,千萬不要用session.run的方式去取資料
  • <a href=“http://www.tensorfly.cn/bbs/forum.php?mod=viewthread&tid=14”, target="_blank">Session.run()和Tensor.eval()區別是什麼?