gpt4 book ai didi

python - Numpy reshape - 是否复制数据?

转载 作者:行者123 更新时间:2023-12-04 14:02:56 25 4
gpt4 key购买 nike

我正在阅读有关 numpy 的 reshape 方法的信息。这是引述:

Note that for this (i.e. reshaping) to work, the size of the initial array must matchthe size of the reshaped array. Where possible, the reshape methodwill use a no-copy view of the initial array, but with noncontiguousmemory buffers this is not always the case.

我做了一些简单的测试,似乎reshape确实不创建副本,内存是共享的。

那么这里的那部分是什么意思“但对于不连续的内存缓冲区,情况并非总是如此”? reshape 确实创建数据副本的示例是什么?真正的规则是什么,即什么时候创建副本,什么时候不创建副本?

最佳答案

viewcopy 的示例

这是为 reshape 操作创建的副本的示例。我们可以使用 np.share_memory 检查两个数组是否共享内存。如果 True 那么其中一个是另一个的 View ,如果 False 那么其中一个是另一个的副本并存储在单独的内存中。意思是,对一个的任何操作都不会反射(reflect)到另一个。

a = np.array([[1,2,3,4],[5,6,7,8]])
b = a.T

arr1 = a.reshape((-1,1))
print('Reshape of original is a view:', np.shares_memory(a, arr1))

print('Transpose sharing memory:', np.shares_memory(a,b))

arr2 = b.reshape((-1,1))
print('Reshape of transpose is a view:', np.shares_memory(b, arr2))
Reshape of original is a view: True    #<- a, a.reshape share memory
Transpose sharing memory: True #<- a, a.T share memory
Reshape of transpose is a view: False #<- a.T, a.T.reshape DONT share memory

说明:

numpy是如何存储数组的?

Numpy 将其 ndarray 存储为连续的内存块。每个元素在前一个元素之后每隔 n 个字节按顺序存储。

(引用自 excellent SO post 的图片)

所以如果你的 3D 数组看起来像这样 -

np.arange(0,16).reshape(2,2,4)

#array([[[ 0, 1, 2, 3],
# [ 4, 5, 6, 7]],
#
# [[ 8, 9, 10, 11],
# [12, 13, 14, 15]]])

enter image description here

然后在内存中将其存储为 -

enter image description here

当检索一个元素(或一个元素 block )时,NumPy 计算需要遍历多少个步幅(每个步幅为 8 个字节)以获取该方向/轴上的下一个元素 。因此,对于上面的示例,对于 axis=2 它必须遍历 8 个字节(取决于 datatype)但是对于 axis=1 它要遍历8*4字节,axis=0需要8*8字节

Almost all numpy operations depend on this nature of storage of the arrays. So, to work with an array that can comprise of non-contiguous blocks of memory, numpy is sometimes forced to create copies instead of views.

为什么 reshape 有时会创建副本?

回到我上面用数组 aa.T 显示的示例,让我们看一下第一个示例。我们有一个数组 a,它存储为一个连续的内存块,如下所示 -

enter image description here

由于数组需要以连续的方式存储,以便可以正确应用其他 numpy 操作,因此被迫创建 numpy 数组的副本,因为很难跟踪与原始数组关联的内存后续操作的元素。这就是为什么 a.T 在这种情况下将 reshape 输出作为副本。

希望这可以解释您的查询。我不太擅长表达,所以请让我知道哪部分让您感到困惑,我可以编辑我的答案以获得更清晰的解释。

关于python - Numpy reshape - 是否复制数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69447431/

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