Tensorflow:interactivesession和session的区别。
目錄:
- 目錄:
- 前言
- 正文
- 總結
前言
在練習tensorflow的時候發現了很多很有意思的基本問題,寫個帖子記錄一下,既方便了回顧,又方便了同學學習/
正文
tf.Session()和tf.InteractiveSession()的區別
官方tutorial是這么說的:
The only difference with a regular Session is that an InteractiveSession installs itself as the default session on
construction. The methods Tensor.eval() and Operation.run() will use that session to run ops.
翻譯一下就是:tf.InteractiveSession()是一種交替式的會話方式,它讓自己成為了默認的會話,也就是說用戶在單一會話的情境下,不需要指明用哪個會話也不需要更改會話運行的情況下,就可以運行起來,這就是默認的好處。這樣的話就是run和eval()函數可以不指明session啦。
對比一下:
import tensorflow as tf import numpy as npimporttensorflow as tf import numpy as nptesta=tf.constant([[1., 2., 3.],[4., 5., 6.]]) testb=np.float32(np.random.randn(3,2)) testc=tf.matmul(testa,testb) init=tf.global_variables_initializer() sess=tf.Session() print (testc.eval())上面的代碼編譯是錯誤的,顯示錯誤如下:
ValueError: Cannot evaluate tensor using `eval()`: No default session is registered. Use `with sess.as_default()` or pass an explicit session to `eval(session=sess)` import tensorflow as tf import numpy as nptesta=tf.constant([[1., 2., 3.],[4., 5., 6.]]) testb=np.float32(np.random.randn(3,2)) testc=tf.matmul(testa,testb) init=tf.global_variables_initializer() sess=tf.InteractiveSession() print (testc.eval())而用InteractiveSession()就不會出錯,簡單來說InteractiveSession()等價于:
sess=tf.Session() with sess.as_default():換句話說,如果說想讓sess=tf.Session()起到作用,一種方法是上面的
sess=tf.Session() with sess as default:print (testc.eval())另外一種方法是
sess=tf.Session() print (c.eval(session=sess))其實還有一種方法也是with,如下:
復制代碼
總結
tf.InteractiveSession()默認自己就是用戶要操作的會話(session),而tf.Session()沒有這個默認,因此用eval()啟動計算時需要指明使用那個會話(session)
總結
以上是生活随笔為你收集整理的Tensorflow:interactivesession和session的区别。的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: comparator 字符串比较大小_j
- 下一篇: Pytho学习笔记:电子邮件1