Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 一维张量的Pytorch交叉熵_Python_Pytorch - Fatal编程技术网

Python 一维张量的Pytorch交叉熵

Python 一维张量的Pytorch交叉熵,python,pytorch,Python,Pytorch,我在这里遗漏了一点:为什么无交叉熵不适用于一维张量 from torch import Tensor X =Tensor([1.0,2.0,3.0])

我在这里遗漏了一点:为什么
无交叉熵
不适用于一维张量

from  torch  import Tensor                                                                                                                                     
X =Tensor([1.0,2.0,3.0])                                                                                                                                       
labs = Tensor([2,2,3])                                                                                                                                         
loss = nn.CrossEntropyLoss().forward(X,labs)

为什么会失败?应该更改哪些内容以获得所需的结果?

如果您看到文档

输入:(N,C),其中C=类数

目标:(N)当每个值为0时,问题将在pytorch论坛中讨论。正如Prajot正确指出的那样,通常一个输入样本有三个不同的标签是没有意义的,因此每个输入只接受一个标签。论坛上的帖子讨论了可能有意义的高级用例的变通方法。

CrossEntropyLoss希望输入的形式为
(minibatch,C)
(minibatch,C,d_1,d_2,…,d_K)
_stacklevel, dtype)
   1315         dim = _get_softmax_dim('log_softmax', input.dim(), _stacklevel)
   1316     if dtype is None:
-> 1317         ret = input.log_softmax(dim)
   1318     else:
   1319         ret = input.log_softmax(dim, dtype=dtype)

IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)
Input: (N,C) where C = number of classes
Target: (N) where each value is 0 <= targets[i] <= C-1
Output: scalar. If reduce is False, then (N) instead.
import torch
from  torch  import Tensor                                                                                                                                 
X =Tensor([[1.0,2.0,3.0]])   #2D                                                                                                                                   
labs = torch.LongTensor([2]) # 0 <= targets[i] <= C-1                                                                                                                          
loss = nn.CrossEntropyLoss().forward(X,labs)