본문 바로가기
Keras Deep Learning

필기체를 분류하는 DNN 구현 실습

by yj.yoon 2020. 8. 19.

개발 환경 : pycharm-community-2020.2 (무료 에디션)

Anaconda, python3.7, Windows 10


1. 기본 파라미터 설정

Nin = 784
Nh_l = [100, 50]
number_of_class = 10
Nout = number_of_class

- Nout는 분류할 클래스 수와 같은 10개로 설정한다. (0~9까지의 필기체 구분 = 10개)

- 은닉 계층은 2개, 각각의 은닉 노드를 100과 50으로 지정했다.

 

 

2. 모델 구현

from keras import layers, models

class DNN(models.Sequential):
    def __init__(self, Nin, Nh_l, Nout):
        super().__init__()
        self.add(layers.Dense(Nh_l[0], activation='relu', input_shape=(Nin,), name='Hidden-1'))
        self.add(layers.Dense(Nh_l[1], activation='relu', name='Hidden-2'))
        self.add(layers.Dense(Nout, activation='softmax'))
        self.compile(loss='categorical_crossentropy',
                     optimizer='adam', # 최적화 방식
                     metrics=['accuracy'])

- 연쇄방식 모델링 객체지향 구현

- DNN 객체를 models.Sequential로부터 상속받는다. 그리고 모델링은 객체의 초기화 함수인 __init__에서 구성한다.

- super().__init__() : 연쇄방식으로 구성할 것이므로 부모 클래스의 초기화 함수를 먼저 불러서 모델링을 시작한다.

- input_shape=(Nin,), name='Hidden-1' : 입력 계층의 정의는 첫 번째 은닉 계층의 정의와 함께 이루어진다.

컴파일(compile) - 분류할 클래스 수가 2개 이상이므로 'categorical_crossentropy'를 loss로 설정

 

 

3. 데이터 준비

4. 학습 및 성능 평가

모두 ANN과 동일하다.

 

 

전체 코드

# 기본 파라미터 설정
Nin = 784
Nh_l = [100, 50]
number_of_class = 10
Nout = number_of_class

# 분류 DNN 모델 구현
from keras import layers, models

class DNN(models.Sequential):
    def __init__(self, Nin, Nh_l, Nout):
        super().__init__()
        self.add(layers.Dense(Nh_l[0], activation='relu', input_shape=(Nin,), name='Hidden-1'))
        self.add(layers.Dense(Nh_l[1], activation='relu', name='Hidden-2'))
        self.add(layers.Dense(Nout, activation='softmax'))
        self.compile(loss='categorical_crossentropy',
                     optimizer='adam',
                     metrics=['accuracy'])

# 데이터 준비
import numpy as np
from keras import datasets
from keras.utils import np_utils

(X_train, y_train), (X_test, y_test) = datasets.mnist.load_data()

y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)

L, W, H = X_train.shape
X_train = X_train.reshape(-1, W * H)
X_test = X_test.reshape(-1, W * H)

X_train = X_train / 255.0
X_test = X_test / 255.0

# 분류 DNN 학습 및 테스팅
model = DNN(Nin, Nh_l, Nout)
history = model.fit(X_train, y_train, epochs=5, batch_size=100, validation_split=0.2)
performace_test = model.evaluate(X_test, y_test, batch_size=100)
print('Test Loss and Accuracy ->', performace_test)

 

콘솔 결과 확인

 

손실 : 0.0946

정확도 : 0.97

 

이미지 데이터가 간단해서 ANN과 DNN의 성능 차이가 거의 없다. 그러나 복잡한 이미지에서는 일반적으로 DNN이 더 우수한 성능을 보인다고 알려져 있다.

 


참고 : 코딩셰프의 3분 딥러닝 케라스맛

ANN 필기체 구분 https://hensorflow.tistory.com/3