【发布时间】:2020-12-09 21:25:55
【问题描述】:
我有两个网络,我需要将它们连接起来以形成我的完整模型。但是我的第一个模型是预训练的,我需要在训练完整模型时使其不可训练。如何在 PyTorch 中实现这一点。
我可以使用this answer 连接两个模型
class MyModelA(nn.Module):
def __init__(self):
super(MyModelA, self).__init__()
self.fc1 = nn.Linear(10, 2)
def forward(self, x):
x = self.fc1(x)
return x
class MyModelB(nn.Module):
def __init__(self):
super(MyModelB, self).__init__()
self.fc1 = nn.Linear(20, 2)
def forward(self, x):
x = self.fc1(x)
return x
class MyEnsemble(nn.Module):
def __init__(self, modelA, modelB):
super(MyEnsemble, self).__init__()
self.modelA = modelA
self.modelB = modelB
def forward(self, x):
x1 = self.modelA(x)
x2 = self.modelB(x1)
return x2
# Create models and load state_dicts
modelA = MyModelA()
modelB = MyModelB()
# Load state dicts
modelA.load_state_dict(torch.load(PATH))
model = MyEnsemble(modelA, modelB)
x = torch.randn(1, 10)
output = model(x)
基本上在这里,我想加载预训练的 modelA 并在训练 Ensemble 模型时使其不可训练。
【问题讨论】:
标签: python pytorch pre-trained-model