가중치 시각화
CNN은 여러 개의 필터를 사용해 이미지에서 특징을 학습한다.
각 필터는 커널이라 부르는 가중치와 절편을 가지고 있다.
가중치의 경우 입력 이미지를 2차원으로 적용하면 어떤 특징을 크게 두드러지게하는데, 그림으로 보면
색이 있는 공간은 값이 높고, 아니면 낮을 것이다.
이전에 학습했던 데이터를 불러오자 checkpoint 파일 불러오기
from tensorflow import keras
model = keras.models.load_model('best-cnn-model.h5')
model.layers
[<keras.layers.convolutional.conv2d.Conv2D at 0x24c86ab22b0>,
<keras.layers.pooling.max_pooling2d.MaxPooling2D at 0x24c86a9c220>,
<keras.layers.convolutional.conv2d.Conv2D at 0x24cfacd7580>,
<keras.layers.pooling.max_pooling2d.MaxPooling2D at 0x24cfacd4be0>,
<keras.layers.reshaping.flatten.Flatten at 0x24cfabec670>,
<keras.layers.core.dense.Dense at 0x24cfabe01c0>,
<keras.layers.regularization.dropout.Dropout at 0x24cfb2fe400>,
<keras.layers.core.dense.Dense at 0x24cfabfe760>]
conv = 모델의 첫 번째 층 : 첫 번째 CNN ( 필터 32개, 커널 사이즈 3x3 )
conv의 가중치의 첫 번째 원소와 두번 째 원소의 크기를 출력해보자.
첫 번째 원소 = 가중치
두 번째 원소 = 절편
conv = model.layers[0]
print(conv.weights[0].shape, conv.weights[1].shape)
(3, 3, 1, 32) (32,)
커널의 크기 3x3이므로 3,3,1이 커널의 크기로 출력되었고, 필터 개수 32개 임을 확인할 수 있다.
절편은 (32,) ==> 필터마다 1개의 절편 존재하므로 32개의 상수가 있음을 확인할 수 있다.
conv_weights = conv.weights[0].numpy()
print(conv_weights.mean(), conv_weights.std())
-0.025013467 0.2464292
가중치 배열의 평균 / 표준편차를 계산
0에 가깝고 표준편차는 0.27이다.
import matplotlib.pyplot as plt
plt.hist(conv_weights.reshape(-1,1))
plt.xlabel('weight')
plt.ylabel('count')
plt.show()
균일해보이지 않다!!!
이제 훈련 전의 데이터의 가중치를 살펴보자.
not_training = keras.Sequential()
not_training.add(keras.layers.Conv2D(32,kernel_size=3, activation = 'relu',
padding='same', input_shape=(28,28,1)))
not_training_conv = not_training.layers[0]
print(not_training_conv.weights[0].shape)
(3, 3, 1, 32)
평균 / 표준편차를 출력해보자.
not_training_weights = not_training_conv.weights[0].numpy()
print(not_training_weights.mean(),not_training_weights.std())
-0.003274826 0.08374746
아까처럼 가중치의 배열을 그림으로 표현해보자.
plt.hist(not_training_weights.reshape(-1,1))
plt.xlabel('weight')
plt.ylabel('count')
plt.show()
'머신러닝 & 딥러닝 기초 > 8장 - CNN 기초' 카테고리의 다른 글
08-2 합성곱 신경망을 사용한 이미지 분류 (0) | 2023.03.13 |
---|---|
08-1 합성곱 신경망의 구성요소 ( 채널, 패딩, 폴링 ) (0) | 2023.03.12 |