如何在挂钩函数中检索图层名称?

时间:2019-09-03 12:39:39

标签: python pytorch

我有一个神经网络

class ConvNet(nn.Module):
  def __init__(self):
    super().__init__()
    self.trunk = nn.ModuleList()
    self.trunk.add_module('conv1', nn.Conv2d(3, 10, 3))

    self.classifier = nn.Linear(30, 2)
  def forward(self, x):
    out = self.classifier(self.trunk.conv1(x))
    return out

model = ConvNet()

我注册了前向钩

def hook(module, input, output):
    print(module, input[0].shape, output.shape)

x =  model.trunk.conv1.register_forward_hook(hook)

如何在挂钩函数中检索此层的名称为“ conv1”,module._get_name返回Conv2dmodule.__class__返回<class 'torch.nn.modules.conv.Conv2d'>,我怎么得到' conv1'?

0 个答案:

没有答案