python - 尽管形状相同 : if not (target. size() == input.size()) 但出现类型错误: 'int' 对象不可调用

标签 python pytorch

这是我收到的错误消息。在第一行中,我输出了预测目标的形状。根据我的理解,错误是由于这些形状不一样而产生的,但在这里它们显然是一样的。

torch.Size([6890, 3]) torch.Size([6890, 3])

Traceback (most recent call last):
  File "train.py", line 251, in <module>
    main()
  File "train.py", line 230, in main
    train(net, training_dataset, targets, device, criterion, optimizer, epoch, args.epochs)
  File "train.py", line 101, in train
    loss = criterion(predicted, target.detach().cpu().numpy())
  File "/home/hb119056/.local/lib/python3.6/site-packages/torch/nn/modules/module.py", line 493, in __call__
    result = self.forward(*input, **kwargs)
  File "/home/hb119056/.local/lib/python3.6/site-packages/torch/nn/modules/loss.py", line 443, in forward
    return F.mse_loss(input, target, reduction=self.reduction)
  File "/home/hb119056/.local/lib/python3.6/site-packages/torch/nn/functional.py", line 2244, in mse_loss
    if not (target.size() == input.size()):
TypeError: 'int' object is not callable

我希望提供所有相关的上下文信息,如果没有,请告诉我。感谢您的任何建议!

编辑:这是发生此错误的代码部分:

        target = torch.from_numpy(np.load(file_dir + '/points/points{:03}.npy'.format(i))).to(device)
        rv = torch.zeros(12 * outputs.shape[0])

        for j in [x for x in range(10) if x != i]:
            source = torch.from_numpy(np.load(file_dir + '/points/points{:03}.npy'.format(j))).to(device)
            rv = factor.ransac(source, target, prob, n_iter, tol, device) # some self-written RANSAC-like method

        predicted = factor.predict(source, rv, outputs)
        print(target.shape, predicted.shape)
        loss = criterion(predicted, target.detach().cpu().numpy()) ## error occurs here

标准nn.MSELoss()

最佳答案

有点晚了,但也许对其他人有帮助。刚刚为自己解决了同样的问题。

正如 Alpha 在他的回答中所说,我们不能为 numpy 数组调用 .size() 。 但我们可以为张量调用 .size() 。 因此,我们需要将我们的目标设为张量。你可以这样做:

target = torch.from_numpy(target)

我正在使用 GPU,因此我还需要将目标发送到 GPU。你可以这样做:

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
target = target.to(device)

然后损失函数必须完美运行。

关于python - 尽管形状相同 : if not (target. size() == input.size()) 但出现类型错误: 'int' 对象不可调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57724134/

相关文章:

pytorch - 我怎样才能制作 torch 张量?

deep-learning - 为什么 torch 修剪实际上没有去除过滤器或重物?

python - 如何在 Python 中使用 imaplib 处理错误

python - 设置复制警告和隐藏链接

python : easy way to do geometric mean in python?

python - PyTorch 线性回归问题

python - 如何在 PyTorch 中打印模型摘要?

image-processing - 带填充的平均池的期望行为是什么?

python - NLTK:为一个词查找大小为 2k 的上下文

python - 文件更改事件网络共享