KerasでCNNの中間層の可視化(特徴マップ)や重みの可視化まとめ
kerasで中間層の出力を取得
kerasでCNNの中間層を取得する方法は2種類存在する.
ケース1
from keras.models import Model intermediante_layer_model = Model(inputs=model.input, outputs=model.get_layer("fc2").output) y = intermediante_layer_model.predict(X) print(y.shape)
ケース2
from keras import backend as K get_layer_output = K.function([model.layers[0].input],[model.layers[21].output]) y = get_layer_output([X,0])[0] print(y.shape)
中間層の重みを可視化
中間層の重みを可視化するためには上記の中間層の取得のときに使ったコードを利用する.
weights = resnet.get_layer("conv1").get_weights()[0]
from keras.applications import ResNet50 import matplotlib.pyplot as plt import numpy as np from PIL import Image <200b> resnet = ResNet50() resnet.summary() <200b> weights = resnet.get_layer("conv1").get_weights()[0] <200b> <200b> weights.shape print("shape",weights.shape) <200b> w = weights[:, :, ::-1, 0].copy() m = w.min() M = w.max() w = (w-m)/(M-m) plt.imshow(w) <200b> result = Image.new("RGB", (7*8+(8-1), 7*8+(8-1))) for i in range(64): w= weights[:, :, ::-1, i].copy() M = w.max() m = w.min() w = (w-m)/(M-m) w *= 255 img = Image.fromarray(w.astype("uint8"), mode="RGB") result.paste(img, (7*(i//8) + (i//8), 7*(i%8)+(i%8))) plt.imshow(result)