关于torch.Tensor.item()函数

  1. torch.Tensor.item()函数,其实就是把张量转换为python标准数字返回,仅适用只有一个元素的张量。
  2. 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型。

如有不对,请各位大佬指出。

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值