最近tf更新了一个新功能autograph,可以将python代码转化为计算图的形式,从而大幅提升效率。
- 安装:
pip install -U tf-nightly
- 导入:
from tensorflow.contrib import autograph as ag
- **调用autograph有两种方式,一种是声明,另一种是调用封装的api**
#直接对函数声明
@ag.convert()
def f(x):
if x < 0:
x = -x
return x
with tf.Graph().as_default():
x = tf.constant(-1)
y = f(x) #声明后不需要再调用api
with tf.Session() as sess:
print(sess.run(y))
# Output: 1
#或者调用api
converted_f = ag.to_graph(f)
print(converted_f(tf.constant(-1)))
# Output: Tensor
print(f(-1))
# Output: 1
- 有一个简单的例子:
def f(x):
if x < 0:
x = -x
return x
通过autograph.to_grah(f)转换会转变为类似
def graph_mode_f(x):
with tf.name_scope('f'):
def if_true():
with tf.name_scope('if_true'):
x_1, = x,
x_1 = tf.negative(x_1)
return x_1,
def if_false():
with tf.name_scope('if_false'):
x_1, = x,
return x_1,
x = ag__.utils.run_cond(tf.greater(x, 0), if_true, if_false)
return x
调用:
with tf.Graph().as_default():
x = tf.constant(-1.0)
converted_f = autograph.to_graph(f)
y = converted_f(x)
with tf.Session() as sess:
print(sess.run(y))
# Output: 1