如何从预先训练的PyTorch模型(例如ResNet或VGG)的特定层提取特征,而无需再次进行前向传递?

最佳答案

您可以在所需的特定层上注册forward hook。就像是:

def some_specific_layer_hook(module, input_, output):
    pass  # the value is in 'output'

model.some_specific_layer.register_forward_hook(some_specific_layer_hook)

model(some_input)


例如,要在ResNet中获得res5c输出,您可能需要使用nonlocal变量(或Python 2中的global):

res5c_output = None

def res5c_hook(module, input_, output):
    nonlocal res5c_output
    res5c_output = output

resnet.layer4.register_forward_hook(res5c_hook)

resnet(some_input)

# Then, use `res5c_output`.

10-08 11:03