Python 3.x 在torchvision模型中查找所有ReLU层
在我从Python 3.x 在torchvision模型中查找所有ReLU层,python-3.x,machine-learning,deep-learning,computer-vision,pytorch,Python 3.x,Machine Learning,Deep Learning,Computer Vision,Pytorch,在我从torchvision.models中获取一个预先训练好的模型之后,我希望所有ReLU实例都向后注册\u hook(f),如下所示: for pos, module in self.model.features._modules.items(): for sub_module in module: if isinstance(module, ReLU): module.register_backward_hook(f) 我的问题是如何在模型
torchvision.models
中获取一个预先训练好的模型之后,我希望所有ReLU
实例都向后注册\u hook(f)
,如下所示:
for pos, module in self.model.features._modules.items():
for sub_module in module:
if isinstance(module, ReLU):
module.register_backward_hook(f)
我的问题是如何在模型中找到所有ReLU
。对于densenet161
,ReLU
不仅存在于model.features.\u modules
中,而且存在于自定义的密集层中,例如model.features.\u modules['denseblock1'][0]
。对于resnet151
,ReLU
存在于模型中。_modules
及其自定义层,例如模型。_modules['layer1']
有没有办法找到模型内部的所有
ReLU
?迭代模型所有组件的更优雅的方法是使用
方法:
如果你不想得到所有的子模块,只有直接的模块,你可以考虑使用方法而不是<代码>模块()/<代码>。您还可以使用方法获取子模块的名称
from torch import nn
for module in self.model.modules():
if isinstance(module, nn.ReLU):
module.register_backward_hook(f)