IndexError: invalid index of a 0-dim tensor. Use `tensor.item()` in Python or `tensor.item<T>()` in

使用python pytorch框架出现问题:

IndexError: invalid index of a 0-dim tensor. Use tensor.item() in Python or tensor.item() in C++ to convert a 0-dim tensor to a number

修改loss.data[0]为loss.item()

例:

if (i+1) % 100 == 0:
            print ('Epoch [%d/%d], Step [%d/%d], Loss: %.4f' 
                   %(epoch+1, num_epochs, i+1, len(train_dataset)//batch_size, loss.data[0]))

修改为

if (i+1) % 100 == 0:
    print ('Epoch [%d/%d], Step [%d/%d], Loss: %.4f' 
           %(epoch+1, num_epochs, i+1, len(train_dataset)//batch_size, loss.item()))

你可能感兴趣的:(DeepLearning学习,python,深度学习,机器学习)