TensorFlow Eager模式

转载自: https://blog.csdn.net/qq_35370018/article/details/79442938

一. 静态图的弊端

使用过TensorFlow的大家都会知道, TF通过计算图将计算的定义和执行分隔开, 这是一种声明式(declaretive)的编程模型. 确实, 这种静态图的执行模式优点很多,但是在debug时确实非常不方便(类似于对编译好的C语言程序调用,此时是我们无法对其进行内部的调试), 因此有了Eager Execution, 这在TensorFlow v1.5首次引入.

引入的Eager Execution模式后, TensorFlow就拥有了类似于Pytorch一样动态图模型能力, 我们可以不必再等到see.run(*)才能看到执行结果, 可以方便在IDE随时调试代码,查看OPs执行结果.

二. Eager Execution

随着TensorFlow的快速API迭代,启动Eager模式越来越方便

方式一(1.5及以上版本)

import tensorflow as tf 
import tensorflow.contrib.eager as tfe
tfe.enable_eager_execution()

方式二(最新版本支持)

import tensorflow as tf
tf.enable_eager_execution()

“A NumPy-like library for numerical computation with support for GPU acceleration and automatic differentiation, and a flexible platform for machine learning research and experimentation.”–the eager execution user guide

Eager 模式下能够使用Python的debug调试工具、数据结构、控制流, 且不必再使用placeholder、session, 操作结果直接可以得到。在此种执行模式下, tensor的表现如同numpy array一般, 可以和numpy的库函数兼容。

(注意: 比较Tensor值相等应当使用tf.equal而不是==

三:auto differentiation

Eager Execution支持自动微分,实际上使用的是反向传播的微分方式。注意根据变量的不同,应使用的函数也有所区别。这些api在eager execution未被激活时同样能够使用。查看user guide

四. 总结

事实上,大多数tf api无论是否使用eager execution都可以同样使用。但如果使用eager execution,user guide
同样给出了一些建议,使用tfe而非tf的部分api。

猜你喜欢

转载自blog.csdn.net/u010472607/article/details/81945354
今日推荐