- torch.Tensor.item()函数,其实就是把张量转换为python标准数字返回,仅适用只有一个元素的张量。
- pytorch官方文档写的很清楚。请看
Tensor.
item
() → number
Returns the value of this tensor as a standard Python number. This only works for tensors with one element. For other cases, see tolist().
意思是:将此张量的值作为标准Python数返回。这仅适用于具有一个元素的张量。对于其他情况,请参见tolist()。
不明白就上代码。
废话少说看代码。
import torch
a=torch.randn(1,dtype=torch.float32)
print(a,'\n',a.type())
#tensor([-1.9218])
#torch.FloatTensor
生成一个float类型的张量,注意只有一个元素。
import torch
a=torch.randn(1,dtype=torch.float32)
print(a,'\n',a.type())
#tensor([-1.9218])
#torch.FloatTensor
x=a.item()
print(x,'\n',type(x))
#-0.20335444808006287
# <class 'float'>
可以看到item()函数把tensor(张量)转换成了float类型
注意:item只能转换一个元素的张量,元素不是一个报错
import torch
a=torch.randn(2,dtype=torch.float32)
print(a,'\n',a.type())
#tensor([0.1798, 0.1281])
#torch.FloatTensor
x=a.item()
print(x,'\n',type(x))
#ValueError: only one element tensors can be converted to Python scalars
可以看到生成了含有两个元素的张量,但是调用item()时,直接报错。
注:当你的tensor类型不同时,生成的python标准数类型也不同。
import torch
a=torch.tensor([2])
print(a,'\n',a.type())
#tensor([2])
#torch.LongTensor
x=a.item()
print(x,'\n',type(x))
#2
#<class 'int'>
可以看到定义了一个longtensor的张量,生成的为int型。
如有不对,请各位大佬指出。