对于只有一个元素的张量,使用 item() 函数将该值从张量中提取出来。
代码
python
import torch
import numpy as np
def test01():
tensor1 = torch.tensor(30)
tensor2 = torch.tensor([30])
tensor3 = torch.tensor([[30]])
print(tensor1.item())
print(tensor2.item())
print(tensor3.item())
# 注意:张量中只有一个元素,如果有多个元素的话,使用 item 函数可能会报错
# tensor4 = torch.tensor([30, 40])
# print(tensor4.item())
if __name__ == "__main__":
test01()