python基本类型、list、numpy、Tensor类型之间的相互转换

list转numpy

b = [random.random() for i in range(4)]
print('b的类型',type(b))
a = numpy.array(b)
print('a的类型',type(a))

输出

b的类型 <class 'list'>
a的类型 <class 'numpy.ndarray'>

numpy转list

a = numpy.random.rand(2,2)
print('a的类型',type(a))
b = a.tolist()
print('b的类型',type(b))

输出

a的类型 <class 'numpy.ndarray'>
b的类型 <class 'list'>

numpy转Tensor

a = numpy.random.rand(2,2)
print('a的类型',type(a))
c = torch.Tensor(a)
print('c的类型',type(c))
e = torch.from_numpy(a)
print('e的类型',type(e))

输出

a的类型 <class 'numpy.ndarray'>
c的类型 <class 'torch.Tensor'>
e的类型 <class 'torch.Tensor'>

Tensor转numpy

c = torch.rand(2,2)
print('c的类型',type(c))
a = c.numpy()
print('a的类型',type(a))

输出

c的类型 <class 'torch.Tensor'>
a的类型 <class 'numpy.ndarray'>

list转Tensor

b = [random.random() for i in range(4)]
print('b的类型',type(b))
c = torch.tensor(b)
print('c的类型',type(c))

输出

b的类型 <class 'list'>
c的类型 <class 'torch.Tensor'>

Tensor转list

c = torch.rand(2,2)
print('c的类型',type(c))
b = c.numpy().tolist()
print('b的类型',type(b))

#gpu上的tensor不能直接转为numpy
if torch.cuda.is_available():
    print("GPU train avaliable")
    device = torch.device("cuda")
else:
    print("CPU train avaliable")
    device = torch.device("cpu")
e = c.to(device)
d = c.cpu().detach().numpy().tolist()
print('d的类型',type(d))

输出

c的类型 <class 'torch.Tensor'>
b的类型 <class 'list'>
GPU train avaliable
d的类型 <class 'list'>

Tensor转基本类型

c = torch.rand(2,2)
print('c的类型',type(c))
a = c.item()
print('a的类型',type(a))

输出

c的类型 <class 'torch.Tensor'>
a的类型 <class 'float'>

基本类型转Tensor

a = 1
print('a的类型',type(a))
c = torch.tensor(a)
print('c的类型',type(c))

输出

a的类型 <class 'int'>
c的类型 <class 'torch.Tensor'>

Tensor转Tensor

tensor = torch.randn(2, 2)
print(tensor, tensor.dtype)
tensor = tensor.to(dtype=torch.long)
print(tensor, tensor.dtype)

输出

tensor([[ 2.4507, -0.1803],
        [ 0.3871, -0.7686]]) torch.float32
tensor([[2, 0],
        [0, 0]]) torch.int64

类型关系

在这里插入图片描述

补充

Pytorch中Tensor的类型转换

  • 7
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值