我对 Pytorch 如何处理单热向量感到非常困惑。在本 教程 中,神经网络将生成一个单热向量作为其输出。据我了解,教程中神经网络的示意结构应该是这样的:
但是, labels
不是单热矢量格式。我得到以下 size
print(labels.size())
print(outputs.size())
output>>> torch.Size([4])
output>>> torch.Size([4, 10])
奇迹般地,我将 outputs
和 labels
传递给 criterion=CrossEntropyLoss()
,完全没有错误。
loss = criterion(outputs, labels) # How come it has no error?
我的假设:
也许 pytorch 会自动将 labels
转换为单热矢量形式。因此,我尝试在将标签传递给损失函数之前将其转换为单热向量。
def to_one_hot_vector(num_class, label):
b = np.zeros((label.shape[0], num_class))
b[np.arange(label.shape[0]), label] = 1
return b
labels_one_hot = to_one_hot_vector(10,labels)
labels_one_hot = torch.Tensor(labels_one_hot)
labels_one_hot = labels_one_hot.type(torch.LongTensor)
loss = criterion(outputs, labels_one_hot) # Now it gives me error
但是,我收到以下错误
RuntimeError:/opt/pytorch/pytorch/aten/src/THCUNN/generic/ClassNLLCriterion.cu:15 不支持多目标
那么,在 Pytorch
中不支持单热向量? How does Pytorch
calculates the cross entropy
for the two tensor outputs = [1,0,0],[0,0,1]
and labels = [0,2]
?目前对我来说完全没有意义。
原文由 Raven Cheuk 发布,翻译遵循 CC BY-SA 4.0 许可协议
PyTorch 在其文档中声明
CrossEntropyLoss
换句话说,它有你的
to_one_hot_vector
概念上内置的功能CEL
并且不公开单热 API。请注意,与存储类标签相比,one-hot 向量的内存效率较低。如果您获得了单热向量并且需要转到类标签格式(例如与
CEL
兼容),您可以使用argmax
如下所示: