概述
1.作用
在TFF框架中,如果需要 使用tff.federated_computation 创建联邦计算的代码块,就必须使用tff.tf_computation修饰,不可以直接包含tensorflow的运算(例如创建tf.tensor以及相关的运算)。
需要注意的一个重要限制是,用 tff.federated_computation 修饰的 Python 函数体必须仅包含联合运算符,即它们不能直接包含 TensorFlow 运算。例如,您不能直接使用 tf.nest 接口添加一对联合值。 TensorFlow 代码必须限制在 tff.tf_computation 修饰的代码块中。只有以这种方式包装时,包装的 TensorFlow 代码才能在 tff.federated_computation 的主体中调用。
2.特点
用tff.tf_computation 修饰的 Python 方法后,方法会被序列化为 TensorFlow 图。所以在这个方法中,不可以包含已经被序列化成TensorFlow 的变量。否则会报错:
try:
# Eager mode
constant_10 = tf.constant(10.)
@tff.tf_computation(tf.float32)
def add_ten(x):
return x + constant_10
except Exception as err:
print (err)
结果:
Attempting to capture an EagerTensor without building a function.
在幕后,每个用 tff.tf_computation 修饰的方法都会暂时禁用eager execution,以便捕获计算的结构。虽然在本地禁用了 Eager Execution,但欢迎您使用 Eager TensorFlow、AutoGraph、TensorFlow 2.0 构造等,只要您以能够正确序列化的方式编写计算逻辑即可。例如我们可以采用下面的结构:
def get_constant_10():
return tf.constant(10.)
@tff.tf_computation(tf.float32)
def add_ten(x):
return x + get_constant_10()
add_ten(5.0)
结果:
15.0
这里提一下eager execution方式,这是TensorFlow的一种代码执行方式,采用eager execution方式编写的代码都会马上执行。禁用之后就不再马上执行了。
最后
以上就是紧张服饰为你收集整理的[TFF联邦学习]关于@tff.tf_computation修饰符的使用1.作用2.特点的全部内容,希望文章能够帮你解决[TFF联邦学习]关于@tff.tf_computation修饰符的使用1.作用2.特点所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复