【问题标题】:cnn IndexError: Target 2 is out of boundscnn IndexError:目标 2 超出范围
【发布时间】:2020-02-17 09:55:45
【问题描述】:

执行代码后出现此错误,似乎代码的以下部分引发了此错误。我尝试了不同的方法,但没有什么能解决它。误差由损失函数给出。

for i, data in enumerate(train_loader, 0):


      #  import pdb;pdb.set_trace()
        inputs, labels = data
        print(type(inputs))
        for input in inputs:
            inputs = torch.Tensor(input)
        inputs, labels= Variable(inputs), Variable(labels)
        inputs=inputs.unsqueeze(1)
        optimizer.zero_grad()
        outputs = net(inputs)
        #import pdb;pdb.set_trace()
        loss_size = loss(outputs, labels)
        loss_size.backward()
        optimizer.step()

        running_loss += loss_size.data[0]
        total_train_loss += loss_size.data[0]

        if (i + 1) % (print_every + 1) == 0:
            print("Epoch {}, {:d}% \t train_loss: {:.2f} took: {:.2f}s".format(
                    epoch+1, int(100 * (i+1) / n_batches), running_loss / print_every, time.time() - start_time))
            running_loss = 0.0
            start_time = time.time()
--------------------------------------------------------------------------- IndexError                                Traceback (most recent call
last) <ipython-input-10-7d1b8710defa> in <module>
      1 CNN = Net()
----> 2 trainNet(CNN, learning_rate=0.001)
      3 #test()

<ipython-input-7-3208c0794681> in trainNet(net, learning_rate)
     23             outputs = net(inputs)
     24             #import pdb;pdb.set_trace()
---> 25             loss_size = loss(outputs, labels)
     26             loss_size.backward()
     27             optimizer.step()

~\Documents\Anaconda3\lib\site-packages\torch\nn\modules\module.py in
__call__(self, *input, **kwargs)
    530             result = self._slow_forward(*input, **kwargs)
    531         else:
--> 532             result = self.forward(*input, **kwargs)
    533         for hook in self._forward_hooks.values():
    534             hook_result = hook(self, input, result)

~\Documents\Anaconda3\lib\site-packages\torch\nn\modules\loss.py in
forward(self, input, target)
    914     def forward(self, input, target):
    915         return F.cross_entropy(input, target, weight=self.weight,
--> 916                                ignore_index=self.ignore_index, reduction=self.reduction)
    917 
    918 

~\Documents\Anaconda3\lib\site-packages\torch\nn\functional.py in
cross_entropy(input, target, weight, size_average, ignore_index,
reduce, reduction)    2019     if size_average is not None or reduce
is not None:    2020         reduction =
_Reduction.legacy_get_string(size_average, reduce)
-> 2021     return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)    2022     2023 

~\Documents\Anaconda3\lib\site-packages\torch\nn\functional.py in
nll_loss(input, target, weight, size_average, ignore_index, reduce,
reduction)    1836                          .format(input.size(0),
target.size(0)))    1837     if dim == 2:
-> 1838         ret = torch._C._nn.nll_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)    1839     elif dim == 4:    1840         ret = torch._C._nn.nll_loss2d(input, target,
weight, _Reduction.get_enum(reduction), ignore_index)
IndexError: Target 2 is out of bounds.

IndexError: 目标 2 超出范围。

【问题讨论】:

  • 最后一个(softmax)层有多少个单元?您的数据中有哪些可能的目标标签?
  • 可能的目标标签是 Ydrone 和 Ndrone,即总共两个类别

标签: python pytorch


【解决方案1】:

我遇到了同样的问题。问题是通过改变类的数量来解决的。

num_classes = 10(改为实际班级编号,而不是1)

【讨论】:

    【解决方案2】:

    您应该更改类数 = 3。
    您可能将 1 和 2 作为类标签,因此您必须尝试将我们的模型网络类中的输出数量设置为 2,但它应该是 3,因为这是 pytorch 的工作方式。 2 类意味着您将 0 和 1 作为类标签。但是由于您将 1,2 作为类标签,因此您应该将其设为 3 类 (0,1,2) 分类问题。 假设这是您的网络课程:

    class Net(nn.Module):
        def __init__(self):
            super(Net, self).__init__()
    
            self.layer_1 = nn.Linear(100, 10)
            self.layer_2 = nn.Linear(10, 2)
    
        def forward(self, x):
            x = self.layer_1(x)
            x = nn.relu(x)
            x = self.layer_2(x)
            x = nn.relu(x)
    
            return x
    

    所以,你只需修改 layer_2 如下:
    self.layer_2 = nn.Linear(10, 3)
    这应该可以。

    【讨论】:

      【解决方案3】:

      问题与您的类标签的值有关。您可以在这里找到一个很好的解释和解决方案: IndexError: Target is out of bounds

      【讨论】:

        猜你喜欢
        • 2022-07-10
        • 2021-01-18
        • 1970-01-01
        • 1970-01-01
        • 2019-12-09
        • 2013-07-16
        • 1970-01-01
        • 2018-10-31
        • 1970-01-01
        相关资源
        最近更新 更多