用法描述
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