Python 装货及;冻结预训练模型以与新网络结合
我有一个预训练的模型,并希望在其上构建一个分类器。我试图加载并冻结预训练模型的权重,并将其输出传递给新的分类器,我希望对其进行优化。到目前为止,我只知道一个Python 装货及;冻结预训练模型以与新网络结合,python,python-3.x,pytorch,Python,Python 3.x,Pytorch,我有一个预训练的模型,并希望在其上构建一个分类器。我试图加载并冻结预训练模型的权重,并将其输出传递给新的分类器,我希望对其进行优化。到目前为止,我只知道一个TypeError:forward()缺少一个必需的位置参数:“x”错误,来自nn。Sequential行: import model #model.py contains the architecture of the pretrained model class Classifier(nn.Module): def __init
TypeError:forward()缺少一个必需的位置参数:“x”
错误,来自nn。Sequential
行:
import model #model.py contains the architecture of the pretrained model
class Classifier(nn.Module):
def __init__(self):
...
def forward(self, x):
...
net = model.Model()
net.load_state_dict(checkpoint["net"])
for c in net.children():
for param in child.parameters():
params.requires_grad = False
model = nn.Sequential(nn.ModuleList(net()), Classifier())
TL;DR
model=nn.Sequential(nn.ModuleList(net),分类器())
您正在通过
net()
“调用”net.forward
,这与Classifier()
中分类器
类的初始化
方法相反,我在PyTorch论坛上与@ptrblck讨论后终于解决了这个问题。该解决方案与Shai的答案类似,只是因为net
包含model.model
类的实例,所以应该执行model=nn.Sequential(net,Classifier())
,而不调用nn.ModuleList()