9

모델 Early Stopping

모델이 훈련 세트에서 적절한 패턴을 학습하여 모델 성능이 최고점에 도달한 경우 자동으로 학습을 종료해주는 것. Early Stopping을 사용하면 정해놓은 epochs의 횟수만큼 다 학습을 하는 것이 아니라 학습 도중 모니터 하고 있는 값이 모니터 하는 도중 개선효과가 없어지기 시작하면 학습을 중단한다.

- 필요한 라이브러리 인포트

# TensorFlow and tf.keras

import tensorflow as tf

from tensorflow import keras

# Helper libraries

import numpy as np

import matplotlib.pyplot as plt

import math

- 상수 선언

# Define Constants

batch_size = 128

epochs = 10000

num_classes = 10

- MNIST에서 학습용(6만개), 테스트용(1만개) 이미지 셋(이미지, 결과 값 페어) 다운로드

# Download MNIST dataset.

mnist = keras.datasets.mnist

(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

- Tensorflow에서 계산하기 쉽도록 값을 0에서 1사이의 값으로 변환 계산한다.

 : 실수로 계산하는 것이 더 좋다.

** 각 이미지에는 0~ 255까지의 채도 값이 들어있다.

# Normalize the input image so that each pixel value is between 0 to 1.

train_images = train_images / 255.0

test_images = test_images / 255.0

- 모델 생성

** 모델을 견고하게 변경, 은닉층을 보강, Convolutional Neural Network를 이용해서 강화

# Define the model architecture with CNN

model = keras.Sequential([

                         keras.layers.Flatten(input_shape=(28,28)),

                         # Hidden Layers

                         # keras.layers.Dense(128, activation=tf.nn.relu),

                         keras.layers.Reshape(target_shape=(28, 28, 1)),

                         keras.layers.Conv2D(filters=32, kernel_size=(3, 3), activation=tf.nn.relu),

                         keras.layers.Conv2D(filters=64, kernel_size=(3, 3), activation=tf.nn.relu),

                         keras.layers.MaxPooling2D(pool_size=(2, 2)),

                         keras.layers.Dropout(0.25),

                         keras.layers.Flatten(input_shape=(28, 28)),

                         keras.layers.Dense(128, activation=tf.nn.relu),

                         keras.layers.Dropout(0.5),

                         keras.layers.Dense(num_classes, activation='softmax')

])

model.compile(optimizer='adam',

              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),

              metrics=['accuracy'])

- 모델 체크포인트 객체 생성

# Save the best model as digits_model.h5

filepath = 'digits_model.h5'

modelCheckpoint = tf.keras.callbacks.ModelCheckpoint(filepath=filepath, save_best_only=True)

- Early Stopping 작성 : 모니터링 대상은 validation loss값이다.

# Define a callback to monitor val_loss

monitorEarlyStop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5)

[참고]

https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/EarlyStopping

** monitor : 모니터 대상

** patience : local minimum이 있을 수 있기 때문에, 정해 놓은 횟수 만큼은 기다리는 것이다.

- 학습 : callback 설정

history = model.fit(train_images, train_labels,

                    validation_data=(test_images, test_labels),

                    epochs=epochs, batch_size=batch_size,

                    callbacks=[modelCheckpoint, monitorEarlyStop])

** val_loss의 값이 낮아지는 동안에는 멈추지 않는다.

** 16회 학습했다.

- 그림 표시용 함수 선언

# Helper function to display digit images

# 샘플을 보여주는 함수

def show_sample(images, labels, sample_count=25):

  # Create a square with can fit {sample_count} images

  grid_count = math.ceil(math.ceil(math.sqrt(sample_count)))

  grid_count = min(grid_count, len(images), len(labels))

  plt.figure(figsize=(2*grid_count, 2*grid_count))

  for i in range(sample_count):

    plt.subplot(grid_count, grid_count, i+1)

    plt.xticks([])

    plt.yticks([])

    plt.grid(False)

    plt.imshow(images[i], cmap=plt.cm.gray)

    plt.xlabel(labels[i])

  plt.show()

