【发布时间】:2018-07-07 01:23:42
【问题描述】:
我正在尝试深入了解 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 的内存缓冲区。因此,改变一个将反映在另一个。所以,我在这里对张量t2中的一些值进行切片和更新@
In [98]: t2[:, 1] = 23.0
正如预期的那样,它在t2 和arr 中进行了更新,因为它们共享相同的内存缓冲区。
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() 构造的
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.Tensor() 可以完成这项工作时,为什么还存在一个专用函数 torch.from_numpy()?
我查看了 PyTorch 文档,但它没有提到任何关于此的内容?有什么想法/建议吗?
【问题讨论】:
-
非常有趣的问题。我不知道答案,但我怀疑
torch.Tensor()可能接受其他形式(例如,列表)的输入,但torch.from_numpy()仅在 numpy 数组上运行。
标签: python numpy multidimensional-array deep-learning pytorch