python - Pytorch:运行时错误:预期的 dtype Float 但得到了 dtype Long

标签 python deep-learning pytorch backpropagation

在 Pytorch 中构建简单的神经网络时,我遇到了这个奇怪的错误。我不明白这个错误以及为什么在向后函数中考虑 Long 和 Float 数据类型。有没有人遇到过这种情况?谢谢你的帮助。

Traceback (most recent call last):
  File "test.py", line 30, in <module>
    loss.backward()
  File "/home/liuyun/anaconda3/envs/torch/lib/python3.7/site-packages/torch/tensor.py", line 198, in backward
    torch.autograd.backward(self, gradient, retain_graph, create_graph)
  File "/home/liuyun/anaconda3/envs/torch/lib/python3.7/site-packages/torch/autograd/__init__.py", line 100, in backward
    allow_unreachable=True)  # allow_unreachable flag
RuntimeError: expected dtype Float but got dtype Long (validate_dtype at /opt/conda/conda-bld/pytorch_1587428398394/work/aten/src/ATen/native/TensorIterator.cpp:143)
frame #0: c10::Error::Error(c10::SourceLocation, std::string const&) + 0x4e (0x7f5856661b5e in /home/liuyun/anaconda3/envs/torch/lib/python3.7/site-packages/torch/lib/libc10.so)
frame #1: at::TensorIterator::compute_types() + 0xce3 (0x7f587e3dc793 in /home/liuyun/anaconda3/envs/torch/lib/python3.7/site
-packages/torch/lib/libtorch_cpu.so)
frame #2: at::TensorIterator::build() + 0x44 (0x7f587e3df174 in /home/liuyun/anaconda3/envs/torch/lib/python3.7/site-packages
/torch/lib/libtorch_cpu.so)
frame #3: at::native::smooth_l1_loss_backward_out(at::Tensor&, at::Tensor const&, at::Tensor const&, at::Tensor const&, long)
 + 0x193 (0x7f587e22cf73 in /home/liuyun/anaconda3/envs/torch/lib/python3.7/site-packages/torch/lib/libtorch_cpu.so)
frame #4: <unknown function> + 0xe080b7 (0x7f58576960b7 in /home/liuyun/anaconda3/envs/torch/lib/python3.7/site-packages/torc
h/lib/libtorch_cuda.so)
frame #5: at::native::smooth_l1_loss_backward(at::Tensor const&, at::Tensor const&, at::Tensor const&, long) + 0x16e (0x7f587
e23569e in /home/liuyun/anaconda3/envs/torch/lib/python3.7/site-packages/torch/lib/libtorch_cpu.so)
frame #6: <unknown function> + 0xed98af (0x7f587e71c8af in /home/liuyun/anaconda3/envs/torch/lib/python3.7/site-packages/torc
h/lib/libtorch_cpu.so)
frame #7: <unknown function> + 0xe22286 (0x7f587e665286 in /home/liuyun/anaconda3/envs/torch/lib/python3.7/site-packages/torc
h/lib/libtorch_cpu.so)
这是源代码:
import torch
import torch.nn as nn
import numpy as np
import torchvision
from torchvision import models
from UTKLoss import MultiLoss
from ipdb import set_trace

# out features [13, 2, 5]
model_ft = models.resnet18(pretrained=True)
num_ftrs = model_ft.fc.in_features
model_ft.fc = nn.Linear(num_ftrs, 20)
model_ft.cuda()

criterion = MultiLoss()
optimizer = torch.optim.Adam(model_ft.parameters(), lr = 1e-3)

image = torch.randn((1, 3, 128, 128)).cuda()
age = torch.randint(110, (1,)).cuda()
gender = torch.randint(2, (1,)).cuda()
race = torch.randint(5, (1,)).cuda()
optimizer.zero_grad()
output = model_ft(image)
age_loss, gender_loss, race_loss = criterion(output, age, gender, race)
loss = age_loss + gender_loss + race_loss
loss.backward()
optimizer.step()
这是我定义的损失函数
import torch
import torch.nn as nn
import torch.nn.functional as F


class MultiLoss(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, output, age, gender, race):
        age_pred = output[:, :13]
        age_pred = torch.sum(age_pred, 1)
        gender_pred = output[:, 13: 15]
        race_pred = output[:, 15:]
        age_loss = F.smooth_l1_loss(age_pred.view(-1, 1), age.cuda())
        gender_loss = F.cross_entropy(gender_pred, torch.flatten(gender).cuda(), reduction='sum')
        race_loss = F.cross_entropy(race_pred, torch.flatten(race).cuda(), reduction='sum')
        return age_loss, gender_loss, race_loss

最佳答案

更改 criterion拨电至:

age_loss, gender_loss, race_loss = criterion(output, age.float(), gender, race)
如果您查看您的错误,我们可以将其追溯到:
frame #3: at::native::smooth_l1_loss_backward_out
在 MultiLoss 类中,smooth_l1_lossage 合作.所以我将它的类型更改为 float(因为预期的 dtype 是 Fl​​oat),同时将它传递给 criterion .您可以检查年龄是 torch.int64 (即 torch.long )通过打印 age.dtype执行此操作后,我没有收到错误消息。希望能帮助到你。

关于python - Pytorch:运行时错误:预期的 dtype Float 但得到了 dtype Long,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62726792/

相关文章:

python - 在 Keras LSTM 中获取每个时间步的输出

Python,机器学习: Are there any API that can split dataset and shuffle?

python - torch torch .load ModuleNotFoundError : No module named 'utils'

machine-learning - 在 PyTorch 中使用 WeightedRandomSampler

python - PyTorch:如何将 DataLoaders 用于自定义数据集

Python 和 SQLite : insert into table

python - 如果超过最大值,则获取开始和停止之间的数字并重新启动计数器

python - 为什么在达到 200 万个单词时向 gensim 词典添加文档会变慢?

python - 无法打开目录中的音频文件

machine-learning - 损失图中step的含义是什么