Python 通过沿一个轴堆叠,将两个numpy视图合并为一个视图
我是否在概念上没有掌握某些东西(仅相似),或者为什么沿第一个Python 通过沿一个轴堆叠,将两个numpy视图合并为一个视图,python,numpy,view,Python,Numpy,View,我是否在概念上没有掌握某些东西(仅相似),或者为什么沿第一个轴=0堆叠多个视图不会产生新视图?问题在于:多个2d数组(其中的单行应组合成一个新矩阵)也是一个不增加内存使用的视图。例如: recs = np.arange(2*2).reshape(2,2) recs2 = np.arange(4,2*2*2).reshape(2,2) print(recs) print(recs2) rv0 = recs[0].view() r2v0 = recs2[0].view() #now combine
轴=0
堆叠多个视图不会产生新视图?问题在于:多个2d数组(其中的单行应组合成一个新矩阵)也是一个不增加内存使用的视图。例如:
recs = np.arange(2*2).reshape(2,2)
recs2 = np.arange(4,2*2*2).reshape(2,2)
print(recs)
print(recs2)
rv0 = recs[0].view()
r2v0 = recs2[0].view()
#now combine
mview = np.stack([rv0,r2v0], axis=0)
print(mview)
np.may_share_memory(mview,recs2)
印刷品
[[0 1]
[2 3]]
[[4 5]
[6 7]]
[[0 1]
[4 5]]
False #sure a copy
是因为2d数组是独立的内存区域,因此生成的数组不允许切片等操作吗 All
concatenate
(stack
只是另一种调用方式)使用自己的数据缓冲创建一个数组。它从来不是原始版本的视图
您的rv0
是一个数组(np.ndarray
),类似于recs
,具有自己的形状、数据类型和步幅。它只与rec
共享数据缓冲区。它可以描述为recs
的“视图”,但在其他方面,它与任何其他数组一样使用。它没有特别标记为视图
类或对象
In [409]: recs = np.arange(2*2).reshape(2,2)
...: recs2 = np.arange(4,2*2*2).reshape(2,2)
由于recs
是arange
生成的数组的重塑
,因此它也是一个“视图”。这一点可以通过以下方式更加明显:
temp = np.arange(2*2)
recs = temp.reshape(2,2)
np.may_share_memory(temp, recs)
可以说,我们可以用ravel()
(它只生成一个1d视图)来拍摄databuffer的快照:
现在看一下堆栈
:
In [414]: mview = np.stack([recs,recs2], axis=0)
In [415]: mview
Out[415]:
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
In [416]: mview.ravel()
Out[416]: array([0, 1, 2, 3, 4, 5, 6, 7])
mview的ravel
不是Out[411]
和Out[412]
的子集mview
必须有自己的连续数据缓冲区。没有任何机制可以使一个数组与2个或更多其他数组共享内存(除非它们也共享内存)
即使是由同一数组的切片构成的堆栈
,也有自己的数据缓冲区:
In [420]: x = np.stack((recs[0],recs[1]))
In [421]: x
Out[421]:
array([[0, 1],
[2, 3]])
In [422]: np.may_share_memory(recs, x)
Out[422]: False
我喜欢使用\uuuu数组\u接口\uuuu
检查数据缓冲区位置(其他定义属性):
[423]中的:记录\数组\接口__
Out[423]:
{'data':(37584304,假),
“跨步”:无,
'描述':[('','
In [420]: x = np.stack((recs[0],recs[1]))
In [421]: x
Out[421]:
array([[0, 1],
[2, 3]])
In [422]: np.may_share_memory(recs, x)
Out[422]: False
In [423]: recs.__array_interface__
Out[423]:
{'data': (37584304, False),
'strides': None,
'descr': [('', '<i8')],
'typestr': '<i8',
'shape': (2, 2),
'version': 3}
In [424]: x.__array_interface__
Out[424]:
{'data': (37614336, False),
'strides': None,
'descr': [('', '<i8')],
'typestr': '<i8',
'shape': (2, 2),
'version': 3}