pytorch 数据类型 和 numpy 数据 相互转化

tensor to numpy

tensor数据在cpu上
如果tensor数据在cpu上,直接使用.numpy()就可以转化。

例子:

注意:torch 和 numpy 转化后 指向地址相同
如果修改原始数据,那么转换后的数据也会修改,例子:

tensor数据在gpu上
如果tensor数据在gpu上,那么需要将tensor数据先转移到cpu上面,然后在进行转化。

例子

a = torch.randn(2,3,4)
a = a.cuda()
print('type of a ', type(a))
print('device of a', a.device)

b = a.numpy() # 会出错

报错信息:TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

应该将a的数据先转化到 cpu 上面,在进行转化,例子:

a = torch.randn(2,3,4)
a = a.cuda()
print('type of a ', type(a))
print('device of a', a.device)

b = a.cpu().numpy()
print('type of b', type(b))

numpy to tensor

使用torch中的from_numpy() 函数将numpy数据 转换 为 torch上数据,例子:

# numpy to tensor

data_np = np.array([1,2,3,4,5])

print('orgin data_np', data_np)
data_tr = torch.from_numpy(data_np)

print('orgin data_tr',data_tr)

data_np[3] = 11

print('modify data_np', data_np)
print('modify data_tr', data_tr)

numpy数据和torch数据指向同一个地址,修改numpy数据会改变torch上数据,结果如下:

orgin data_np [1 2 3 4 5]
orgin data_tr tensor([1, 2, 3, 4, 5])
modify data_np [ 1 2 3 11 5]
modify data_tr tensor([ 1, 2, 3, 11, 5])

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值