pytorch tensor与numpy转换

戏子无情 提交于 2019-11-27 15:39:44

从官网拷贝过来的,就是做个学习记录。版本 0.4


 

tensor to numpy

a = torch.ones(5)
print(a)

输出

tensor([1., 1., 1., 1., 1.])

进行转换

b = a.numpy()
print(b)

输出

[1. 1. 1. 1. 1.]

注意,转换后的tensor与numpy指向同一地址,所以,对一方的值改变另一方也随之改变

a.add_(1)
print(a)
print(b)

numpy to tensor

import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)

输出

[2. 2. 2. 2. 2.]
tensor([2., 2., 2., 2., 2.], dtype=torch.float64)

除chartensor外所有tensor都可以转换为numpy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!