我正在使用Windows上的PyTorch在FashionMNIST上训练一个简单的感知器。当我使用cpu运行它时,它执行得很好,但是在gpu上,它会抛出“无效的向量下标”错误。我在做什么错了?
我的代码:
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(28 * 28, 10)
def forward(self, x):
x = x.view(-1, 28 * 28)
x = self.fc1(x)
return x
net = Net().to(device)
optimizer = torch.optim.Adam(net.parameters(), lr=0.001)
criterion = torch.nn.CrossEntropyLoss()
epochs = 1
for epoch in range(epochs):
running_loss = 0
for i, data in enumerate(trainLoader, 0):
x, y = data
z = net(x.to(device))
loss = criterion(z, y.to(device))
optimizer.zero_grad()
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 2000 == 1999:
print(epoch + 1, i + 1, running_loss / 2000)
running_loss = 0
错误日志:
File "C:/Users/tarpt/Desktop/deep1.py", line 45, in <module>
loss.backward()
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\torch\tensor.py", line 102, in backward
torch.autograd.backward(self, gradient, retain_graph, create_graph)
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\torch\autograd\__init__.py", line 90, in backward
allow_unreachable=True) # allow_unreachable flag
RuntimeError: invalid vector<T> subscript