【问题标题】:IndexError: Target 1 is out of boundsIndexError:目标 1 超出范围
【发布时间】:2021-06-05 03:02:27
【问题描述】:

当我运行下面的程序时,它给了我一个错误。问题似乎出在损失函数中,但我找不到。我已经阅读了 nn.CrossEntropyLoss 的 Pytorch 文档,但仍然找不到问题。

图像尺寸为 (1 x 256 x 256), 批量大小为 1

我是 PyTorch 的新手,谢谢。

import torch
import torch.nn as nn
from PIL import Image
import numpy as np
torch.manual_seed(0)

x = np.array(Image.open("cat.jpg"))
x = np.expand_dims(x, axis = 0)
x = np.expand_dims(x, axis = 0)
x = torch.from_numpy(x)
x = x.type(torch.FloatTensor) # shape = (1, 1, 256, 256)

def Conv(in_channels, out_channels, kernel=3, stride=1, padding=0):
    return nn.Conv2d(in_channels, out_channels, kernel, stride, padding)

class model(nn.Module):
    def __init__(self):
        super(model, self).__init__()

        self.sequential = nn.Sequential(
            Conv(1, 3),
            Conv(3, 5),
            nn.Flatten(),
            nn.Linear(317520, 1),
            nn.Sigmoid()
        )

    def forward(self, x):
        y = self.sequential(x)
        return y

def compute_loss(y_hat, y):
    return nn.CrossEntropyLoss()(y_hat, y)

model = model()
y_hat = model(x)

loss = compute_loss(y_hat, torch.tensor([1]))

错误:

Traceback (most recent call last):
  File "D:/Me/AI/Models/test.py", line 38, in <module>
    **loss = compute_loss(y, torch.tensor([1]))**
  File "D:/Me/AI/Models/test.py", line 33, in compute_loss
    return nn.CrossEntropyLoss()(y_hat, y)
  File "D:\Softwares\Anaconda\envs\deeplearning\lib\site-packages\torch\nn\modules\module.py", line 1054, in _call_impl
    return forward_call(*input, **kwargs)
  File "D:\Softwares\Anaconda\envs\deeplearning\lib\site-packages\torch\nn\modules\loss.py", line 1120, in forward
    return F.cross_entropy(input, target, weight=self.weight,
  File "D:\Softwares\Anaconda\envs\deeplearning\lib\site-packages\torch\nn\functional.py", line 2824, in cross_entropy
    return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
**IndexError: Target 1 is out of bounds.**

Process finished with exit code 1

【问题讨论】:

    标签: python python-3.x pytorch


    【解决方案1】:

    这看起来像一个二元分类器模型:cat or not cat。但是您正在使用 CrossEntropyLoss,当您有超过 2 个目标类时使用它。所以你应该使用Binary Cross Entropy Loss

    def compute_loss(y_hat, y):
        return nn.BCELoss()(y_hat, y)
    

    【讨论】:

      【解决方案2】:

      我认为改变
      nn.Linear(317520, 1) -> nn.Linear(317520, 2)

      【讨论】:

        【解决方案3】:

        试试 loss = compute_loss(y_hat, torch.tensor([0]))

        【讨论】:

        • 它可以工作,但 0 以外的任何东西都不能。
        • @SanskarKumar Python 列表和元组使用 0 作为列表或元组内的第一个索引。如果您的列表或元组中只有 1 个元素,则 0 以上的所有内容都将返回 IndexError,0 将返回第一个元素。如果对您有用,请将答案标记为已接受:)
        • 在讨论哪个列表/元组?
        • 任何列表。例如:考虑:my_list = ['hello world']my_list[0] 将返回“hello world”,my_list[1] 将返回 IndexError
        猜你喜欢
        • 2022-07-10
        • 2021-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-09
        • 2016-06-03
        • 2016-08-12
        • 2015-08-06
        相关资源
        最近更新 更多