如果你有两个子模型,想要将它们合在一起形成一个更大的模型,可以一起来看看。
下面是一个例子,演示了如何将两个子模型合并为一个模型:
import torch.nn as nn
class SubModel1(nn.Module):
def __init__(self):
super(SubModel1, self).__init__()
self.fc1 = nn.Linear(784, 512)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(512, 256)
def forward(self, x):
x = x.view(-1, 784)
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
class SubModel2(nn.Module):
def __init__(self):
super(SubModel2, self).__init__()
self.fc3 = nn.Linear(256, 128)
self.relu = nn.ReLU()
self.fc4 = nn.Linear(128, 10)
def forward(self, x):
x = self.fc3(x)
x = self.relu(x)
x = self.fc4(x)
return x
class CombinedModel(nn.Module):
def __init__(self, submodel1, submodel2):
super(CombinedModel, self).__init__()
self.submodel1 = submodel1
self.submodel2 = submodel2
def forward(self, x):
x = self.submodel1(x)
x = self.submodel2(x)
return x
submodel1 = SubModel1()
submodel2 = SubModel2()
combined_model = CombinedModel(submodel1, submodel2)