张量流中的自定义层

时间:2019-03-03 16:14:33

标签: python tensorflow dropout

我试图对tensorflow中的内置dropout函数进行一些更改。这样做的最佳过程是什么?

我想在正向传播和反向传播步骤中进行一些更改。在Tensorflow Implementation中,我只能找到前向通行证,而不能找到后向通行证。 我想同时修改前进和后退通行证。

1 个答案:

答案 0 :(得分:1)

您可以使用tf.custom_gradient在单个方法中定义自己的前进和后退步骤。这是一个简单的示例:

import tensorflow as tf

tf.InteractiveSession()

@tf.custom_gradient
def custom_multiply(a, x):
  # Define your own forward step
  y = a * x
  # Define your own backward step
  def grads(dy): return dy * x, dy * a + 100
  # Return the forward result and the backward function
  return y, grads

a, x = tf.constant(2), tf.constant(3)
y = custom_multiply(a, x)
dy_dx = tf.gradients(y, x)[0]
# It will print `dy/dx = 102` instead of 2 if the gradient is not customized
print('dy/dx =', dy_dx.eval())

如果您想customize your own layer,只需将tf.layers.Dropout.call中使用的核心功能替换为您自己的功能即可。

相关问题