E資格例題⑦ im2col プラスα
問題①
正解①
(c):公式みたいなもの
問題②
正解②
(a)
def im2col(img, k_h, k_w, s_h, s_w, p_h, p_w):
# ミニバッチサイズ, チャンネル数, 縦幅, 横幅
n, c, h, w = img.shape
# paddingを行う、(あ)の要素は上記n, c, h, wに対応、nとcにはパディングしない
# 'constant'は標準モード
img = np.pad(img, [(0,0), (0,0), (p_h, p_h), (p_w, p_w)], 'constant')
# 出力サイズを計算
# フィルターもカーネルも同じ意味
# //:整数除算(切り捨て除算)
out_h = (h + 2 * p_h - k_h) // s_h + 1
out_w = (w + 2 * p_w - k_w) // s_w + 1
問題③
正解③
(a)
col = np.ndarray((n, c, k_h, k_w, out_h, out_w), dtype=img.dtype)
# フィルタに対応する画素をスライス
# フィルタの各要素(k_h、k_wの二次元データ)に適用させる画像データを、
# ストライドずつづらしながら取得(out_h、out_wの二次元データ)、colに格納
# (y, x)は(k_h, k_w)のフィルタの各要素。
for y in range(k_h):
y_lim = y + s_h * out_h
for x in range(k_w):
x_lim = x + s_w * out_w
col[:, :, y, x, :, :] = img[:, :, y:y_lim:s_h, x:x_lim:s_w]
問題④
正解④
(b)
# 畳み込み領域をシーケンス化
img_col, out_h, out_w = im2col(img, k_h, k_w, s_h, s_w, p_h, p_w)
# フィルタの各要素をシーケンス化
kernel_col = kernel.reshape(k_n, -1).T
# 変換後画像データと変換後フィルタの畳み込み(行列積)により特徴マップを抽出
conv = np.dot(img_col, kernel_col)
# (ミニバッチサイズn, チャネル数c, 縦幅h、横幅w)の形に戻してreturn
# img.shape[0]:n
return conv.reshape(img.shape[0], out_h, out_w, -1).transpose(0, 3, 2, 1)
この記事が気に入ったらサポートをしてみませんか?