“Floor”和“Identity”都是操作类型字符串,前者对应tf.floor,后者对应tf.identity。 所以我猜你的代码的作用是用tf.identity的反向传播梯度(简称BPG)计算机制代替tf.floor的BPG计算机制 图 G 中的操作,同时传递 tf.reduce_mean 的前向输出。这似乎有点奇怪,因为到目前为止我发现在gradient_override_map 的所有应用程序中, op_type_map 的键始终与用于在上下文中产生输出的操作的类型字符串相同。我的意思是我更熟悉返回tf.floor(SomeVals)而不是tf.reduce_mean(SomeVals)的场景。
gradient_override_map({op_A_type: op_B_type}) 所做的是将 op_A 的 BPG 计算机制替换为 op_B 的,同时保留 op_A_type 的前向传播计算机制。 lahwran 的回答中显示了 gradient_override_map 的常见应用。
@tf.RegisterGradient("CustomGrad")
def _const_mul_grad(unused_op, grad):
return 5.0 * grad
g = tf.get_default_graph()
with g.gradient_override_map({"Identity": "CustomGrad"}):
output = tf.identity(input, name="Identity")
通过
@tf.RegisterGradient("CustomGrad")
def _const_mul_grad(unused_op, grad):
return 5.0 * grad
装饰器tf.RegisterGradient("CustomGrad")注册了_const_mul_grad(unused_op, grad)定义的渐变函数,用于自定义操作类型——“CustomGrad”,
同时
g = tf.get_default_graph()
with g.gradient_override_map({"Identity": "CustomGrad"}):
output = tf.identity(input, name="Identity")
保证字符串类型为“Identity”(tf.identity)的所有操作(在图 g 中)的输出与原样,而 tf.identity 的 BPG 计算机制s替换为字符串类型“CustomGrad”的BPG运算机制。
附:
操作的类型字符串对应于定义操作的原型的OpDef.name 字段。要查找操作的OpDef.name,请参考this question下的明星的回答
-
不需要声明 tf.identity 操作的名称,因为 tf.identity 中的 arg 'name' 是可选的。