tensorflow函數解析:Session.run和Tensor.eval的區別

tensorflow函數解析:Session.run和Tensor.eval

翻譯 2017年04月20日 15:05:50

原問題連接:html

http://stackoverflow.com/questions/33610685/in-tensorflow-what-is-the-difference-between-session-run-and-tensor-evalpython

譯:

問題:api

tensorflow有兩種方式:Session.run和 Tensor.eval,這二者的區別在哪?session

答:機器學習

若是你有一個Tensor t,在使用t.eval()時,等價於:tf.get_default_session().run(t).函數

舉例:post

 

t = tf.constant(42.0) sess = tf.Session() with sess.as_default(): # or `with sess:` to close on exit assert sess is tf.get_default_session() assert t.eval() == sess.run(t)

 

這其中最主要的區別就在於你能夠使用sess.run()在同一步獲取多個tensor中的值,學習

例如:fetch

 

t = tf.constant(42.0) u = tf.constant(37.0) tu = tf.mul(t, u) ut = tf.mul(u, t) with sess.as_default(): tu.eval() # runs one step ut.eval() # runs one step sess.run([tu, ut]) # evaluates both tensors in a single step

 

注意到:每次使用 eval 和 run時,都會執行整個計算圖,爲了獲取計算的結果,將它分配給tf.Variable,而後獲取。ui

原文以下:

Question:

TensorFlow has two ways to evaluate part of graph: Session.run on a list of variables and Tensor.eval. Is there a difference between these two?

Answer:

If you have a Tensor t, calling t.eval() is equivalent to calling tf.get_default_session().run(t).

You can make a session the default as follows:

t = tf.constant(42.0) sess = tf.Session() with sess.as_default(): # or `with sess:` to close on exit assert sess is tf.get_default_session() assert t.eval() == sess.run(t)

The most important difference is that you can use sess.run() to fetch the values of many tensors in the same step:

t = tf.constant(42.0) u = tf.constant(37.0) tu = tf.mul(t, u) ut = tf.mul(u, t) with sess.as_default(): tu.eval() # runs one step ut.eval() # runs one step sess.run([tu, ut]) # evaluates both tensors in a single step

Note that each call to eval and run will execute the whole graph from scratch. To cache the result of a computation, assign it to a tf.Variable.

相關文章
相關標籤/搜索