torch.tensor与torch.Tensor的使用说明

问题描述

在使用pytorch进行softmax,得出每个类别的预测值,再进行NLLloss计算损失函数时,如果真实值是由torch.Tensor构造出来的,会报错:
代码如下:

import torch.nn as nn

torch.manual_seed(1)

input = torch.randn(3,3)#随机化输入张量

sm = nn.Softmax(dim=1)#构造softmax层

input = torch.log(sm(input))#计算softmax后预测值的对数

loss = nn.NLLLoss()#定义NLLLoss类
y = torch.Tensor([0,2,1])#此处用torch.Tensor构造真实预测类别的张量
cost = loss(input, y)#计算损失
print(cost)

然而运行一下,报错:
RuntimeError: expected scalar type Long but found Float

然而,如果把

y = torch.Tensor([0,2,1])

改成

y = torch.tensor([0,2,1])
或者是
y = torch.LongTensor([0,2,1])

程序正常运行,打印出tensor(0.8347)

原因

有点奇怪哈,这是为什么呢,根据报错提示,我们试着打印一下torch.tensor构造的张量类型,和torch.Tensor构造的张量类型

import torch
y1 = torch.Tensor([0,2,1])
y2 = torch.tensor([0,2,1])
print(y1.type())
print(y2.type())

输出结果
(y1) torch.FloatTensor
(y2) torch.LongTensor
再结合之前的报错,我们找到原因了,loss接收的真实值类型为LongTensor,而torch.Tensor默认构造的是FloatTensor类型。
这是一个在计算损失函数时需要注意的细节,希望大家不要踩坑~

更多torch.Tensor与torch.tensor的区别请参考:
torch.Tensor和torch.tensor的区别

猜你喜欢

转载自blog.csdn.net/weixin_45577864/article/details/119153317