我使用 NumPy 中的 amax
和 sliding_window_view
函数成功找到了每个滑动窗口 View 中数组的最大值,如下所示:
import numpy as np
a = np.random.randint(0, 100, (5, 6)) # 2D array
array([[51, 92, 14, 71, 60, 20],
[82, 86, 74, 74, 87, 66],
[23, 2, 21, 52, 1, 87],
[29, 37, 1, 63, 59, 20],
[32, 75, 57, 21, 83, 48]])
windows = np.lib.stride_tricks.sliding_window_view(a, (3, 3))
np.amax(windows, axis=(2, 3))
array([[92, 92, 87, 87],
[86, 86, 87, 87],
[75, 75, 83, 87]])
现在,我试图在考虑窗口的情况下找到原始数组中最大值的位置。
预期输出
The first element i.e. `92` should give position `(1, 0)`.
The second element i.e. `92` should give position `(1, 0)`.
The third element i.e. `87` should give position `(4, 1)`.
.
.
The seventh element i.e. `87` should give position `(4, 1)`.
The twelveth element i.e. `87` should give position `(5, 2)`.
.
so on
注意:每个值只需要一个位置。因此,如果窗口内有多个位置,则仅返回第一个。
最佳答案
此解决方案给出每个窗口的索引,但如果最大值在某个窗口中出现两次,则不会给出唯一索引:
maxvals = np.amax(windows, axis=(2, 3))
# array([[92, 92, 87, 87],
# [86, 86, 87, 87],
# [75, 75, 83, 87]])
indx = np.array((windows == np.expand_dims(maxvals, axis = (2, 3)).nonzero())
它为 windows
数组中的四个轴中的每一个返回一个数组。现在我们对每个窗口中的相对索引位置使用一些数学来获取原始数组中出现最大值的索引:
np.sum(indx.reshape(2, 2, -1), axis = 0)
# array([[0, 0, 1, 1, 2, 1, 1, 1, 1, 2, 4, 4, 4, 2],
# [1, 1, 4, 4, 5, 1, 1, 4, 4, 5, 1, 1, 4, 5]])
进行 reshape 是为了便于添加索引。前两个数组给出窗口位置。后两个数组是相对于窗口的位置。所以我们只需将它们相加即可。 您可以检查第二个轴上的每对值是否是您需要的索引对。
关于python - 如何获取数组滑动窗口 View 中最大元素的矩阵位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72741431/