我正在嘗試在堆疊 np 陣列中創建一個多維視窗并找到每個視窗的最大值。下面res是一個形狀為 (3, 4, 4) 的堆疊陣列。我想通過軸有一個 2x2 大小的視窗。例如,第一個視窗將是 (3,2,2),其值為:
ideal_result = np.array([[13, 45], [1, 2], [11, 22], [1, 2], [1, 2], [1, 7]])
那么最大視窗將是:np.max(ideal_result) = 45
這將是整個視窗并構造一個 2x2np.array([[45 67],[23 44]])
設定:
a = np.array([[13, 45, 67, 4], [1, 2, 3, 4], [2, 3, 4, 6], [1, 23, 44, 1]])
b = np.array([[11, 22, 33, 57], [1, 2, 3, 4], [2, 3, 94, 6], [1, 23, 44, 1]])
c = np.array([[1, 2, 3, 4], [1, 7, 8, 9], [2, 3, 4, 76], [1, 23, 44, 1]])
res = np.stack((a, b, c))
print(np.shape(res))
嘗試的代碼:
import numpy as np
v = np.lib.stride_tricks.as_strided(res, shape=(3, 2, 2), strides=(3, 2, 2))
uj5u.com熱心網友回復:
考慮扁平化陣列的外觀如何使步幅正確通常會有所幫助:
res.flatten()
輸出:
array([13, 45, 67, 4, 1, 2, 3, 4, 2, 3, 4, 6, 1, 23, 44, 1, 11,
22, 33, 57, 1, 2, 3, 4, 2, 3, 94, 6, 1, 23, 44, 1, 1, 2,
3, 4, 1, 7, 8, 9, 2, 3, 4, 76, 1, 23, 44, 1])
dtype 是int648 個位元組,因此每個連續元素之間的步幅是 8。我將用步幅標記哪些元素應該在第一個視窗中:
0 1 4 5 16
array([13, 45, 67, 4, 1, 2, 3, 4, 2, 3, 4, 6, 1, 23, 44, 1, 11,
17 20 21 32 33
22, 33, 57, 1, 2, 3, 4, 2, 3, 94, 6, 1, 23, 44, 1, 1, 2,
36 37
3, 4, 1, 7, 8, 9, 2, 3, 4, 76, 1, 23, 44, 1])
你能看到圖案嗎?
對于每個維度,我們有以下值和步幅:
x| values: 13->45, 11->22, 1->2, ... stride: 1
y| values: 13->1, 45->2, 11->2, ... stride: 4
z| values: 13->11, 45->22, 11->1, ... stride: 16
np.lib.stride_tricks.as_strided(res, shape=(3, 2, 2), strides=(8 * 16, 8 * 4, 8 * 1))
輸出:
array([[[13, 45],
[ 1, 2]],
[[11, 22],
[ 1, 2]],
[[ 1, 2],
[ 1, 7]]])
這只是一個視窗,我們想要其中的 4 個,每個視窗之間的跳轉在 x 方向為 8*2 位元組,在 y 方向為 8*8 位元組。
windows = np.lib.stride_tricks.as_strided(res, shape=(2, 2, 3, 2, 2), strides=(8 * 8, 8 * 2, 8 * 16, 8 * 4, 8 * 1))
windows.max(axis=(2, 3, 4))
輸出:
array([[45, 67],
[23, 94]])
假設步幅與內核大小相同(如在傳統的 2D 最大池中)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/439825.html
下一篇:使用Python定義時間回圈
