Tensor 和 NumPy 相互转换的实现

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Tensor 和 NumPy 相互转换的实现

xzw96   2023-03-20 我要评论

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

1. Tensor 转 NumPy

a = torch.ones(6)
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. 1. 1.]
tensor([2., 2., 2., 2., 2., 2.]) [2. 2. 2. 2. 2. 2.]
tensor([3., 3., 3., 3., 3., 3.]) [3. 3. 3. 3. 3. 3.]

2. NumPy 数组转 Tensor

import numpy as np
a = np.ones(7)
b = torch.from_numpy(a)
print(a, b)

a += 1
print(a, b)
b += 1
print(a, b)
[1. 1. 1. 1. 1. 1. 1.] tensor([1., 1., 1., 1., 1., 1., 1.], dtype=torch.float64)
[2. 2. 2. 2. 2. 2. 2.] tensor([2., 2., 2., 2., 2., 2., 2.], dtype=torch.float64)
[3. 3. 3. 3. 3. 3. 3.] tensor([3., 3., 3., 3., 3., 3., 3.], dtype=torch.float64)

3. torch.tensor() 将 NumPy 数组转换成 Tensor

直接用torch.tensor()将NumPy数组转换成Tensor,该方法总是会进行数据拷贝,返回的Tensor和原来的数据不再共享内存。

import numpy as np
a = np.ones((2,3))
c = torch.tensor(a)
a += 1
print('a:',a)
print('c:',c)
print(id(a)==id(c))
a: [[2. 2. 2.]
 [2. 2. 2.]]
c: tensor([[1., 1., 1.],
        [1., 1., 1.]], dtype=torch.float64)
False

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们