上一篇啰啰嗦嗦说了很多tf2.0中eager execution和autograph的一些特性,但是感觉还是没有说透,反而让人很迷惑,这次再唠唠tf.function到底有啥奇妙之处。
tf.function()
tf1.x中一般的工作流程,就是先创建一个计算图,然后通过tf.Session对图进行计算。例如:
g = tf.Graph()
with g.as_default():
a = tf.constant(...)
x = tf.constant(...)
b = tf.Variable(..)
y = tf.matmul(a, x) + b
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)
print(sess.run(y))
eager execution带来的改变就是,正如大家多次听说的那样,用户不再需要直接定义计算图或者通过tf.Session来执行代码,也不需要调用tf.global_variables_initializer去初始化变量或者通过tf.control_dependencies去执行计算图中没有包含的节点。
a = tf.constant([[10,10],[11.,1.]])
x = tf.constant([[1.,0.],[0.,1.]])
b = tf.Variable(12.)
y = tf.matmul(a, x) + b
print(y.numpy())
但是也带来了执行效率低的问题,因为代码需要依赖Python的解释器来进行计算,无法对数据流以及计算图进行优化.
Autograph
移除tf.Session这一概念,可以用一个Python装饰符来进行加速,