在pytorch中训练多输出回归模型

时间:2021-06-17 01:01:29

标签: python neural-network regression loss

我想要一个包含 3 个回归输出的模型,例如下面的虚拟示例:

import torch

class MultiOutputRegression(torch.nn.Module):

    def __init__(self):
        super(MultiOutputRegression, self).__init__()
        self.linear1 = torch.nn.Linear(1, 10)
        self.linear2 = torch.nn.Linear(10, 10)
        self.linear3 = torch.nn.Linear(3, 3)

    def forward(self, x):
        x = self.linear1(x)
        x = self.linear2(x)
        x = self.linear3(x)
        return x

假设我想训练它执行一个虚拟任务,例如,给定输入 x 返回 [x, 2x, 3x]

定义标准和损失后,我们可以使用以下数据对其进行训练:

for i in range(1, 100, 2):
    x_train = torch.tensor([i, i + 1]).reshape(2, 1).float()
    y_train = torch.tensor([[j, 2 * j] for j in x_train]).float()
    y_pred = model(x_train)
    # todo: perform training iteration 

第一次迭代的样本数据为:

x_train
tensor([[1.],
        [2.]])
y_train
tensor([[1., 2., 3.],
        [2., 4., 6.]])

如何定义合适的损失和标准来训练神经网络? 感谢您的帮助

0 个答案:

没有答案