츨처 : <"코딩셰프의 3분 딥러닝 케라스맛" 김성진 저>를 공부하면서 작성하였습니다.
코드
- 함수형 모델 구성과 객체지향형 모델 구성 두 가지 모델이 구현되어 있지만 어느걸로 써도 동일한 결과를 얻을 수 있다.
# basic ANN(shallow neural network으로도 불림 snn)
# mnist 분류를 ANN을 이용하여 구성
# 패키지 임포트
from keras import layers, models
# 연쇄 방식 모델링 함수형 구현 방법
# model을 초기화 하고 add를 이용한 구현 방식을 사용한다.
# 함수형, 객체지향형 둘다 같은 결과를 가진다.
# ann 함수형 모델 구성
def ANN_func(Nin,Nh,Nout):
# 모델 초기화
model = models.Sequential()
# 활성 함수 relu
model.add(layers.Dense(Nh,activation='relu',input_shape=(Nin,)))
# 활성 함수 softmax
model.add(layers.Dense(Nout),activation='softmax')
# 손실 함수 교차 엔트로피
model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
return model
# ann 객체지향형 모델 구성
# models.Sequential로 부터 상속 받는다.
class ANN_class(models.Sequential):
def __init__(self,Nin,Nh,Nout):
# 부모 클래스 초기화
super().__init__()
self.add(layers.Dense(Nh,activation='relu',input_shape=(Nin,)))
self.add(layers.Dense(Nout, activation='softmax'))
self.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
# 데이터 불러오기
import numpy as np
# mnist() 함수 사용하기 위해
from keras import datasets
# to_categorical() 함수 사용하기 위해
from keras.utils import np_utils
def Data_func():
# mnist를 읽어옵니다.
(x_train,y_train),(x_test,y_test) = datasets.mnist.load_data()
# 0~9까지의 숫자를 0과 1로 표현되는 벡터로 변환
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
# 기존의 l*w*h형식의 데이터를 l*(w*h)로 변환한다.
l,w,h = x_train.shape
x_train = x_train.reshape(-1,w * h)
x_test = x_test.reshape(-1,w * h)
# 0~255의 값을 0~1사이의 값으로 변환(정규화라고 한다)
x_train = x_train/255.0
y_train = y_train/255.0
return (x_train,y_train),(x_test,y_test)
import matplotlib.pyplot as plt
# 손실 그래프
def plot_loss(history):
# 선 그리기
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
# 그래프 제목
plt.title('Model Loss')
# x,y축 이름 표시
plt.ylabel('Loss')
plt.xlabel('Epoch')
# 각 라인 표식 표시
plt.legend(['Train','Test'],loc=0)
# 정확도 그래프
def plot_acc(history):
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc=0)
# 메인 함수
def main():
Nin=784
Nh=100
number_of_class=10
Nout=number_of_class
model= ANN_class(Nin,Nh,Nout)
(x_train,y_train),(x_test,y_test)=Data_func()
# epochs 회수만큼 반복한다, batch_size 개수만큼 나눠서 넣느다
history=model.fit(x_train,y_train,epochs=15,batch_size=100,validation_split=0.2)
performace_Test=model.evaluate(x_test,y_test,batch_size=100)
print('Test Lost and Accuracy ->',performace_Test)
plot_loss(history)
plt.show()
plot_acc(history)
plt.show()
# 실행
if __name__ == '__main__':
main()
실행 결과
- 15/15 : epoch 15번의 반복횟수중 15번이 끝났을때의 결과를 의미한다.
- 100/48000 : 48000개의 데이터 중에서 100개 학습하였다.
- 1s or 0s : 학습하는데 걸린 시간.
- loss : 손실값
- acc : 정확도
- val_loss, val_acc : 검증 데이터 이용한 손실,정확도
- 트레이닝 셋에 대한 정확도는 점점 높아진다.
- 테스트 셋에 대한 정확도는 어느정도 상승한 이후에 오히려 떨어지기도 한다.
- 같은 데이터를 이용해서 반복학습 하기 때문에 다음과 같은 이유들이 발생하는 것 같다.(과적합(오버피팅)이라고 표현한다.)
'IT > 머신러닝' 카테고리의 다른 글
| [keras] DNN (Basic CIFAR10) (0) | 2018.09.06 |
|---|---|
| [Keras] DNN 기본 예제 (0) | 2018.08.31 |
| [Keras] 기본 예제 (0) | 2018.08.31 |
| [section_12_lab] Dynamic RNN & RNN with Time Series Data (0) | 2018.06.01 |
| [section_12_lab] Long Sequence RNN (by Stacked RNN + Softmax layer) (0) | 2018.06.01 |