Pytorch 由多个不同的网络模型组合而成的大模型(用一个损失函数,和优化方法去训练)

   一开始写模型的时候,网上学习到的都是那种非常简单的模型,可是我要实现的模型是将多个模型套起来,一个大模型,一起训练。
   其实只要先定义几个小模型,然后将其定义在大模型的init中,然后用forward来控制内部的运作即可,直接看代码把。

class Model_one(nn.Module):
    def __init__(self, n_input, n_output):
        super(Model_one, self).__init__()
        self.predict = nn.Linear(n_input, n_output, bias=False)

    def forward(self, x):
        out = self.predict(x)
        return out


class Model_two(nn.Module):
    def __init__(self, n_input, n_output):
        super(Model_two, self).__init__()
        self.hidden1 = nn.Linear(n_input, 128)
        self.hidden2 = nn.Linear(128, 64)
        self.predict = nn.Linear(64, n_output)
        self.dropout = nn.Dropout(p=0.5)
        self.dropout2 = nn.Dropout(p=0.8)

     def forward(self, x):
        out = self.hidden1(x)
        out = self.dropout(out)
        out = F.relu(out)

        out = self.hidden2(out)
        out = self.dropout(out)
        out = F.relu(out)

        predict = self.predict(out)
        predict = self.dropout2(predict)
        predict = torch.sigmoid(predict)
        return predict



    def forward(self, x):
        out = self.hidden1(x)
        out = F.relu(out)
        out = self.hidden2(out)
        out = F.relu(out)
        out = self.hidden3(out)
        out = F.relu(out)
        predict = self.predict(out)
        predict = torch.sigmoid(predict)
        return predict


class Model(nn.Module):
    def __init__(self, category_len, grid_len, K):
        super(Model, self).__init__()
        self.category_model = Model_one(category_len, K)
        self.grid_model = Model_one(grid_len, K)
        self.category_bias_model = Model_one(category_len, K)
        self.grid_bias_model = Model_two(grid_len, K)
        self.MLP_model = Model_two(2 * K, K)
        self.NeuMF_model = Model_one(2 * K, 1)

    def forward(self, category_input, grid_input):
        category_out = self.category_model(category_input)
        grid_out = self.grid_model(grid_input)
        SVD_out = category_out * grid_out
        bu = self.category_bias_model(category_input)
        bi = self.grid_bias_model(grid_input)
        SVD_out = SVD_out + bu + bi
        MLP_input = torch.cat((category_out, grid_out), 1)  # 横向拼接
        MLP_out = self.MLP_model(MLP_input)
        NeuMF_RS_input = torch.cat((SVD_out, MLP_out), 1)  # 横向拼接
        NeuMF_RS_out = self.NeuMF_model(NeuMF_RS_input)

        return NeuMF_RS_out

   这里的Model_one和Model_two定义的小模型都是大模型的组成部分,只要控制好其中输入输出的衔接即可。
   其中的dropout在这是用来防止过拟合的,不用关注,关注网络是如何写的就可以了。
太笨了,一开始完全不懂怎么写

  • 50
    点赞
  • 124
    收藏
    觉得还不错? 一键收藏
  • 14
    评论
首先,需要准备好红外图像和可见光图像的数据集。然后,可以按照以下步骤训练模型: 1. 定义多尺度自编码网络的结构,可以使用PyTorch中的nn.Module来实现。 2. 定义损失函数,可以使用MSE(均方误差)或其他适合的损失函数。 3. 定义优化器,可以使用Adam或其他适合的优化器。 4. 对数据集进行预处理,例如归一化、裁剪等。 5. 定义训练循环,包括前向传播、计算损失、反向传播、更新参数等步骤。 6. 在训练过程中,可以使用验证集来监控模型的性能,避免过拟合。 7. 在训练完成后,可以使用测试集来评估模型的性能。 以下是一个简单的示例代码: ```python import torch import torch.nn as nn import torch.optim as optim # 定义多尺度自编码网络 class AutoEncoder(nn.Module): def __init__(self): super(AutoEncoder, self).__init__() self.encoder = nn.Sequential( nn.Conv2d(3, 64, 3, stride=1, padding=1), nn.ReLU(), nn.MaxPool2d(2, stride=2), nn.Conv2d(64, 128, 3, stride=1, padding=1), nn.ReLU(), nn.MaxPool2d(2, stride=2), nn.Conv2d(128, 256, 3, stride=1, padding=1), nn.ReLU(), nn.MaxPool2d(2, stride=2), nn.Conv2d(256, 512, 3, stride=1, padding=1), nn.ReLU(), nn.MaxPool2d(2, stride=2), ) self.decoder = nn.Sequential( nn.ConvTranspose2d(512, 256, 3, stride=2, padding=1, output_padding=1), nn.ReLU(), nn.ConvTranspose2d(256, 128, 3, stride=2, padding=1, output_padding=1), nn.ReLU(), nn.ConvTranspose2d(128, 64, 3, stride=2, padding=1, output_padding=1), nn.ReLU(), nn.ConvTranspose2d(64, 3, 3, stride=2, padding=1, output_padding=1), nn.Sigmoid(), ) def forward(self, x): x = self.encoder(x) x = self.decoder(x) return x # 定义损失函数优化器 criterion = nn.MSELoss() optimizer = optim.Adam(model.parameters(), lr=0.001) # 加载数据集并进行预处理 # ... # 训练循环 for epoch in range(num_epochs): running_loss = 0.0 for i, data in enumerate(trainloader, 0): inputs, labels = data optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() running_loss += loss.item() if i % 10 == 9: # 每10个batch输出一次loss print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 10)) running_loss = 0.0 # 在验证集上测试模型 # ... print('Finished Training') ``` 以上代码仅供参考,实际训练过程中可能需要根据具体情况进行调整。同时,还需要注意模型的超参数选择、数据集划分等问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值