criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(rnn.parameters(), lr=learning_rate)
for i, (images, labels) in enumerate(train_loader):
images = Variable(images.view(-1, sequence_length, input_size)).cuda()
# Forward + Backward + Optimize
optimizer.zero_grad()
outputs = rnn(images)
_, predicted = torch.max(outputs.data, 1)
loss = criterion(outputs, predicted)
loss.backward()
optimizer.step()
error happen with line loss = criterion(outputs, predicted)
AttributeError: ‘torch.cuda.LongTensor’ object has no attribute 'requires_grad’
how can I use criterion with predicted? thank you
u need to make labels a Variable
labels = Variable(labels).cuda()
thanks for your answer, before I have used :labels = Variable(labels).cuda(),
error also exist as:AttributeError: ‘torch.cuda.LongTensor’ object has no attribute 'requires_grad’
this error location:
loss = criterion(outputs, predicted)
I also used : labels.data = predicted, occur other errors!
u can’t use predicted to get loss, u should use labels, because u need to get loss by comparing ground truth and predicting label, the predict is outputs, and the ground truth is labels
loss = criterion(outputs, labels)
thanks for you!Well,you are right, but I attempt to do it with a new way.Now, I know how to modify:
…
, predicted = torch.max(outputs.data, 1)
labels.data.copy(predicted)
loss = criterion(outputs, labels)
…
thinks, SherlockLiaoSherlock