Use torch.Tensor.item() to get a Python number from a tensor containing a single value.

.item()方法返回张量元素的值。

用法示例

>>> import torch
>>> x = torch.tensor([[1]])
>>> x
tensor([[1]])
>>> x.item()
1
>>> x = torch.tensor(2.5)
>>> x
tensor(2.5000)
>>> x.item()
2.5

注意事项

张量中只有一个元素才能调用该方法,多个元素会报错:

>>> import torch
>>> x = torch.tensor([1, 2]) 
>>> x
tensor([1, 2])
>>> x.item()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: only one element tensors can be converted to Python scalars

引用参考

https://pytorch.org/docs/stable/tensors.html