tf.function
把普通python语法写的函数或者代码变成TensorFlow里面的图
auto-graph 是tf.function所依赖的一个机制,这种机制可以把python语法的东西变成TensorFlow里面的图
# tf.function and auto-graph.
# 输入 缩放因子
def scaled_elu(z, scale=1.0, alpha=1.0):
# z >= 0 ? scale * z : scale * alpha * tf.nn.elu(z)
# 判断z是不是大于0
is_positive = tf.greater_equal(z, 0.0)
# where实现三元表达式
return scale * tf.where(is_positive, z, alpha * tf.nn.elu(z))
#输入一个标量
print(scaled_elu(tf.constant(-3.)))
#输入一个向量
print(scaled_elu(tf.constant([-3., -2.5])))
# 使用tf.function 把python函数 变成TensorFlow里面的图实现函数
scaled_elu_tf = tf.function(scaled_elu)
print(scaled_elu_tf(tf.constant(-3.)))
print(scaled_elu_tf(tf.constant([-3., -2.5])))
# 使用python_function转为python函数
print(scaled_elu_tf.python_function is scaled_elu)
转化为这种图结构有什么优势?速度快
GPU的加速比会更大。
# 1 + 1/2 + 1/2^2 + ... + 1/2^n
# 使用下面的代码 把python代码转化为图结构
@tf.function
def converge_to_2(n_iters):
total = tf.constant(0.)
increment = tf.constant(1.)
for _ in range(n_iters):
total += increment
increment /= 2.0
return total
print(converge_to_2(20))
# 转化为TensorFlow代码 然后生成tensorflow里面的图结构
def display_tf_code(func):
code = tf.autograph.to_code(func)
# 展示代码
from IPython.display import display, Markdown
display(Markdown('```python\n{}\n```'.format(code)))
Variable不能定义在函数里面,在定义神经网络的时候,在转成function之前,需要把变量全部初始化
# 添加类型限定 输入参数的类型 限制输入tf.int32 名字为x
@tf.function(input_signature=[tf.TensorSpec([None], tf.int32, name='x')])
def cube(z):
return tf.pow(z, 3)
try:
print(cube(tf.constant([1., 2., 3.])))
except ValueError as ex:
print(ex)
print(cube(tf.constant([1, 2, 3])))
看新参数获得的对象和原参数是否一致,他们的signation是一样的