박가방

4. Minst 손 글씨 분석[다중분류] - Early Stopping 본문

데이터 마이닝/딥러닝

4. Minst 손 글씨 분석[다중분류] - Early Stopping

박가방 2023. 3. 23. 10:45

- 본문에서는 Minst 손 글씨 예제와 추가적으로 EalryStopping 기법에 대해 공부하고자 한다.

- 학습 곡선에서 train loss는 당연히 떨어질 수 밖에 없다. 거의 증가하지 않는다.

- 따라서 validation loss를 보면서 과적합을 막아보자

1. 환경준비

① 라이브러리 불러오기

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

from sklearn.model_selection import train_test_split
from sklearn.metrics import *
from sklearn.preprocessing import MinMaxScaler

from keras.models import Sequential
from keras.layers import Dense, Flatten
from keras.backend import clear_session
from keras.optimizers import Adam
from keras.datasets import mnist

#Early Stopping
from keras.callbacks import EarlyStopping

② 학습 곡선

# 학습곡선 함수
def dl_history_plot(history):
    plt.figure(figsize=(10,6))
    plt.plot(history['loss'], label='train_err', marker = '.')
    plt.plot(history['val_loss'], label='val_err', marker = '.')

    plt.ylabel('Loss')
    plt.xlabel('Epoch')
    plt.legend()
    plt.grid()
    plt.show()

③ Minst 데이터 불러오기

# 케라스 데이터셋으로 부터 mnist 불러오기
(x_train, y_train), (x_val, y_val) = mnist.load_data()
x_train.shape, y_train.shape

- 28 X 28 형을 가진 6만개의 3차원 데이터

④ 데이터 살펴보기

# 아래 숫자를 바꿔가며 화면에 그려 봅시다.
n = 59999

plt.figure()
plt.imshow(x_train[n], cmap=plt.cm.binary)
plt.colorbar()
plt.show()

- 28 X 28 형을 가지고 있으며 각각의 픽셀에는 0~255의 값이 할당되어 있다.

- 오른쪽 그림에서, 위에서부터 28개의 열을 가진 각각의 행이 28행까지 계속 내려오는 것.

 

plt.figure(figsize=(10,10))
for i in range(25):
    plt.subplot(5,5,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.imshow(x_train[i], cmap=plt.cm.binary)
    plt.xlabel(class_names[y_train[i]])
plt.tight_layout()
plt.show()

#우리의 분석단위는 이미지 한장

2. 데이터 전처리

x_train.shape, y_train.shape, x_val.shape, y_val.shape

 - Mnist가 깔끔히 나눠줬구나

① flatten(평탄화)

#flatten 2 -> 1차원
x_train = x_train.reshape(60000, -1)
x_val = x_val.reshape(10000, -1)

 - 28 x 28 형의 하나의 이미지가 1x784 형의 데이터로 변경

 

② 스케일링

 - 0-255 값으로 되어 있는 데이터를 0 ~ 1사이 값으로 변환

# 0~255 값을 0~1로 스케일링
x_train = x_train / 255.
x_val = x_val / 255.

3. 모델링

① features 선언

nfeatures = x_train.shape[1]
# 결과 : nfeatures : 784

② 모델 구조 선언 & 컴파일 & 학습

# 메모리정리
clear_session()

# 모델 구조 선언
model = Sequential([Dense(10, input_shape = (nfeatures,), activation = 'softmax')])

# 컴파일
model.compile(optimizer=Adam(learning_rate=0.001), loss='sparse_categorical_crossentropy')

# 학습 및 loss 할당
history = model.fit(x_train, y_train, epochs = 100, validation_split=0.2).history

 

③ 학습 곡선 

- 따라서 validation loss를 보면서 과적합을 막아보자

dl_history_plot(history)

4. 과적합 방지

- 대부분의 경우에 ealry stopping 사용함.

① early stopping 설정

md = 0.01 # 0.01값 이상으로 커지면 카운팅
pa = 5    # 그것이 5회 카운팅 될 경우 스톱
es = EarlyStopping(monitor = 'val_loss', min_delta = md, patience = pa)

② 모델 구조 선언 & 컴파일 & 모델 학습

# 모델 구조 선언
model = Sequential([Dense(10, input_shape = (nfeatures,), activation = 'softmax')])

# 컴파일
model.compile(optimizer=Adam(learning_rate=0.001), loss='sparse_categorical_crossentropy')

# 모델학습 및 loss 할당
history = model.fit(x_train, y_train, epochs = 100, validation_split = .2, callbacks = [es]).history

 

③ 학습 곡선 비교

 

변경 전                                                                                 변경 후

#0.01만큼 변화 했는데, 5번동안 증가하여 스톱

④ 학습 곡선 비교

변경 전                                                                                 변경

 - 성능이 약간 증가하였다.

 

5. 모델 저장 및 불러오기

- mlflow

① 모델 저장 - keras

- model.save(‘파일이름.h5’) - (h5 file format: hadoop file format)

Hadoop 이란: 

- keras로 만든 모델은 자체적으로 저장하게 해줍니다.
- Apache Hadoop은 컴퓨팅 리소스 클러스터 간에 대규모 데이터 세트를 분산 처리할 수 있는 오픈 소스 프레임워크를 제공합니다. 
- 설계를 단일 서버에서 수천 대의 서버로 확장할 수 있으며 각각 로컬 컴퓨팅 및 스토리지 기능을 제공합니다.
- Google의 MapReduce와 비슷

# 출처 : https://www.hpe.com/kr/ko/what-is/hadoop.html

model.save('mnist_model.h5')

② 모델 불러오기

# load 라이브러리 불러오기
from keras.models import load_model
# 불러오기
model2 = load_model('mnist_model.h5')

 

범용적인 저장

- 범용적인 저장 joblib.damp, .load
- 피클링 한다 : 파이썬의 오브젝트들을 저장한다. -> .pkl