见:https://www.tensorflow.org/guide/autograph
1,Tensorflow AutoGraph能够将普通的python代码转换成Tensorflow graph code。
其引用方式如下:
from tensorflow import contrib
autograph = contrib.autograph
Autograph支持eager mode(tf.enable_eager_execution())下使用,也支持graph模式。
2,Autograph有个method:to_code和to_graph
*Autograph.to_code可以以str的形式,返回转化后的code,如:
def add(x, y):
return x+y
print(autograph.to_code(add))
结果如下
from __future__ import print_function
def tf__add(x, y):
try:
with ag__.function_scope('add'):
return x + y
except:
ag__.rewrite_graph_construction_error(ag_source_map__)
tf__add.autograph_info__ = {}
*Autograph.to_graph直接返回可调用的graph对象,如:
tf_add = autograph.to_graph(add)
print(tf_add(10, 20))
结果为30
3,还可以用decorator的方式调用
如
@autograph.convert()
def python_func(input1, input2):
…
return output
4, 注意autograph对生成和返回python list仍需要特殊处理
在创建list后,需设定类型
z = []
# We ask you to tell us the element dtype of the list
autograph.set_element_type(z, tf.int32)
# 在返回前,需要调用autograph.stack
return autograph.stack(z)
完整例子如下:
@autograph.convert()
def arange(n):
z = []
# We ask you to tell us the element dtype of the list
autograph.set_element_type(z, tf.int32)
for i in tf.range(n):
z.append(i)
# when you're done with the list, stack it
# (this is just like np.stack)
return autograph.stack(z)
with tf.Graph().as_default(), tf.Session() as sess:
sess.run(arange(tf.constant(10)))
5,所支持的python语言特性目前如下:
Assert, Print, Lists, Nested control flow, While loop, For loop, Break