python - Tensorflow:在 Eager 模式下慢 7 倍
问题描述
在使用 tensorflow 完成了一个简单的最小化任务(为硬 sigmoid 近似拟合最佳参数)之后,我决定将其从图形模式转换为渴望模式。令我惊讶的是,在急切模式下运行需要更长的时间。
这是代码。
图形模式代码:
import tensorflow as tf
from time import time
beg = time()
a = tf.Variable(-10, name='a', dtype=tf.float32)
b = tf.Variable(10, name='b', dtype=tf.float32)
def g(x):
return tf.clip_by_value( (x-a)/(b-a), 0, 1)
X = tf.lin_space(-20., 20., 2000)
loss = tf.reduce_sum( tf.square( tf.math.sigmoid(X) - g(X)))
opt = tf.train.AdamOptimizer(learning_rate=1e-3)
train_op = opt.minimize( loss)
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)
for _ in range( int(1e4)):
sess.run( train_op)
print( 'Non-eager run in %.1f seconds' %(time()-beg))
印刷Non-eager run in 3.5 seconds
渴望模式代码:
import tensorflow as tf
from time import time
tf.enable_eager_execution()
beg = time()
a = tf.Variable(-10, name='a', dtype=tf.float32)
b = tf.Variable(10, name='b', dtype=tf.float32)
def g(x):
return tf.clip_by_value( (x-a)/(b-a), 0, 1)
X = tf.lin_space(-20., 20., 2000)
opt = tf.train.AdamOptimizer(learning_rate=1e-3)
for _ in range( int(1e4)):
with tf.GradientTape() as tape:
loss = tf.reduce_sum( tf.square( tf.math.sigmoid(X) - g(X)))
grads = tape.gradient(loss, [a,b])
opt.apply_gradients(zip(grads, [a,b]), global_step=tf.train.get_or_create_global_step())
print( 'Eager run in %.1f seconds' %(time()-beg))
印刷Eager run in 20.9 seconds
我敢打赌,我的 Eager 代码是次优的,并且tensorflow
似乎在其下一个大版本中转向 Eager Execution,我想知道如何优化此代码以使其性能至少与第一个版本相匹配。
解决方案
您在 tensorflow 2.0 中的代码将类似于(请注意,您已经可以尝试每晚构建 tensorflow 2.0(https://pypi.org/project/tf-nightly-2.0-preview/))
import tensorflow as tf
from time import time
tf.enable_eager_execution()
beg = time()
@tf.function
def train():
a = tf.Variable(-10, name='a', dtype=tf.float32)
b = tf.Variable(10, name='b', dtype=tf.float32)
def g(x):
return tf.clip_by_value((x - a) / (b - a), 0, 1)
X = tf.lin_space(-20., 20., 2000)
opt = tf.train.AdamOptimizer(learning_rate=1e-3)
for _ in range(int(1e4)):
with tf.GradientTape() as tape:
loss = tf.reduce_sum(tf.square(tf.math.sigmoid(X) - g(X)))
grads = tape.gradient(loss, [a, b])
opt.apply_gradients(
zip(grads, [a, b]),
global_step=tf.train.get_or_create_global_step())
train()
print('Eager run in %.1f seconds' % (time() - beg))
请注意tf.contrib.eager.defun
and Autograph
(在 1.12 及更高版本中可用),它们的基础@tf.session
仍在积极开发中并且是实验性的,因此现在实现有点错误;因此,如果它无法运行或速度较慢,可能值得在 Github 上打开一个问题。
在 2.0@tf.session
中将合并两者的defun
优点autograd
推荐阅读
- python - 终端在 ubuntu 20.04 上的 python 上运行
- python - 如何在熊猫中将一列值与多列值进行比较
- python - 通过将函数应用于 nx 1 numpy 数组中的元素对,numpy 中的 nxn 矩阵
- python-3.x - 如何从 .csv Python3 中获取特定的列值?
- excel - 重命名目录中的文件不仅是文件夹
- flutter - 如何确定 Flutter 中 MultiChildRenderObjectWidget 的子对象的形状?
- javascript - 从本地存储 [JS][HTML5][React][LocalStorage] 获取特定的键值
- javascript - 为什么我记忆的 React 组件仍在重新渲染?
- node.js - React 更改后如何刷新组件
- angular - 如何测试输入元素的输入?