Zheng Chu's Blog

让希望永驻


  • 主页

  • 所有专栏

  • 历史文章

  • 标签

  • 关于我

Tensorflow2-AutoGraph

Posted on 2020-10-01 Edited on 2021-03-17 In Tensorflow Views:

三种计算图

有三种计算图的构建方式:静态计算图,动态计算图,以及Autograph.

在TensorFlow1.0时代,采用的是静态计算图,需要先使用TensorFlow的各种算子创建计算图,然后再开启一个会话Session,显式执行计算图。

而在TensorFlow2.0时代,采用的是动态计算图,即每使用一个算子后,该算子会被动态加入到隐含的默认计算图中立即执行得到结果,而无需开启Session

因为使用动态图会有许多次Python进程和TensorFlow的C++进程之间的通信。而静态计算图构建完成之后几乎全部在TensorFlow内核上使用C++代码执行,效率更高。此外静态图会对计算步骤进行一定的优化,剪去和结果无关的计算步骤。

如果需要在TensorFlow2.0中使用静态图,可以使用@tf.function装饰器将普通Python函数转换成对应的TensorFlow计算图构建代码。运行该函数就相当于在TensorFlow1.0中用Session执行代码。使用tf.function构建静态图的方式叫做 Autograph.

在TensorFlow2.0中,使用的是动态计算图和Autograph.

实践中,我们一般会先用动态计算图调试代码,然后在需要提高性能的的地方利用@tf.function切换成Autograph获得更高的效率。

一,Autograph编码规范总结

a function with @tf.fuction such that the whole function will be compiled, optimized, and run as a single computational graph

Python “assert” within a @tf.function function will throw an exception. Use tf.debugging.assert_{condition} instead for both modes.

  • 1,被@tf.function修饰的函数应尽可能使用TensorFlow中的函数而不是Python中的其他函数。例如使用tf.print而不是print,使用tf.range而不是range,使用tf.constant(True)而不是True.
  • 2,避免在@tf.function修饰的函数内部定义tf.Variable.
  • 3,被@tf.function修饰的函数不可修改该函数外部的Python列表或字典等数据结构变量。

二,Autograph编码规范解析

1,被@tf.function修饰的函数应尽量使用TensorFlow中的函数而不是Python中的其他函数。

1
2
3
4
5
6
7
8
9
10
11
12
import numpy as np
import tensorflow as tf

@tf.function
def np_random():
a = np.random.randn(3,3)
tf.print(a)

@tf.function
def tf_random():
a = tf.random.normal((3,3))
tf.print(a)
1
2
3
4
5
6
7
8
9
10
#np_random每次执行都是一样的结果。
np_random()
np_random()

array([[ 0.22619201, -0.4550123 , -0.42587565],
[ 0.05429906, 0.2312667 , -1.44819738],
[ 0.36571796, 1.45578986, -1.05348983]])
array([[ 0.22619201, -0.4550123 , -0.42587565],
[ 0.05429906, 0.2312667 , -1.44819738],
[ 0.36571796, 1.45578986, -1.05348983]])
1
2
3
4
5
6
7
8
9
10
#tf_random每次执行都会有重新生成随机数。
tf_random()
tf_random()

[[-1.38956189 -0.394843668 0.420657277]
[2.87235498 -1.33740318 -0.533843279]
[0.918233037 0.118598573 -0.399486482]]
[[-0.858178258 1.67509317 0.511889517]
[-0.545829177 -2.20118237 -0.968222201]
[0.733958483 -0.61904633 0.77440238]]

2,避免在@tf.function修饰的函数内部定义tf.Variable.

1
2
3
4
5
6
7
8
9
10
11
# 避免在@tf.function修饰的函数内部定义tf.Variable.

x = tf.Variable(1.0,dtype=tf.float32)
@tf.function
def outer_var():
x.assign_add(1.0)
tf.print(x)
return(x)

outer_var()
outer_var()

3,被@tf.function修饰的函数不可修改该函数外部的Python列表或字典等结构类型变量。

一,Autograph的机制原理

一,Autograph和tf.Module概述

TensorFlow提供了一个基类tf.Module,通过继承它构建子类,我们不仅可以获得以上的自然而然,而且可以非常方便地管理变量,还可以非常方便地管理它引用的其它Module,最重要的是,我们能够利用tf.saved_model保存模型并实现跨平台部署使用。

实际上,tf.keras.models.Model,tf.keras.layers.Layer 都是继承自tf.Module的,提供了方便的变量管理和所引用的子模块管理的功能。

因此,利用tf.Module提供的封装,再结合TensoFlow丰富的低阶API,实际上我们能够基于TensorFlow开发任意机器学习模型(而非仅仅是神经网络模型),并实现跨平台部署使用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class DemoModule(tf.Module):
def __init__(self,init_value = tf.constant(0.0),name=None):
super(DemoModule, self).__init__(name=name)
with self.name_scope: #相当于with tf.name_scope("demo_module")
self.x = tf.Variable(init_value,dtype = tf.float32,trainable=True)

#在tf.function中用input_signature限定输入张量的签名类型:shape和dtype
@tf.function(input_signature=[tf.TensorSpec(shape = [], dtype = tf.float32)])
def addprint(self,a):
with self.name_scope:
self.x.assign_add(a)
tf.print(self.x)
return(self.x)


#执行
demo = DemoModule(init_value = tf.constant(1.0))
result = demo.addprint(tf.constant(5.0))

#查看模块中的全部变量和全部可训练变量
print(demo.variables)
print(demo.trainable_variables)

#查看模块中的全部子模块
demo.submodules

#使用tf.saved_model 保存模型,并指定需要跨平台部署的方法
tf.saved_model.save(demo,"./data/demo/1",signatures = {"serving_default":demo.addprint})

#加载模型
demo2 = tf.saved_model.load("./data/demo/1")
demo2.addprint(tf.constant(5.0))





import datetime

# 创建日志
stamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
logdir = './data/demomodule/%s' % stamp
writer = tf.summary.create_file_writer(logdir)

#开启autograph跟踪
tf.summary.trace_on(graph=True, profiler=True)

#执行autograph
demo = DemoModule(init_value = tf.constant(0.0))
result = demo.addprint(tf.constant(5.0))

#将计算图信息写入日志
with writer.as_default():
tf.summary.trace_export(
name="demomodule",
step=0,
profiler_outdir=logdir)

五、TensorFlow的中阶API

TensorFlow的中阶API主要包括:

  • 数据管道(tf.data)
  • 特征列(tf.feature_column)
  • 激活函数(tf.nn)
  • 模型层(tf.keras.layers)
  • 损失函数(tf.keras.losses)
  • 评估函数(tf.keras.metrics)
  • 优化器(tf.keras.optimizers)
  • 回调函数(tf.keras.callbacks)
# Tensorflow
Tensorflow2-DistributedTraining
Tensorflow2-CustomMetrics
  • Table of Contents
  • Overview
Zheng Chu

Zheng Chu

90 posts
20 categories
25 tags
GitHub 简书 CSDN E-Mail
  1. 1. 三种计算图
    1. 1.0.1. 一,Autograph编码规范总结
    2. 1.0.2. 二,Autograph编码规范解析
    3. 1.0.3. 一,Autograph的机制原理
    4. 1.0.4. 一,Autograph和tf.Module概述
  • 2. 五、TensorFlow的中阶API
  • © 2021 Zheng Chu
    Powered by Hexo v4.2.1
    |
    Theme – NexT.Pisces v7.3.0
    |