torch tensor 和 ndarray、list互相转化

Torch的Tensor与numpy的array会共享储存空间,修改一个也会导致另外一个被修改

一、torch tensor --> numpy array

用tensor对象的.numpy()方法

a = torch.ones(5)  # tensor([1., 1., 1., 1., 1.])
b = a.numpy()  # array([1., 1., 1., 1., 1.], dtype=float32)
 
a.add_(1)
 
print(a)  # tensor([2., 2., 2., 2., 2.])
print(b)  # array([2., 2., 2., 2., 2.], dtype=float32)

二、 numpy array --> torch tensor

用torch.from_numpy()函数

a = np.ones(5)  # array([1., 1., 1., 1., 1.])
b = torch.from_numpy(a)  # tensor([1., 1., 1., 1., 1.], dtype=torch.float64)
np.add(a,1,out=a)
 
print(a)  # array([2., 2., 2., 2., 2.])
print(b)  # tensor([2., 2., 2., 2., 2.], dtype=torch.float64)

三、list --> numpy array

不共享内存

ndarray = np.array(list)

四、numpy array --> list

不共享内存

list = ndarray.tolist()

 五、list --> torch tensor

不共享内存

tensor=torch.Tensor(list)

六、torch tensor --> list

先转numpy array,再转list

list = tensor.numpy().tolist()

参考:

Torch的Tensor与numpy的array数据相互转换_负壹的博客-CSDN博客_array tensor torch

机器学习笔记之list, numpy.array, torch.Tensor 格式相互转化 - 时光飞逝,逝者如斯 - 博客园 (cnblogs.com) 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值