Python 官方文档:入门教程 => 点击学习
tensor与numpy的相互转换 1. numpy转tensor命令1:torch.tensor()命令2:torch.as_tensor()命令3:torch.from_numpy()区别
a = np.random.random(size=(4,5)) b = torch.tensor(a,dtype=torch.float)====输出========>> aarray([[0.93866392, 0.5665604 , 0.32893379, 0.77752777, 0.59380636], [0.09680724, 0.09611474, 0.69760508, 0.9120742 , 0.07956756], [0.46761691, 0.7771953 , 0.23979901, 0.52539619, 0.99063046], [0.05881101, 0.77289148, 0.22587614, 0.6438252 , 0.82986165]])>>btensor([[0.9387, 0.5666, 0.3289, 0.7775, 0.5938], [0.0968, 0.0961, 0.6976, 0.9121, 0.0796], [0.4676, 0.7772, 0.2398, 0.5254, 0.9906], [0.0588, 0.7729, 0.2259, 0.6438, 0.8299]])
注意:
>>> c =torch.as_tensor(a)>>> ctensor([[0.9387, 0.5666, 0.3289, 0.7775, 0.5938], [0.0968, 0.0961, 0.6976, 0.9121, 0.0796], [0.4676, 0.7772, 0.2398, 0.5254, 0.9906], [0.0588, 0.7729, 0.2259, 0.6438, 0.8299]], dtype=torch.float64)
>>> d = torch.from_numpy(a)>>> dtensor([[0.9387, 0.5666, 0.3289, 0.7775, 0.5938], [0.0968, 0.0961, 0.6976, 0.9121, 0.0796], [0.4676, 0.7772, 0.2398, 0.5254, 0.9906], [0.0588, 0.7729, 0.2259, 0.6438, 0.8299]], dtype=torch.float64)
torch.from_numpy(np.array)
和torch.as_tensor()
,均会指向相同的内存地址。n = np.ones(5)t = torch.as_tensor(n)t1 = torch.from_numpy(n)t2 = torch.tensor(n)print('numpy n = ', n)print('torch t =', t)print('torch t1 =', t1)print('torch t2 =', t2)n += 1print("\nafter add 1, numpy = ", n)print('torch t = ', t)print('torch t1 = ', t1)print('torch t2 = ', t2)# 输出。numpy n = [1. 1. 1. 1. 1.]torch t = tensor([1., 1., 1., 1., 1.], dtype=torch.float64)torch t1 = tensor([1., 1., 1., 1., 1.], dtype=torch.float64)# numpy +1之后,三种方式转换出来的tensor的变化after add 1, numpy = [2. 2. 2. 2. 2.]torch t = tensor([2., 2., 2., 2., 2.], dtype=torch.float64)torch t1 = tensor([2., 2., 2., 2., 2.], dtype=torch.float64)torch t2 = tensor([1., 1., 1., 1., 1.], dtype=torch.float64)
t = torch.ones(5)n1 = t.numpy()n2 = np.array(t)print('numpy n1 = ', n1)print('numpy n2 = ', n2)print('torch t =', t)t += 1print("\nafter +1 ")print("numpy n1= ", n1)print("numpy n2 = ", n2)print('torch = ', t)# 输出结果numpy n1 = [1. 1. 1. 1. 1.]numpy n2 = [1. 1. 1. 1. 1.]torch t = tensor([1., 1., 1., 1., 1.])after +1 numpy n1= [2. 2. 2. 2. 2.]numpy n2 = [1. 1. 1. 1. 1.] # 没有改变torch = tensor([2., 2., 2., 2., 2.])
GPU上的tensor不能和numpy直接转换。必须先转换为CPU上的tensor。
# 如果一个tensor的device是GPU,先使用如下命令转为CPUtensor.cpu() # 再使用tensor.numpy()进行转化tensor.data.numpy()# tensor到GPUtensor.GPU()
来源地址:https://blog.csdn.net/weixin_44769214/article/details/126273031
--结束END--
本文标题: tensor与numpy的相互转换
本文链接: https://www.lsjlt.com/news/395100.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0