【问题标题】:Tensor Size Miss match on loss function张量大小未匹配损失函数
【发布时间】:2020-10-29 08:40:25
【问题描述】:

1: 当尝试使用批量大小执行 pytorch 训练序列时,当 nn 输出和批次通过 MSEloss 函数时,我的损失函数似乎出错。

2: 试图搜索 nn 填充,但是这不是 covnet 而是自动编码器,类似的堆栈溢出问题没有产生结果。

3: 神经网络:

class Net(nn.Module):
    def __init__(self, input_dim=10):
        super().__init__()
        self.fc1 = nn.Linear(input_dim, int(0.75 * input_dim))
        self.fc2 = nn.Linear(int(0.75 * input_dim), int(0.5 * input_dim))
        self.fc3 = nn.Linear(int(0.5 * input_dim), int(0.33 * input_dim))
        self.fc4 = nn.Linear(int(0.33 * input_dim), int(0.25 * input_dim))
        self.fc5 = nn.Linear(int(0.25 * input_dim), int(0.33 * input_dim))
        self.fc6 = nn.Linear(int(0.33 * input_dim), int(0.5 * input_dim))
        self.fc7 = nn.Linear(int(0.5 * input_dim), int(0.75 * input_dim))
        self.fc8 = nn.Linear(int(0.75 * input_dim), input_dim)

    def forward(self, x):
        x = torch.tanh(self.fc1(x))
        x = torch.tanh(self.fc2(x))
        x = torch.tanh(self.fc3(x))
        x = torch.tanh(self.fc4(x))
        x = torch.tanh(self.fc5(x))
        x = torch.tanh(self.fc6(x))
        x = torch.tanh(self.fc7(x))
        x = self.fc8(x)
        return torch.softmax(x, dim=1)

火车方法:

def train(net, x_train, x_opt, BATCH_SIZE, EPOCHS, input_dim):
    outputs = 0
    mse = 0
    optimizer = optim.SGD(net.parameters(), lr=0.001)
    loss_function = nn.MSELoss()

    for epoch in range(EPOCHS):
        for i in tqdm(range(0, len(x_train), BATCH_SIZE)):
            batch_x = x_train[i:i + BATCH_SIZE]
            # print("bx", batch_x.size())

            batch_y = x_opt[i:i + BATCH_SIZE]
            # print("by", batch_y.size())
            net.zero_grad()
            # batch_x.view(batch_y.shape[0])
            outputs = net(batch_x)
            # print('out', outputs)

            loss = loss_function(outputs, batch_y)
            loss.backward()
            optimizer.step()  # Does the update

        print(f"Epoch: {epoch}. Loss: {loss}")

错误:

 99%|█████████▉| 1452/1466 [00:02<00:00, 718.09it/s]B:\tools and software\Anaconda\envs\pysyft-pytorch\lib\site-packages\torch\nn\modules\loss.py:431: UserWarning: Using a target size (torch.Size([39, 10])) that is different to the input size (torch.Size([38, 10])). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size.
  return F.mse_loss(input, target, reduction=self.reduction)
100%|█████████▉| 1465/1466 [00:02<00:00, 718.36it/s]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "B:\tools and software\PyCharm 2020.1\plugins\python\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "B:\tools and software\PyCharm 2020.1\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "B:/projects/openProjects/githubprojects/BotnetTrafficAnalysisFederaedLearning/anomaly-detection/pytorch_conversion.py", line 154, in <module>
    input_dim=input_dim)
  File "B:/projects/openProjects/githubprojects/BotnetTrafficAnalysisFederaedLearning/anomaly-detection/pytorch_conversion.py", line 64, in train
    loss = loss_function(outputs, batch_y)
  File "B:\tools and software\Anaconda\envs\pysyft-pytorch\lib\site-packages\torch\nn\modules\module.py", line 532, in __call__
    result = self.forward(*input, **kwargs)
  File "B:\tools and software\Anaconda\envs\pysyft-pytorch\lib\site-packages\torch\nn\modules\loss.py", line 431, in forward
    return F.mse_loss(input, target, reduction=self.reduction)
  File "B:\tools and software\Anaconda\envs\pysyft-pytorch\lib\site-packages\torch\nn\functional.py", line 2215, in mse_loss
    expanded_input, expanded_target = torch.broadcast_tensors(input, target)
  File "B:\tools and software\Anaconda\envs\pysyft-pytorch\lib\site-packages\torch\functional.py", line 52, in broadcast_tensors
    return torch._C._VariableFunctions.broadcast_tensors(tensors)
RuntimeError: The size of tensor a (38) must match the size of tensor b (39) at non-singleton dimension 0

【问题讨论】:

    标签: numpy machine-learning pytorch federated-learning pysyft


    【解决方案1】:

    错误似乎是说目标和输出的批量大小不一样您是否尝试打印目标和输出的大小。如果是这样,结果如何。此外,您可能希望将输入的大小打印到模型中,以查看那里是否有东西。很抱歉将此发布到我无法评论的答案。

    【讨论】:

    • 在原始代码上,所做的是让 TensorFlow 模型返回一个 numpy 预测数组,然后从验证集中减去预测集。这将用于产生均方误差。但是,输出形状远小于验证集。
    • 我认为这是因为您的 x_opts 列表或其他任何列表都比 x_train 长,因此它无法填充相同数量的批次。您能否检查以确保您的 x_opts 大小与您的 x_train 匹配。
    • 不,大小不一样,但我现在可以继续前进。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2021-03-07
    • 2019-01-20
    • 2018-09-18
    • 2021-07-23
    • 2019-06-24
    • 2017-09-02
    • 2021-11-20
    • 2019-02-11
    相关资源
    最近更新 更多