我需要使用 swin Transfomer 作为我的 SVM 模型的骨干。我需要首先提取特征,因此我尝试删除最后一层并训练模型。这是一个示例可执行代码。
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
import numpy as np
HUB_URL = "SharanSMenon/swin-transformer-hub:main"
MODEL_NAME = "swin_tiny_patch4_window7_224"
model = torch.hub.load(HUB_URL, MODEL_NAME, pretrained=True)
model = nn.Sequential(*list(model.children())[:-1]) #--> If you comment this line, the code is executing
for param in model.parameters():
param.requires_grad = False
dummy_tensor = torch.randn(32, 3, 224, width)
# Print the shape of the dummy tensor
model(dummy_tensor)
我错过了什么,我用 resnet50 尝试了相同的过程,效果很好。为什么我无法删除最后一层并仅获得输出特征?我应该怎么办?有什么建议吗?
这两个模型具有不同的
forward
逻辑。如果您检查 nn.Sequential(*list(model.children())[:-1])
的结果,您会发现您将 ModuleList
放入了 Sequential
块中,这是没有意义的。具体错误是尝试调用未实现的 forward
的 ModuleList
方法。
您需要使您的逻辑适应每个模型架构。