Keras 따라하기 Early Stopping 사용법
regularization 기법 중 하나인 조기종료(Early stopping)를 Keras를 통해 구현해본다. keras 의 callbacks 에 Earlystopping 기능을 지원한다.
설명을 보면 Stop training when a monitored quantity has stopped improving. 이라고 써있다. (monitored 하는 양이 향상되지 않으면 멈춘다)
Arguments :
- monitor : 측정할 것을 넣는 변수로, 보통 ‘val_loss’ (검증세트의 loss 값)를 monitor로 삼는다.
- min_delta : 향상되는 가장 최소의 값을 지정해줌으로써 이 값보다 작게 향상될 경우, 향상되지 않는 걸로 간주하고 count를 증가시킨다.
- patience : 인내값, 이 값을 count가 초과하게 되면 조기종료를 마친다.
- verbose : 1 이면 과정을 보여주고 , 0 이면 과정을 출력해주지 않는다.
- mode : {“auto”, “min”, “max”} 가 있고 기본 옵션으로 “auto” 가 사용됨. monitor 값이 증가해야할 경우 “max”, 감소해야할 경우 “min” 을 설정하는데 앞서 위와 같은 예로 “val_loss” 를 사용할 경우 “min” 또는 “auto” 를 사용해야한다.
- baseline : 이 값을 설정해주어 이 값에 도달했을 때 더 이상 training 하지 않게 할 수 있다.
- restore_best_weights : 기본 옵션 “False”로 training에서 가장 마지막에 사용된 가중치를 저장한다.
EarlyStopping 객체를 이용하여 훈련이 이뤄지면 특정시점의 validation error가 줄어들지 않는 곳 부터 patience 값에 도달할 때까지 계속되다 멈추게 된다. 즉 최고의 가중치 값은 마지막이 아닌 patience가 증가되기 시작하는 부분이다. 이 가중치 값을 저장하는 데 도움을 주는 것이 앞서 배운 ModelCheckPoint이다. 어떻게 사용되는지 간단한 예시 코드로 살펴본다.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
from keras.datasets import mnist from keras.utils import np_utils from keras.models import Sequential from keras.layers import Dense from keras.callbacks import ModelCheckpoint, EarlyStopping import os import numpy as np MODEL_SAVE_FOLDER_PATH = '/home/gjtrj45/Project/venv/model/' if not os.path.exists(MODEL_SAVE_FOLDER_PATH): os.mkdir(MODEL_SAVE_FOLDER_PATH) model_path = MODEL_SAVE_FOLDER_PATH + 'mnist' + '{epoch:02d}-{val_loss:.4f}.hdf5' cd_checkpoint = ModelCheckpoint(filepath=model_path, monitor='val_loss', verbose=1, save_best_only=True) cd_early_stopping = EarlyStopping(monitor='val_loss', patience=10) #-----------------data setting ------------------ (X_train, y_train),(X_test, y_test) = mnist.load_data() X_train = np.array(X_train) X_test = np.array(X_test) X_train = X_train.reshape(X_train.shape[0],-1) X_test = X_test.reshape((X_test.shape[0],-1)) X_train = X_train / 255. X_test = X_test / 255. X_val = X_train[50000:] X_train = X_train[:50000] y_train = np_utils.to_categorical(y_train,10) y_test = np_utils.to_categorical(y_test,10) y_val = y_train[50000:] y_train = y_train[:50000] def create_model(): model = Sequential() model.add(Dense(512, input_dim=784, activation='relu')) model.add(Dense(10, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(X_train,y_train,validation_data=(X_val,y_val), epochs=30, batch_size=200, verbose=0, callbacks= [cd_checkpoint, cd_early_stopping]) return model model = create_model() print("\nAccuracy : {:.4f}%".format(model.evaluate(X_test,y_test)[1])) |