Pytorch | 训练模型计算损失时“log_softmax_lastdim_kernel_impl“ not implemented for ‘Long‘报错及解决

问题

下面这段代码会报错:"log_softmax_lastdim_kernel_impl" not implemented for 'Long'

criterion = nn.CrossEntropyLoss()
x=torch.tensor([[0,1,0,5]])
y=torch.tensor([3])
l=criterion(x,y)

解决方案

将x=torch.tensor([[0,1,0,5]])

改成x=torch.tensor([[0,1,0,5]],dtype=torch.float32)

解决过程

可以用a.dtype()查看张量a的数据类型

我找到了一个可以跑通的模型,其中:

print(outputs.dtype)
print(labels.dtype)

而在错误的代码中,output和labels的类型分别是:

 

因此,需要将output的类型修改成float32.修改源代码如下:

criterion = nn.CrossEntropyLoss()
x=torch.tensor([[0,1,0,5]],dtype=torch.float32)
y=torch.tensor([3])
print(x.dtype)
print(y.dtype)
criterion(x,y)

 

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务