# Helper function to display specific digit images

# 샘플의 특정 숫자를 보여주는 함수

def show_sample_digit(images, labels, digit, sample_count=25):

  # Create a square with can fit {sample_count} images

  grid_count = math.ceil(math.ceil(math.sqrt(sample_count)))

  grid_count = min(grid_count, len(images), len(labels))

  plt.figure(figsize=(2*grid_count, 2*grid_count))

  i = 0

  digit_count = 0

  while digit_count < sample_count:

    i += 1

    if (digit == labels[i]):

      plt.subplot(grid_count, grid_count, digit_count+1)

      plt.xticks([])

      plt.yticks([])

      plt.grid(False)

      plt.imshow(images[i], cmap=plt.cm.gray)

      plt.xlabel(labels[i])

      digit_count += 1

  plt.show()

# Helper function to display specific digit images

# 특정 숫자를 좀 더 크게 보여주는 함수

def show_digit_image(image):

  # Draw digit image

  fig = plt.figure()

  ax = fig.add_subplot(1, 1, 1)

  # Major ticks every 20, minor ticks every 5

  major_ticks = np.arange(0, 29, 5)

  minor_ticks = np.arange(0, 29, 1)

  ax.set_xticks(major_ticks)

  ax.set_xticks(minor_ticks, minor=True)

  ax.set_yticks(major_ticks)

  ax.set_yticks(minor_ticks, minor=True)

  # And a corresponding grid

  ax.grid(which='both')

  # Or if you want different settings for the grids:

  ax.grid(which='minor', alpha=0.2)

  ax.grid(which='major', alpha=0.5)

  ax.imshow(image, cmap=plt.cm.binary)

plt.show()

# 다운로드 하는 함수

# Download the digit classification model if you're using Colab,

# or print the model's local path if you're not using Colab.

def download(path):

    try:

        from google.colab import files

        files.download(path)

    except ImportError:

        import os

        print('Error dowbload:', os.path.join(os,getcwd(), path))

- 모델 다운로드

# Download the digit classification model if you're using Colab

download(filepath)

- 전체 모델 저장

# Save Model

savefile = 'saved_digits.h5'

model.save(savefile)

- 모델 구조 확인

model.summary()

- 저장된 내용 확인(리눅스 명령어)

!ls -al

- 모델 불러오기

# Load Model

load_model = tf.keras.models.load_model(savefile)

- 불러온 모델 구조 확인

load_model.summary()

- 모델 정확도 평가

# Evaluate the model using test dataset.

test_loss, test_acc = model.evaluate(test_images, test_labels)

print('Test Accuracy: ', test_acc)

# Evaluate the load model using test dataset.

test_loss, test_acc = load_model.evaluate(test_images, test_labels)

print('Load model Test Accuracy: ', test_acc)

- 그래프 생성

# Evaluate the model using test dataset. - Show performance

fig, loss_ax = plt.subplots()

fig, acc_ax = plt.subplots()

loss_ax.plot(history.history['loss'], 'ro', label='train_loss')

loss_ax.plot(history.history['val_loss'], 'r:', label='validation_loss')

loss_ax.set_xlabel('epoch')

loss_ax.set_ylabel('loss')

loss_ax.legend(loc='upper left')

acc_ax.plot(history.history['accuracy'], 'bo', label='train_accuracy')

acc_ax.plot(history.history['val_accuracy'], 'b:', label='validation_accuracy')

acc_ax.set_xlabel('epoch')

acc_ax.set_ylabel('accuracy')

acc_ax.legend(loc='upper left')

plt.show()

 



기재: 본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성되었습니다.

https://bit.ly/37BpXiC

 

패스트캠퍼스 [직장인 실무교육]

프로그래밍, 영상편집, UX/UI, 마케팅, 데이터 분석, 엑셀강의, The RED, 국비지원, 기업교육, 서비스 제공.

fastcampus.co.kr

 

+ Recent posts