如何使用 PyTorch 组合两个训练有素的模型?

how to combine two trained models using PyTorch?

我目前正在研究两个使用不同类型数据但相互关联的模型。我想创建一个组合模型,它接受每种数据类型的一个实例,独立地通过每个预训练模型运行它们,然后通过一些前馈处理两个不同模型的组合输出层在顶部。 到目前为止,我已经了解到我可以改变 forward 以接受两个输入,所以我只是将我的各个模型的结构克隆到组合模型中,使用 forward(right ) 的层分别处理它们,然后合并指定的输出。我遇到的问题是弄清楚如何实现这一目标。

我从你的问题中了解到,你可以创建两个模型,然后你需要第三个模型,它将神经网络与前向和 __main__ 相结合,然后你可以 load_state_dict 例如:

第一个模型

class FirstM(nn.Module):
    def __init__(self):
        super(FirstM, self).__init__()
        self.fc1 = nn.Linear(20, 2)
        
    def forward(self, x):
        x = self.fc1(x)
        return x

第二个模型

class SecondM(nn.Module):
    def __init__(self):
        super(SecondM, self).__init__()
        self.fc1 = nn.Linear(20, 2)
        
    def forward(self, x):
        x = self.fc1(x)
        return x

在这里创建一个模型,您可以按如下方式在其中合并两个模型:

class Combined_model(nn.Module):
    def __init__(self, modelA, modelB):
        super(Combined_model, self).__init__()
        self.modelA = modelA
        self.modelB = modelB
        self.classifier = nn.Linear(4, 2)
        
    def forward(self, x1, x2):
        x1 = self.modelA(x1)
        x2 = self.modelB(x2)
        x = torch.cat((x1, x2), dim=1)
        x = self.classifier(F.relu(x))
        return x

然后在主分类之外你可以做如下

# Create models and load state_dicts    
modelA = FirstM()
modelB = SecondM()
# Load state dicts
modelA.load_state_dict(torch.load(PATH))
modelB.load_state_dict(torch.load(PATH))

model = Combined_model(modelA, modelB)
x1, x2 = torch.randn(1, 10), torch.randn(1, 20)
output = model(x1, x2)