TF Eager Execution 閱讀筆記
@[TensonFlow]
看了半天不知道Eager 是啥,這哪能看下去。所以Google了一下,在知乎發(fā)現(xiàn)如下解釋:
......就開啟了Eager模式,這時(shí),TensorFlow會(huì)從原先的聲明式(declarative)編程形式變成命令式(imperative)編程形式。當(dāng)寫下語(yǔ)句"c = tf.matmul(a, b)"后(以及其他任何tf開頭的函數(shù)),就會(huì)直接執(zhí)行相應(yīng)的操作并得到值,而不再像之前那樣,生成一個(gè)Tensor,通過sess.run()才能拿到值。注意:這種Eager模式一旦被開啟就不能被關(guān)閉。
好處
使用Eager模式的好處大家應(yīng)當(dāng)都很清楚,可以直接參考PyTorch的相關(guān)問題來看:PyTorch到底好用在哪里?。這里就簡(jiǎn)單說一說,大概有以下幾點(diǎn):
- 搭模型更方便了:之前搭模型通常要認(rèn)真記下每一步Tensor的shape和意義,然后再操作?,F(xiàn)在可以輕松點(diǎn),邊搭邊寫,忘記形狀或者含義的時(shí)候可以直接打出來看。另外流程控制可以使用Python的內(nèi)建語(yǔ)法,更加直觀。
- 調(diào)試時(shí)no more sess.run() ! 之前在調(diào)試時(shí)必須要加上sess.run(),很麻煩,現(xiàn)在可以直接把變量print出來,亦可使用IDE的監(jiān)控工具單步調(diào)試。
- 最后,如果之前我們想在自己的程序中用tf開頭的函數(shù),需要手動(dòng)開啟Session將結(jié)果的Tensor轉(zhuǎn)換成Numpy數(shù)組,或者使用官方提供的函數(shù)修飾器。現(xiàn)在只需要用開啟這個(gè)Eager模式,就可以直接把tf開頭的函數(shù)當(dāng)普通函數(shù)用了。
作者:何之源
鏈接:https://www.zhihu.com/question/67471378/answer/253549074
來源:知乎
著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
OK。主要優(yōu)勢(shì)是立即執(zhí)行,對(duì)模型搭建調(diào)試友好。
Since there isn't a computational graph to build and run later in a session, it's easy to inspect results using print() or a debugger. Evaluating, printing, and checking tensor values does not break the flow for computing gradients.
GradientTape
又是一個(gè)不知道的東西,感覺上這個(gè)Eager模式是某種進(jìn)階模式,在我對(duì)術(shù)語(yǔ)和流程掌握都不夠的時(shí)候,閱讀起來有點(diǎn)障礙,而且感觸也很少。
首先根據(jù)術(shù)語(yǔ)表,Gradient是梯度。
官方的解釋有以下幾點(diǎn):
- It records operations to use to compute gradients.
- Since different operations can occur during each call, all forward-pass operations get recorded to a "tape".
- To compute the gradient, play the tape backwards and then discard.
- A particular tfe.GradientTape can only be computed once, subsequent calls throw a runtime error.
嗯就是記錄操作并用來反向運(yùn)算計(jì)算梯度的,不能連續(xù)調(diào)用。
示例
示例用的是MNIST識(shí)別手寫數(shù)字的問題,代碼見https://github.com/tensorflow/models/blob/master/official/mnist/mnist_eager.py