RNN은 순차적 데이터의 표현을 학습하기 적합한 신경망, RNN을 기반으로 한 모델은 각 MNIST 이미지를 시간 단계가 28인 28개 요소를 가진 입력 벡터의 시퀀스로 처리할 수 있다.
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Activation, SimpleRNN
from keras.utils import to_categorical, plot_model
from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 레이블 개수 계산
num_labels = len(np.unique(y_train))
num_labels
# 원-핫 벡터로 변환
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
# 이미지 차원
image_size = x_train.shape[1]
image_size
# 크기 조정, 정규화
x_train = np.reshape(x_train, [-1, image_size, image_size])
x_train = x_train.astype('float32') / 255.0
x_test = np.reshape(x_test, [-1, image_size, image_size])
x_test = x_test.astype('float32') / 255.0
# 모델 파라미터
input_shape = (image_size, image_size)
batch_size = 128
units = 256
dropout = 0.2
model = Sequential()
model.add(SimpleRNN(units=units, dropout = dropout, input_shape=input_shape))
model.add(Dense(num_labels))
model.add(Activation('softmax'))
model.summary()
>>>
Model: "sequential_2"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
simple_rnn_2 (SimpleRNN) (None, 256) 72960
dense_2 (Dense) (None, 10) 2570
activation_2 (Activation) (None, 10) 0
=================================================================
Total params: 75,530
Trainable params: 75,530
Non-trainable params: 0
_________________________________________________________________
# SGD 최적화 사용
model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
model.fit(x_train, y_train, epochs=20, batch_size=batch_size)
>>>
Epoch 1/20
469/469 [==============================] - 29s 59ms/step - loss: 0.7318 - accuracy: 0.7961
Epoch 2/20
469/469 [==============================] - 28s 59ms/step - loss: 0.3032 - accuracy: 0.9106
Epoch 3/20
469/469 [==============================] - 29s 63ms/step - loss: 0.2274 - accuracy: 0.9319
Epoch 4/20
469/469 [==============================] - 27s 58ms/step - loss: 0.1904 - accuracy: 0.9435
Epoch 5/20
469/469 [==============================] - 27s 58ms/step - loss: 0.1694 - accuracy: 0.9491
Epoch 6/20
469/469 [==============================] - 27s 58ms/step - loss: 0.1497 - accuracy: 0.9549
Epoch 7/20
469/469 [==============================] - 27s 58ms/step - loss: 0.1344 - accuracy: 0.9592
Epoch 8/20
469/469 [==============================] - 28s 61ms/step - loss: 0.1253 - accuracy: 0.9620
Epoch 9/20
469/469 [==============================] - 27s 58ms/step - loss: 0.1138 - accuracy: 0.9656
Epoch 10/20
469/469 [==============================] - 27s 59ms/step - loss: 0.1060 - accuracy: 0.9684
Epoch 11/20
469/469 [==============================] - 27s 58ms/step - loss: 0.1024 - accuracy: 0.9686
Epoch 12/20
469/469 [==============================] - 27s 59ms/step - loss: 0.0989 - accuracy: 0.9701
Epoch 13/20
469/469 [==============================] - 29s 62ms/step - loss: 0.0907 - accuracy: 0.9727
Epoch 14/20
469/469 [==============================] - 27s 59ms/step - loss: 0.0877 - accuracy: 0.9731
Epoch 15/20
469/469 [==============================] - 28s 59ms/step - loss: 0.0846 - accuracy: 0.9743
Epoch 16/20
469/469 [==============================] - 27s 58ms/step - loss: 0.0811 - accuracy: 0.9754
Epoch 17/20
469/469 [==============================] - 28s 60ms/step - loss: 0.0784 - accuracy: 0.9763
Epoch 18/20
469/469 [==============================] - 29s 61ms/step - loss: 0.0747 - accuracy: 0.9769
Epoch 19/20
469/469 [==============================] - 27s 58ms/step - loss: 0.0735 - accuracy: 0.9776
Epoch 20/20
469/469 [==============================] - 27s 58ms/step - loss: 0.0712 - accuracy: 0.9775
<keras.callbacks.History at 0x7f5e15859150>
loss, acc = model.evaluate(x_test, y_test, batch_size=batch_size)
loss, acc
>>>
79/79 [==============================] - 2s 22ms/step - loss: 0.0640 - accuracy: 0.9801
(0.06404527276754379, 0.9800999760627747)
input_shape = (image_size, image_size)로 실제로 input_shape = (timesteps, input_dim) 또는 input_dim 의 시퀀스(timesteps 길이의 차원벡터)다.
두 번재로 RNN 셀을 표현하기 위해 units=256으로 된 SimpleRNN 계층을 사용한다. units 변수는 출력 유닛 개수를 뜨샇ㄴ다. RNN의 출력은 현재 입력뿐만 아니라 이전 출력이나 은닉 상태로 구성된 함수다. 이전 출력도 이전 입력의 함수이므로 현재 출력도 이전 출력과 입력이 연쇄적으로 구성된 함수다.
다음 방정식은 SimpleRNN의 출력을 설명한다.
b는 편향 값이고 W와 U는 각각 순환 커널과 커널이다. 아래 첨자 t는 시퀀스에서의 위치를 가리킨다.
256 + 256*256 + 256*28 = 72960 개의 매개변수
SimpleRNN과 RNN의 차이는 소프트맥스 계산 전에 O_t = Vh_t + c 출력값이 없다는 것
시간 단계마다 셀이 하나 존재하지만, 실제로 네트워크를 펼치지 않으면 똑같은 셀을 반복적으로 재사용하기 때문에 셀이 여러 개 존자하는 것 같지만 RNN의 기본 신경망은 모든 셀에 공유된다.
실제론 RNN군에 있는 다른 모델들이 더 보편적으로 사용되는데 LSTM의 경우 장기 종속성 문제를 해결하거나 현재 출력과 관련한 과거 정보를 기억한다.
'basic_ML_models' 카테고리의 다른 글
basic_autoencoder (0) | 2022.10.23 |
---|---|
basic_Y_network_model (1) | 2022.10.23 |
basic_functional_model_RNN (1) | 2022.10.23 |
basic_CNN (0) | 2022.10.23 |
basic_MLP (0) | 2022.10.23 |