【发布时间】:2019-01-30 04:13:09
【问题描述】:
在使用 tensorflow 完成一个简单的最小化任务(为硬 sigmoid 近似拟合最佳参数)后,我决定将其从图形模式转换为渴望模式。令我惊讶的是,在 Eager 模式下运行需要更长的时间。
这里是代码。
图形模式代码:
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,我想知道如何优化此代码以使其性能至少与第一个版本匹配.
【问题讨论】:
-
为什么投反对票?
标签: python tensorflow optimization