pytorch中tensor类型转换

转载自:https://www.jb51.net/article/177575.htm,做简要记录
1、tensor与numpy数组:

# tensor转numpy
tensor.numpy()
# numpy转tensor
torch.from_numpy()

2、tensor与list:

# tensor转list
tensor.tolist()
# list转tensor
torch.tensor()

3、tensor类型转换

tensor = torch.Tensor(3, 5) 
# torch.long() 将tensor投射为long类型
newtensor = tensor.long() 
# torch.half()将tensor投射为半精度浮点类型
newtensor = tensor.half() 
# torch.int()将该tensor投射为int类型
newtensor = tensor.int() 
# torch.double()将该tensor投射为double类型
newtensor = tensor.double() 
# torch.float()将该tensor投射为float类型
newtensor = tensor.float() 
# torch.char()将该tensor投射为char类型
newtensor = tensor.char() 
# torch.byte()将该tensor投射为byte类型
newtensor = tensor.byte() 
# torch.short()将该tensor投射为short类型
newtensor = tensor.short()

4、type_as() 将张量转换成指定类型张量,需要赋值,type_as不会改变调用它的tensor

>>> a=torch.Tensor(2,5)
>>> a
tensor([[1.9431e-19, 4.8613e+30, 1.4603e-19, 2.0704e-19, 4.7429e+30],    [1.6530e+19, 1.8254e+31, 1.4607e-19, 6.8801e+16, 1.8370e+25]])
>>> b=torch.IntTensor(1,2)
>>> a.type_as(b)
tensor([[     0, -2147483648,      0,      0, -2147483648],    [-2147483648, -2147483648,      0, -2147483648, -2147483648]],    dtype=torch.int32)
>>> a
tensor([[1.9431e-19, 4.8613e+30, 1.4603e-19, 2.0704e-19, 4.7429e+30],    [1.6530e+19, 1.8254e+31, 1.4607e-19, 6.8801e+16, 1.8370e+25]])
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值