gpt4 book ai didi

python - PyTorch 内存模型 : "torch.from_numpy()" vs "torch.Tensor()"

转载 作者:IT老高 更新时间:2023-10-28 20:34:58 30 4
gpt4 key购买 nike

我正在尝试深入了解 PyTorch 张量内存模型的工作原理。

# input numpy array
In [91]: arr = np.arange(10, dtype=float32).reshape(5, 2)

# input tensors in two different ways
In [92]: t1, t2 = torch.Tensor(arr), torch.from_numpy(arr)

# their types
In [93]: type(arr), type(t1), type(t2)
Out[93]: (numpy.ndarray, torch.FloatTensor, torch.FloatTensor)

# ndarray
In [94]: arr
Out[94]:
array([[ 0., 1.],
[ 2., 3.],
[ 4., 5.],
[ 6., 7.],
[ 8., 9.]], dtype=float32)

我知道 PyTorch 张量共享 NumPy ndarray 的内存缓冲区。因此,改变一个将反射(reflect)在另一个。所以,我在这里切片和更新张量中的一些值 t2

In [98]: t2[:, 1] = 23.0

正如预期的那样,它在 t2arr 中更新,因为它们共享相同的内存缓冲区。

In [99]: t2
Out[99]:

0 23
2 23
4 23
6 23
8 23
[torch.FloatTensor of size 5x2]


In [101]: arr
Out[101]:
array([[ 0., 23.],
[ 2., 23.],
[ 4., 23.],
[ 6., 23.],
[ 8., 23.]], dtype=float32)

但是,t1 也更新了。请记住,t1 是使用 torch.Tensor() 构造的,而 t2 是使用 torch.from_numpy()< 构造的/p>

In [100]: t1
Out[100]:

0 23
2 23
4 23
6 23
8 23
[torch.FloatTensor of size 5x2]

所以,无论我们是否使用 torch.from_numpy()torch.Tensor()要从 ndarray 构造张量,所有这样的张量和 ndarray 共享相同的内存缓冲区。

基于这样的理解,我的问题是为什么一个专用函数torch.from_numpy()仅在 torch.Tensor() 时存在能胜任吗?

我查看了 PyTorch 文档,但它没有提到任何关于此的内容?有什么想法/建议吗?

最佳答案

from_numpy() 自动继承输入数组dtype。另一方面,torch.Tensortorch.FloatTensor 的别名。

因此,如果将 int64 数组传递给 torch.Tensor,则输出张量为浮点张量,它们不会共享存储。 torch.from_numpy 按预期为您提供 torch.LongTensor

a = np.arange(10)
ft = torch.Tensor(a) # same as torch.FloatTensor
it = torch.from_numpy(a)

a.dtype # == dtype('int64')
ft.dtype # == torch.float32
it.dtype # == torch.int64

关于python - PyTorch 内存模型 : "torch.from_numpy()" vs "torch.Tensor()",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48482787/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com