首页 > 解决方案 > 将 torch.nn.CrossEntropyLoss 与 label as int 和 prob 张量进行比较会产生错误

问题描述

我有这个标准:

criterion = nn.CrossEntropyLoss()

在训练阶段我有:

label = tensor([0.])
outputs = tensor([[0.0035, 0.0468]], grad_fn=<AddmmBackward>)

当我尝试比较它们时:

 criterion(outputs, label)

我收到此错误:

    ret = torch._C._nn.nll_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
RuntimeError: Expected object of scalar type Long but got scalar type Float for argument #2 'target' in call to _thnn_nll_loss_forward

标签: pytorch

解决方案


nn.CrossEntropyLoss期望它的label输入是 typetorch.Long而不是torch.Float.
请注意,此行为与预期与输入具有相同类型的nn.BCELoss位置相反。target

如果您只是.从标签中删除 :

label = torch.tensor([0])  # no . after 0 - now it is an integer

pytorch 会自动创建labeltorch.Long类型,你没问题:

In [*]: criterion(outputs, torch.tensor([0]))
Out[*]: tensor(0.7150)

评论planet_plutoCraig.Li的其他答案:

  1. 投射现有张量的更一般的方法是使用.to(...)
label = torch.tensor([0]).to(dtype=torch.long)

但是,create-and-casting 并不是一种非常有效的处理方式:想想看,你让 pytroch 创建一个torch.float张量,然后将其转换为torch.long.

  1. dtype或者,您可以在创建张量时明确定义所需的:
label = torch.tensor([0.], dtype=torch.long)

这种方式 pytorch 创建label所需的dtype并且不需要第二阶段的铸造。


推荐阅读