假设我有一个3d numpy数组,其形状为(27,27,27)。我想通过同时对每个轴上的每3个元素进行平均来将其压缩为(9,9,9)(例如使3x3x3像素变为1x1x1)。目标是同时在所有三个轴上有效地压缩单个整数(假设任何阵列对于每个轴的形状都将具有该整数的倍数)。
我最初的尝试是使用np.apply_over_axes,尽管我担心它不会得到所有3个轴的立方平均值,而是依次平均每个轴。
def mean_over(arr, axis):
np.average(arr.reshape(-1, 3), axis=axis)
the_array_small = np.apply_over_axes(mean_over, the_array, \[0,1,2\])
但是,这将返回一个错误:
Traceback (most recent call last):
File "\<stdin\>", line 1, in \<module\>
File "\<\__array_function_\_ internals\>", line 180, in apply_over_axes
File "/opt/homebrew/Caskroom/mambaforge/base/envs/seaborn/lib/python3.10/site-packages/numpy/lib/shape_base.py", line 496, in apply_over_axes
if res.ndim == val.ndim:
AttributeError: 'NoneType' object has no attribute 'ndim'
我不相信我的apply_over_axes解决方案能够达到我的目标。理想情况下,返回每个(3,3,3)分量的平均值。
3条答案
按热度按时间jqjz2hbq1#
只是第一个答案(但同样,取决于你对我的评论的回答,依靠一些卷积可能会更好)
mbzjlibv2#
另一种解决方案,但要利用
as_strided
pcrecxhr3#
使用this answer中的
cubify
函数,您可以将数组拆分为立方体。有了这个结果,你可以使用apply_over_axes
来获得平均值,并根据你想要的结果进行整形。这里我使用一个9x9x9的立方体的例子,因为这样更容易看到结果。结果: