私はサイズs
の正方形のサブリージョンで分割する必要がある2D Numpy ndarray、x
を持っています。各小地域について、私は最大の要素(私が行う)とその小領域内での位置(私は把握できません)を得たいと思います。ここNumpy 2D配列の各サブマトリックスの最大の要素のインデックスを取得します
が最小の例である:たとえば
>>> x = np.random.randint(0, 10, (6,8))
>>> x
array([[9, 4, 8, 9, 5, 7, 3, 3],
[3, 1, 8, 0, 7, 7, 5, 1],
[7, 7, 3, 6, 0, 2, 1, 0],
[7, 3, 9, 8, 1, 6, 7, 7],
[1, 6, 0, 7, 5, 1, 2, 0],
[8, 7, 9, 5, 8, 3, 6, 0]])
>>> h, w = x.shape
>>> s = 2
>>> f = x.reshape(h//s, s, w//s, s)
>>> mx = np.max(f, axis=(1, 3))
>>> mx
array([[9, 9, 7, 5],
[7, 9, 6, 7],
[8, 9, 8, 6]])
、mx
の左下隅に8
はx
の左下隅にある部分領域[[1,6], [8, 7]]
から最大の要素です。私が欲しいもの
は、このような指標最大の要素のを保持mx
に似た配列を、得ることです:
[[0, 1, 1, 2],
[0, 2, 3, 2],
[2, 2, 2, 2]]
、例えば、左下隅の2
があります線形表現[[1, 6], [8, 7]]
の8
のインデックス。
np.argmax(f[i, :, j, :])
を繰り返し、i
とj
を繰り返しますが、大量の計算では速度差が大きいです。あなたにアイデアを与えるために、私はmax poolingのためだけにNumpyを使用しようとしています。基本的には、私が使っているものよりも速い選択肢があるかどうか尋ねています。
# Get shape of output array
m,n = np.array(x.shape)//s
# Reshape and permute axes to bring the block as rows
x1 = x.reshape(h//s, s, w//s, s).swapaxes(1,2).reshape(-1,s**2)
# Use argmax along each row and reshape to output shape
out = x1.argmax(1).reshape(m,n)
サンプル入力、出力 - -