카테고리 없음
ResNet을 이용한 MNIST 필기숫자 학습
태지쌤
2023. 12. 1. 07:57
반응형
from tensorflow.keras import datasets, models
from tensorflow.keras import Model, Input, optimizers
from tensorflow.keras.layers import Flatten, Dense
from tensorflow.keras.layers import Conv2D, MaxPooling2D
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.layers import ReLU
def res_blk(x, n_filters, f_size=3):
xx = Conv2D(n_filters, f_size,
padding='same')(x)
xx = BatchNormalization()(xx)
xx = ReLU()(xx)
xx = Conv2D(n_filters, f_size,
padding='same')(xx)
xx = BatchNormalization()(xx)
return ReLU()(xx + x)
# MNIST 필기체 숫자 데이터세트 가져오기
(train_imgs, train_labels), (test_imgs, test_labels) \
= datasets.mnist.load_data()
# 픽셀 값을 0~1 사이로 정규화
train_imgs, test_imgs = train_imgs / 255.0, test_imgs / 255.0
# Conv2D에 맞게 데이터 reshape
train_imgs = train_imgs.reshape(60000, 28, 28, 1)
test_imgs = test_imgs.reshape(10000, 28, 28, 1)
def res_blk(x, n_filters, f_size=3):
xx = Conv2D(n_filters, f_size, padding='same')(x)
xx = BatchNormalization()(xx)
xx = ReLU()(xx)
xx = Conv2D(n_filters, f_size, padding='same')(xx)
xx = BatchNormalization()(xx)
return ReLU()(xx + x)
# 모델 구성 후 요약 정보 출력
inputs = Input(shape=(28, 28, 1))
x = Conv2D(64, 3, activation='relu')(inputs)
x = res_blk(x, 64, 3)
x = MaxPooling2D((2, 2))(x)
x = res_blk(x, 64, 3)
x = MaxPooling2D((2, 2))(x)
x = Conv2D(32, 3)(x)
x = Flatten()(x)
x = Dense(64, activation='relu')(x)
outputs = Dense(10, activation='softmax')(x)
model = Model(inputs=inputs, outputs=outputs)
model.summary()
# 모델 컴파일
model.compile(optimizer=optimizers.SGD(0.001, momentum=0.9),
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# 학습
model.fit(train_imgs, train_labels, epochs=5)
# 모델 저장
models.save_model(model, 'RN-mnist')
# 테스트 집합을 대상으로 평가
_, test_acc = model.evaluate(test_imgs, test_labels, verbose=1)
print('테스트 데이터세트 인식률 = ', test_acc)
반응형