Python 索引器:维度超出范围(预期在[-1,0]范围内,但得到1)
我已经阅读了前面的一些问题,我得到了这个错误,可能与张量维度之间的差异有关,但因为这是我第一次尝试运行PyTorch,所以我来到这里,因为我对它几乎没有直觉。想要在一个基本的MNIST设置上运行一个非标准的数据集(我很确定我加载的很好),来搞乱它,看看是什么移动了什么Python 索引器:维度超出范围(预期在[-1,0]范围内,但得到1),python,machine-learning,pytorch,Python,Machine Learning,Pytorch,我已经阅读了前面的一些问题,我得到了这个错误,可能与张量维度之间的差异有关,但因为这是我第一次尝试运行PyTorch,所以我来到这里,因为我对它几乎没有直觉。想要在一个基本的MNIST设置上运行一个非标准的数据集(我很确定我加载的很好),来搞乱它,看看是什么移动了什么 Traceback (most recent call last): File "C:/Users/Administrator/Desktop/pytong/proj/pytorch_cnnv2.py", line 110, i
Traceback (most recent call last):
File "C:/Users/Administrator/Desktop/pytong/proj/pytorch_cnnv2.py", line 110, in <module>
loss = loss_func(output, b_y)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\torch\nn\modules\module.py", line 547, in __call__
result = self.forward(*input, **kwargs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\torch\nn\modules\loss.py", line 916, in forward
ignore_index=self.ignore_index, reduction=self.reduction)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\torch\nn\functional.py", line 1995, in cross_entropy
return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\torch\nn\functional.py", line 1316, in log_softmax
ret = input.log_softmax(dim)
IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)
其余代码、SAN导入和加载:
class CNNModel(nn.Module):
def __init__(self):
super(CNNModel, self).__init__()
# Convolution 1
self.cnn1 = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=5, stride=1, padding=0)
self.relu1 = nn.ReLU()
# Max pool 1
self.maxpool1 = nn.MaxPool2d(kernel_size=2)
# Convolution 2
self.cnn2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=5, stride=1, padding=0)
self.relu2 = nn.ReLU()
# Max pool 2
self.maxpool2 = nn.MaxPool2d(kernel_size=2)
# Fully connected
self.fc1 = nn.Linear(338 * 4 * 4, 5)
def forward(self, x):
# Convolution 1
out = self.cnn1(x)
print(out.shape)
out = self.relu1(out)
print(out.shape)
# Max pool 1
out = self.maxpool1(out)
print(out.shape)
# Convolution 2
out = self.cnn2(out)
print(out.shape)
out = self.relu2(out)
print(out.shape)
# Max pool 2
out = self.maxpool2(out)
print('++++++++++++++ out')
print(out.shape)
# out = out.reshape(-1, 169 * 4 * 4)
out = out.view(out.size(0), -1)
print(out.shape)
print('-----------------------')
# Linear function (readout)
out = self.fc1(out)
print(out.shape)
print('=======================')
return out
if __name__ == '__main__':
print("Number of train samples: ", len(train_data))
print("Number of test samples: ", len(test_data))
print("Detected Classes are: ", train_data.class_to_idx) # classes are detected by folder structure
model = CNNModel()
optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE)
loss_func = nn.CrossEntropyLoss()
# Training and Testing
for epoch in range(EPOCHS):
print(enumerate(train_data_loader))
for step, (x, y) in enumerate(train_data_loader):
b_x = Variable(x) # batch x (image)
b_y = Variable(y) # batch y (target)
# print('============ b_x')
# print(len(b_x))
# print(b_x.data)
# print('============ b_y')
# print(len(b_y))
# print(b_y.data)
output = model(b_x)[0]
loss = loss_func(output, b_y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if step % 50 == 0:
test_x = Variable(test_data_loader)
test_output, last_layer = model(test_x)
pred_y = torch.max(test_output, 1)[1].data.squeeze()
accuracy = sum(pred_y == test_y) / float(test_y.size(0))
print('Epoch: ', epoch, '| train loss: %.4f' % loss.data[0], '| test accuracy: %.2f' % accuracy)
加上我尝试用于诊断的打印输出:
torch.Size([100, 16, 60, 60])
torch.Size([100, 16, 60, 60])
torch.Size([100, 16, 30, 30])
torch.Size([100, 32, 26, 26])
torch.Size([100, 32, 26, 26])
++++++++++++++ out
torch.Size([100, 32, 13, 13])
torch.Size([100, 5408])
-----------------------
torch.Size([100, 5])
=======================
很可能是输出和真值标签格式不匹配。您需要包括更多详细信息,如所使用的损失函数、真值标签格式等。为了能够调试此问题在这一行:
output = model(b_x)[0]
[0]
将形状从[100,5]
更改为[5]
,而损失预期是另一种情况。只需删除它:
output = model(b_x)
这个答案非常适合评论,我想我打算用另一种方式回答这个问题。是的,很好,我预期会出现一些简单化的问题,但你用你的经验为我指出了正确的方向。有更多的错误,但我想我会从这里管理。谢谢
output = model(b_x)