Tensorflow AutoGraph用法

见: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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值