如何在Keras中创建自定义图层以获取和操纵渐变 [英] How to create a custom layer to get and manipulate gradients in Keras
本文介绍了如何在Keras中创建自定义图层以获取和操纵渐变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从通过对抗性学习缓解不必要的偏见
模型架构是
- 1)输入层
- 2)密集的定长层
- 3)自定义渐变项目层
- 4a)任务1层
- 4b)任务2层(对抗性任务)
- 1) Input layer
- 2) Dense fixed length layer
- 3) Custom gradient project layer
- 4a) Task 1 layers
- 4b) Task 2 layers (adversarial task)
我想使用自定义图层(3)处理任务1和任务2的渐变.目前,我计划在自定义图层的调用中添加类似的内容
I would like to manipulate the gradients from task 1 and task 2 with a custom layer (3). Currently I plan to have something like this in the call of a custom layer
@tf.RegisterGradient('blah') def proj_gradients(op, grad): return grad[0] - grad[1] g = K.get_session().graph with g.gradient_override_map({'Identity': 'blah'}): y = tf.identity(X)
有没有更直观的Keras方法?
Is there a more intuitive Keras way for doing this?
推荐答案
tf.custom_gradient 是在此处使用的最佳工具.它使您可以在调用站点上定义渐变函数,具有比覆盖图更好的界面,并且可以很好地执行.
tf.custom_gradient is the best tool to use here. It lets you define the gradient function at the call site, has a nicer interface than the override map, and works well with eager execution.
这篇关于如何在Keras中创建自定义图层以获取和操纵渐变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文