pytorch中Tensor的数据类型

1. 32位浮点型:torch.FloatTensor

a=torch.Tensor( [[2,3],[4,8],[7,9]], )
print "a:",a
print "a.size():",a.size()
print "a.dtype:",a.dtype

b=torch.FloatTensor( [[2,3],[4,8],[7,9]] )
print "b:",b
print "b.shape:",b.shape
print "b.dtype:",b.dtype

 

可以看出 torch.FloatTensor 是32位float类型,并且torch.Tensor默认的数据类型是32位float类型。

2. 64位浮点型:torch.DoubleTensor

b=torch.DoubleTensor( [[2,3],[4,8],[7,9]] )
print "b:",b
print "b.shape:",b.shape
print "b.dtype:",b.dtype

 

 3. 16位整型:torch.ShortTensor

b=torch.ShortTensor( [[2,3],[4,8],[7,9]] )
print "b:",b
print "b.shape:",b.shape
print "b.dtype:",b.dtype

4.  32位整型:torch.IntTensor

b=torch.IntTensor( [[2,3],[4,8],[7,9]] )
print "b:",b
print "b.shape:",b.shape
print "b.dtype:",b.dtype

5. 64位整型:torch.LongTensor

b=torch.LongTensor( [[2,3],[4,8],[7,9]] )
print "b:",b
print "b.shape:",b.shape
print "b.dtype:",b.dtype

6. 快速创建Tensor

(1) torch.zeros()

a=torch.zeros( size=(4,5),dtype=torch.float32 )
print a
print a.shape
print a.dtype

(2) torch.randn()

a=torch.randn( size=(4,5),dtype=torch.float32 )
print a
print a.shape
print a.dtype

7. Tensor索引方式,参考numpy

8. Tensor和numpy数组转换:

(1) Tensor转numpy,

a=torch.randn( size=(4,5),dtype=torch.float32 )
print a
print a.shape
print a.dtype

b= a.numpy()
print b
print b.shape
print b.dtype

(2) numpy转Tensor,

a=np.random.randn(4,3)
print a
print a.shape
print a.dtype

b=torch.from_numpy( a )
print b
print b.shape
print b.dtype

9.更改Tensor的数据类型,

a=torch.FloatTensor( (3,2) )
print a
print a.shape
print a.dtype

a.int()
print a
print a.shape
print a.dtype

10. GPU加速,如果pytorch支持GPU加速,可以加Tensor放到GPU执行,

if torch.cuda.is_available():
    a_cuda = a.cuda()

 

  • 12
    点赞
  • 62
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值