在使用交叉熵计算损失时出现IndexError: Target -1 is out of bounds 错误
这里的-1是一个可变的任意负数。 前提交叉熵有两种方式:
# Example of target with class indices
loss = nn.CrossEntropyLoss()
input = torch.randn(3, 5, requires_grad=True)
target = torch.empty(3, dtype=torch.long).random_(5)
output = loss(input, target)
output.backward()
# Example of target with class probabilities
input = torch.randn(3, 5, requires_grad=True)
target = torch.randn(3, 5).softmax(dim=1)
output = loss(input, target)
output.backward()
第一种是指定了每个类,第二种是通过one hot 进行编码的。其实都转化为第一种
出现场景: 当在看Segment的deeplabv3_resnet50网络时,损失函数使用的是交叉熵。这里输入的是 x=(4,21,480,480) y=(4,480,480) 这里的意思就是将图片的480480的像素点进行分类,并且每个像素点有21个类别的概率。这就是x表示的意思。 y的话表示4个数量,480480像素所属的概率。那么这里使用的交叉熵的第一种。但是第一种里面的target值不能为负数,如果是负数就会出现上面的问题。还有这种: Target -6 is out of bounds. 随机生成class indices 推荐:
target1 = torch.randint(low=0, high=2, size=(4, 480, 480), dtype=torch.int64)