심층 신경망 DNN(Deep Neural Network) : 은닉 게층을 많이 쌓아서 만든 인공지능 기술
활성화 함수의 종류는 RELU, softmax, sigmoid가 있다.
컴파일 시 모멘텀, 아다 그리드, 아담 등의 최적화 함수를 통해 역으로 추적 분석하는 최적화 과정을 거친다.
모멘텀 :
경사도 소실 문제 : 여러 은닉 계층으로 구성되어 지능망의 최적화 과정에서 학습에 사용하는 활성화 함수에 따라 경사도 소실이 발생할 수 있다.
- 경사도 소실 문제는 문제에 맞는 활성화 함수(시그모이드, ReLU, softmax...)들을 이용하여 극복
필기체를 분류하는 DNN 예제를 mnist 데이터 셋으로 실습했다.
기본 파라미터 설정
#기본 파라미터 설정
Nin = 784
Nh_l = [100, 50]
number_of_class = 10
Nout = number_of_class
입력 노드 수는 기존 데이터 셋의 28 x 28인 784, 출력 노드 수는 10개로 설정한다.
이전의 은닉계층 Nh_l은 100과 50 두 개로 설정한다.
#분류 DNN 모델 구현
from keras import layers, models
class DNN(models.Sequential):
def __init__(self, Nin, Nh_l, Nout):
super().__init__()
DNN 객체를 models.Sequential로부터 상속받고 모델링은 객체의 초기화 함수인 __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'))
제1 은닉 계층은 relu 활성화 함수를 이용한다.
마지막 은닉 계층은 softmax를 적용한다.
Softmax는 입력받은 값을 출력으로 0~1사이의 값으로 모두 정규화하며 출력 값들의 총합은 항상 1이 된다.
self.add(layers.Dropout(0.2))
드롭아웃 기법은 괄호 안의 확률로 출력 노드의 신호를 보내다 말다 하여 다음에 오는 계층이 더욱 견고하게 신호에 적응한다.
keras에서는 이 차이를 자동으로 처리하기 때문에 추가할 필요가 없다.
self.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# adam : 가장 많이 사용되는 최적화 함수
metrics 인자로 여러 개의 평가 기준을 지정할 수 있다.
학습 과정 중에 제대로 학습되고 있는 지 살펴볼 수 있다.
compile 메서드의 loss 인수를 다음과 같은 keras의 crossentropy로 선택하여 사용한다.
- mean_squared_error
- mean_squared_logarithmic_error
- mean_absolute_error
- mean_absolute_percentage_error
- binary_crossentropy
- categorical_crossentropy
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_train이 어떤 숫자일지 각 숫자마다 예측한 퍼센트를 나타내는 것 / 출력할 때는 제일 가능성 큰 값을 1로 출력
y_test = np_utils.to_categorical(y_test)
L, W, H = x_train.shape
x_train = x_train.reshape(-1, W*H) #28x28의 높이와 너비를 하나로
x_test = x_test.reshape(-1, W*H)
x_train = x_train/255.0
x_test = x_test/255.0 #뭔지 다시 알아보기
mnist 데이터 셋을 가져온다.
categorical 변환은 해당 숫자가 5 이면 [0. 0. 0. 0. 1. 0. 0. 0. 0]처럼 바꾼다.
reshape으로 28x28의 높이와 너비를 784 하나로 변환한다.
# 분류 DNN 학습 및 성능 평가
model = DNN(Nin, Nh_l, Nout)
history = model.fit(x_train, y_train, epochs=10, batch_size=100,
validation_split=0.2)#validation_split : 20%를 테스트에 쓰임
perfomace_test = model.evaluate(x_test, y_test, batch_size=100)
print('Test loss and accuracy', perfomace_test)
batch_size : 한 번의 배치마다 학습하는 양
epochs : 학습하는 횟수
validation_split : 테스트에 쓰일 데이터 양
학습 결과를 history에 넣는다.
import matplotlib.pyplot as plt
fig, loss_ax = plt.subplots(figsize=(10,5))
acc_ax = loss_ax.twinx()
loss_ax.plot(history.history['loss'], 'y', label='train loss')
loss_ax.plot(history.history['val_loss'], 'r', label='val loss')
acc_ax.plot(history.history['accuracy'], 'b', label='train accuracy')
acc_ax.plot(history.history['val_accuracy'], 'g', label='val accuracy')
loss_ax.set_xlabel('epoch')
loss_ax.set_ylabel('loss')
acc_ax.set_ylabel('accuracy')
loss_ax.legend(loc='upper left')
acc_ax.legend(loc='lower left')
plt.show()
plot을 출력하면 다음과 같다.
#기본 파라미터 설정
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'])# adam : 가장 많이 사용되는 최적화 함수
# history data에 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_train이 어떤 숫자일지 각 숫자마다 예측한 퍼센트를 나타내는 것 / 출력할 때는 제일 가능성 큰 값을 1로 출력
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=10, batch_size=100,
validation_split=0.2)#validation_split : 20%를 테스트에 쓰임
perfomace_test = model.evaluate(x_test, y_test, batch_size=100)#평가
print('Test loss and accuracy', perfomace_test)
import matplotlib.pyplot as plt
fig, loss_ax = plt.subplots(figsize=(10,5))
acc_ax = loss_ax.twinx()
loss_ax.plot(history.history['loss'], 'y', label='train loss')
loss_ax.plot(history.history['val_loss'], 'r', label='val loss')
acc_ax.plot(history.history['accuracy'], 'b', label='train accuracy')
acc_ax.plot(history.history['val_accuracy'], 'g', label='val accuracy')
loss_ax.set_xlabel('epoch')
loss_ax.set_ylabel('loss')
acc_ax.set_ylabel('accuracy')
loss_ax.legend(loc='upper left')
acc_ax.legend(loc='lower left')
plt.show()
코딩셰프의 3분 딥러닝, 케라스맛
케라스 코드로 맛보는 딥러닝 핵심 개념! 간결하고 직관적인 인공신경망 API를 제공하는 케라스는 구글 텐서플로, 마이크로소프트 CNTK, 아마존 MXNET, OpenCL PlaidML, 시애노 등의 딥러닝 엔진에서 지
www.google.com
'Deep Learning' 카테고리의 다른 글
합성곱신경망 CNN(Convolutional Neural Network) (2) | 2020.08.18 |
---|---|
분류 모델 2 (0) | 2020.08.12 |
군집화 KMean 알고리즘 2 (0) | 2020.08.12 |
군집화 KMean 알고리즘 (1) | 2020.08.12 |
분류 모델 (0) | 2020.08.11 |