解决RuntimeError: Dimension out of range (expected to be in range of [-1, 0], but got 1)

问题描述:

x = [[0.1,0.2,0.1],
	[0.4,0.1,0.3]]
y = [1, 0]
loss_fn  = nn.CrossEntropyLoss()
loss = loss_fn(x, y)

x为特征矩阵,y为标签。
x对应维度应为batch_size x dim。
y对应维度应为batch_size。
当使用交叉熵时,当最后一个batch_size为1时。造成x维度变成1,y也为1。此时nn.CrossEntropyLoss()误将x识别成y产生如下报错。

RuntimeError: Dimension out of range (expected to be in range of [-1, 0], but got 1)

解决方法:

读取数据时,将最后一个batch舍弃。
例如:pytorch中torch.utils.data.dataloader的drop_last参数设置为True

参考:
[1] 【解决办法】torch交叉熵使用时遇到 Dimension [SEO实验室]
[2] Pytorch官方文档

你可能感兴趣的:(Bug,Pytorch,bug,深度学习,pytorch)