首页 > 解决方案 > 在pytorch中获取gradCam的渐变

问题描述

我在我的 pytorch densenet121 模型中使用前向和后向钩子。我requires_grad在训练时设置为 False。

for param in model.features.parameters():
    param.requires_grad = False

我想获得神经网络中最后一个卷积层的梯度,为此我定义了这样的钩子:

model.features.denseblock4.denselayer16.conv2.register_backward_hook(h1)

但这给了我空列表。但是我是否设置requires_grad = True了最后一层然后我得到了渐变。

for param in model.features.denseblock4.denselayer16.conv2.parameters():
    param.requires_grad = True

我对gradCAM使用渐变。

是这种写方法还是有其他方法来获得梯度还是我需要requires_grad = True为整个网络设置?

标签: pythonneural-networkpytorchgradient

解决方案


推荐阅读