开发者

Tensor和NumPy相互转换的方法

目录
  • Tensor转NumPy
  • NumPy数组转 Tensor

我们很容易用 numpy(php) 和 from_numpy() 将 Tensor 和NumPy中的数组相互转换。

但是需要注意的点是: 这两个函数所产⽣生的的 Tensor 和NumPy中的数组共享相同的内存(所以他们之间的转换很快),改变其中⼀个时另⼀个也会改变!!!

还有一个常用的将NumPy中的array转换成 Tensor 的方法就是 torch.tensor() , 需要注意的

是,此方法总是会进行数据拷贝(就会消耗更多的时间和空间),所以返回的 Tensor 和原来的数据不再共享内存。

Tensor转NumPy

使用numpy()将 Tensor 转换成NumPy数组:

a = torch.ones(5)
b = a.numpy()
print(a, b)
a += 1
print(a, b)
b += 1
print(a, b)

输出为:

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

tensor([2., 2., 2., 2., 2.]) [2. 2. 2. 2. 2.]

tensor([3., 3., 3., 3., 3.]) [3. 3. 3. 3. 3.]

Num开发者_Js入门Py数组转javascript Tensor

通过使用 from_numpy() 将NumPy数组转换成 Tensor :

import numpy as np
a = np.ones(5)
b = torch.from_numpyjavascript(a)
print(a, b)
a += 1
print(a, b)
b += 1
print(a, b)

[1. php1. 1. 1. 1.] tensor([1., 1., 1., 1., 1.], dtype=torch.float64)

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

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

所有在CPU上的 Tensor (除了 CharTensor )都支持与NumPy数组相互转换。

此外上面我们提到还有一个常用的方法就是直接用 torch.tensor() 将NumPy数组转换成 Tensor ,需要

注意的是该方法总是会进行数据拷贝,返回的 Tensor 和原来的数据不再共享内存。

c = torch.tensor(a)
a += javascript1
print(a, c)

输出为:

[4. 4. 4. 4. 4.] tensor([3., 3., 3., 3., 3.], dtype=torch.float64)

到此这篇关于Tensor和NumPy相互转换的方法的文章就介绍到这了,更多相关Tensor和NumPy相互转换内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