python IndexError:训练pytorch模型时目标25超出界限

pxy2qtax  于 2023-01-12  发布在  Python
关注(0)|答案(1)|浏览(259)

我有一个自定义的公司数据集,它有14个特征和1个输出标签,有5个类[9, 12, 15, 18, 21, 25]。我已经建立了一个线性模型,使用以下定义:

class HourPredictor(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(in_features=14, out_features=64)
        self.fc2 = nn.Linear(in_features=64, out_features=32)
        self.output = nn.Linear(in_features=32, out_features=5)
    
    def forward(self, x):
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.output(x)
        return x

但是当我尝试训练模型时,它给了我这个索引错误:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
File <timed exec>:9

File ~/.envs/.vas/lib/python3.10/site-packages/torch/nn/modules/module.py:1194, in Module._call_impl(self, *input, **kwargs)
   1190 # If we don't have any hooks, we want to skip the rest of the logic in
   1191 # this function, and just call forward.
   1192 if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1193         or _global_forward_hooks or _global_forward_pre_hooks):
-> 1194     return forward_call(*input, **kwargs)
   1195 # Do not call functions when jit is used
   1196 full_backward_hooks, non_full_backward_hooks = [], []

File ~/.envs/.vas/lib/python3.10/site-packages/torch/nn/modules/loss.py:1174, in CrossEntropyLoss.forward(self, input, target)
   1173 def forward(self, input: Tensor, target: Tensor) -> Tensor:
-> 1174     return F.cross_entropy(input, target, weight=self.weight,
   1175                            ignore_index=self.ignore_index, reduction=self.reduction,
   1176                            label_smoothing=self.label_smoothing)

File ~/.envs/.vas/lib/python3.10/site-packages/torch/nn/functional.py:3026, in cross_entropy(input, target, weight, size_average, ignore_index, reduce, reduction, label_smoothing)
   3024 if size_average is not None or reduce is not None:
   3025     reduction = _Reduction.legacy_get_string(size_average, reduce)
-> 3026 return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index, label_smoothing)

IndexError: Target 25 is out of bounds.
h7appiyu

h7appiyu1#

TL;DR

您需要将标签从[9, 12, 15, 18, 25]Map到[0, 1, 2, 3, 4]
你的模型并不知道它预测的五个类都有“名字”,例如,第一个类是“9”,第三个是“15”,以此类推,它只输出这五个“桶”的概率。
你可以将“名字”Map到预测类概率向量的索引中。这些索引应该是有效的:在[0, 4]的范围内。

相关问题