Python 索引器:目标1超出范围

Python 索引器:目标1超出范围,python,python-3.x,pytorch,Python,Python 3.x,Pytorch,当我运行下面的程序时,它会给我一个错误。问题似乎出在损失函数中,但我找不到它。我已经阅读了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

当我运行下面的程序时,它会给我一个错误。问题似乎出在损失函数中,但我找不到它。我已经阅读了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

回溯(最近一次呼叫最后一次):
文件“D:/Me/AI/Models/test.py”,第38行,在
**损耗=计算损耗(y,火炬张量([1]))**
文件“D:/Me/AI/Models/test.py”,第33行,计算损耗
返回nn.CrossEntropyLoss()(y_hat,y)
文件“D:\Softwares\Anaconda\envs\deeplearning\lib\site packages\torch\nn\modules\module.py”,第1054行,在调用impl中
返回转发呼叫(*输入,**kwargs)
文件“D:\Softwares\Anaconda\envs\deeplearning\lib\site packages\torch\nn\modules\loss.py”,第1120行,向前
返回F.交叉熵(输入,目标,权重=自身权重,
文件“D:\Softwares\Anaconda\envs\deeplearning\lib\site packages\torch\nn\functional.py”,第2824行,交叉熵
返回火炬。交叉熵损失(输入、目标、权重、减少。获取枚举(减少),忽略索引)
**索引器:目标1超出范围**
进程已完成,退出代码为1
试试看
loss=compute\u loss(y\u hat,torch.tensor([0]))

这看起来像一个二元分类器模型:cat还是not cat。但是您使用的是CrossEntropyLoss,当您有两个以上的目标类时使用。所以您应该使用的是


它可以工作,但除0以外的任何内容都不能工作。@SanskarKumar Python列表和元组使用0作为列表或元组中的第一个索引。如果列表或元组中只有1个元素,则0以上的所有内容都将返回索引器,0将返回第一个元素。如果对您有效,请将答案标记为已接受:)你在谈论哪个列表/元组?任何列表。例如:考虑:
my_list=['hello world']
<代码>我的列表[0]将返回“hello world”,而
我的列表[1]
将返回Indexer Ror
def compute_loss(y_hat, y):
    return nn.BCELoss()(y_hat, y)