窓行列を取り出す
Published:
By nobCategory: Posts
Tags: 機械学習 ニューラルネットワーク CNN numpy Python
窓行列を取り出したい
6x6の行列がある。
import numpy as np
data = np.arange(6 * 6).reshape(6, 6)
print(data)
[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]
[12 13 14 15 16 17]
[18 19 20 21 22 23]
[24 25 26 27 28 29]
[30 31 32 33 34 35]]
この行列から、3x3の窓行列を取り出したい。
numpy.lib.stride_tricks.sliding_window_view
from numpy.lib.stride_tricks import sliding_window_view
windows = sliding_window_view(data, (3, 3))
a = windows.reshape(-1, 3 * 3)
print(a)
[[ 0 1 2 6 7 8 12 13 14]
[ 1 2 3 7 8 9 13 14 15]
[ 2 3 4 8 9 10 14 15 16]
[ 3 4 5 9 10 11 15 16 17]
[ 6 7 8 12 13 14 18 19 20]
[ 7 8 9 13 14 15 19 20 21]
[ 8 9 10 14 15 16 20 21 22]
[ 9 10 11 15 16 17 21 22 23]
[12 13 14 18 19 20 24 25 26]
[13 14 15 19 20 21 25 26 27]
[14 15 16 20 21 22 26 27 28]
[15 16 17 21 22 23 27 28 29]
[18 19 20 24 25 26 30 31 32]
[19 20 21 25 26 27 31 32 33]
[20 21 22 26 27 28 32 33 34]
[21 22 23 27 28 29 33 34 35]]
numpy
x = (
np.arange(3).reshape(1, -1) + np.arange(0, 6 * 3, 6).reshape(-1, 1)
).reshape(1, -1)
print(x.shape)
print(x)
(1, 9)
[[ 0 1 2 6 7 8 12 13 14]]
y = (
np.arange(6 - 3 + 1).reshape(1, -1)
+ np.arange(0, 6 * (6 - 3 + 1), 6).reshape(-1, 1)
).reshape(-1, 1)
print(y.shape)
print(y)
(16, 1)
[[ 0]
[ 1]
[ 2]
[ 3]
[ 6]
[ 7]
[ 8]
[ 9]
[12]
[13]
[14]
[15]
[18]
[19]
[20]
[21]]
index = x + y
b = data.reshape(-1)[index]
print(b)
[[ 0 1 2 6 7 8 12 13 14]
[ 1 2 3 7 8 9 13 14 15]
[ 2 3 4 8 9 10 14 15 16]
[ 3 4 5 9 10 11 15 16 17]
[ 6 7 8 12 13 14 18 19 20]
[ 7 8 9 13 14 15 19 20 21]
[ 8 9 10 14 15 16 20 21 22]
[ 9 10 11 15 16 17 21 22 23]
[12 13 14 18 19 20 24 25 26]
[13 14 15 19 20 21 25 26 27]
[14 15 16 20 21 22 26 27 28]
[15 16 17 21 22 23 27 28 29]
[18 19 20 24 25 26 30 31 32]
[19 20 21 25 26 27 31 32 33]
[20 21 22 26 27 28 32 33 34]
[21 22 23 27 28 29 33 34 35]]
np.array_equal(a, b)
True