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
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:【pytorch】.item()的用法 - Python技术站