使用hook函数来获取网络中间层的输入或者输出

第一种:

参考链接:(35条消息) Pytorch中hook如何直接调取网络中间层的输入输出数据(不理论分析,直接实践上手教程)_pytroch网络输入数据_one努力翻身的咸鱼的博客-CSDN博客对于

input_data = {}
output_data = {}
def get_activation(name):
    def hook(model,input,output):
        input_data[name] = input[0].detach() # input type is tulple, only has one element, which is the tensor
        output_data[name] = output.detach()  # output type is tensor
    return hook
————————————————
版权声明:本文为CSDN博主「one努力翻身的咸鱼」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/JasonFuyz/article/details/126803862

对于这样的形式在我实际用的时候虽然很方便的从字典里看得出哪一层的输出,但是在代码验证的时候会出现以下错误。AttributeError: Can‘t pickle local object 

对于这样的错误我也在网上查看了是因为闭包的原因。所以这样的方法我也就用不了了。(因为我我i不会改,不知道怎么解除闭包)

但是也有可能是另外一种原因就是没有remove hook(不过我没有尝试)。

第二种:

参考链接:(36条消息) Pytorch获取中间层信息-hook函数_pytorch提取中间层特征 hook_winycg的博客-CSDN博客

features = []
def hook(module, input, output):
    features.append(output.clone().detach())
handle.remove()

用完之后remove就好。我忘记remove了,还是会报错AttributeError: Can‘t pickle local object 。

个人使用经验注意事项:

hook在网络推理之前注册,remove在网络推理之后。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
获取PyTorch中间层输出,可以使用`register_forward_hook`方法。该方法可用于在网络的前向传递中注册回调函数,并在给定层次结构上获取中间层输出。 以下是一个示例代码,展示如何获取名为`intermediate_layer_output`层的输出: ```python import torch.nn as nn class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.layer1 = nn.Linear(10, 5) self.intermediate_layer = nn.Linear(5, 3) self.layer2 = nn.Linear(3, 1) def forward(self, x): x = self.layer1(x) x = torch.relu(x) x = self.intermediate_layer(x) x = torch.relu(x) x = self.layer2(x) return x model = MyModel() # 定义回调函数 def get_intermediate_layer_output(name): def hook(model, input, output): setattr(model, name, output) return hook # 注册回调函数 model.intermediate_layer.register_forward_hook(get_intermediate_layer_output('intermediate_layer_output')) # 输入数据并进行前向传递 x = torch.randn(1, 10) output = model(x) # 获取中间层输出 intermediate_output = model.intermediate_layer_output ``` 在上述代码中,我们首先定义了一个名为`MyModel`的模型,并在其中定义了三个线性层。然后,我们定义了一个名为`get_intermediate_layer_output`的回调函数,该函数用于获取中间层输出。我们使用`register_forward_hook`方法将回调函数注册到`intermediate_layer`层上。最后,我们输入数据并进行前向传递,然后使用`model.intermediate_layer_output`获取中间层输出

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值