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

相关文章:

  • 2022-03-09
  • 2022-12-23
  • 2022-12-23
  • 2021-04-05
  • 2021-07-13
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-07-10
  • 2022-12-23
  • 2021-08-24
  • 2022-12-23
  • 2021-09-02
  • 2021-05-16
相关资源
相似解决方案