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

在使用PyTorch框架的时候运行以下的代码

        plt.text(0.5, 0, 'Loss = %.4f' % loss.data[0], fontdict={'size': 20, 'color': 'red'})

运行的结果时候,遇到一个错误

   plt.text(0.5, 0, 'Loss = %.4f' % loss.data[0], fontdict={'size': 20, 'color': 'red'})
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

错误的解释:0维张量的索引无效。使用张量。Python中的item()`或`张量。在C++中,将0维张量转换为数字的项<T>(a)` 

解决办法:

        将data[0]  修改成item(),就可以正常运行了

        plt.text(0.5, 0, 'Loss = %.4f' % loss.item(), fontdict={'size': 20, 'color': 'red'})

导致的原因:

         loss.data[0] 是pytorch0.3.1版本代码,在0.4-0.5版本的pytorch会出现警告,不会报错,但是0.5版本以上的pytorch就会报错,总的来说是版本更新问题.

你可能感兴趣的:(PyTorch,python,深度学习,人工智能,pytorch,ide)