본문 바로가기
DNN with Keras/Regularization and Dropout

홀드아웃 (Holdout) 방법

by goatlab 2023. 7. 24.
728x90
반응형
SMALL

홀드아웃 (Holdout) 방법

 

 

주어진 원천 데이터를 랜덤 (random)하게 두 분류로 분리하여 교차 검정을 실시하는 방법이다. 하나는 모형의 학습 및 구축을 위한 훈련용 데이터로 하나는 성과 평가를 위한 검증용 데이터로 사용한다.

 

Classification with Stratified K-Fold Cross-Validation

 

샘플 부족을 생성하기 위해 교차 검증을 사용하여 데이터 세트를 훈련하고 fit한다. 또한, 표본 외 (검정 세트에 대한 예측) 결과도 기록한다. 분류 데이터를 사용하여 계층화된 k-폴드 교차 검증을 수행하는 것이 좋다. 이 기법을 사용하면 모든 접기에서 각 클래스의 백분율이 동일하게 유지된다. 계층화 사용회귀 분석에 사용된 KFold 개체 대신 StratifiedKFold개체이다.

 

import pandas as pd
import os
import numpy as np
from sklearn import metrics
from scipy.stats import zscore
from sklearn.model_selection import StratifiedKFold
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation

EPOCHS = 500
kf = StratifiedKFold(5 , shuffle = True , random_state = 42)
oos_y = [ ]
oos_pred = [ ]

fold = 0
for train, test in kf.split(x):
  fold += 1
  print(f"Fold #{fold}")

  x_train = x[train]
  y_train = y[train]
  x_test = x[test]
  y_test = y[test]

  model = Sequential()
  model.add(Dense(20, input_dim = x.shape[1], activation = 'relu'))
  model.add(Dense(10, activation = 'relu'))
  model.add(Dense(1))
  model.compile(loss = 'mean_squared_error', optimizer = 'adam')
  model.fit(x_train, y_train, validation_data = (x_test, y_test), verbose= 0, epochs= EPOCHS)
  pred = model.predict(x_test)
  
  oos_y.append(y_test)
  oos_pred.append(pred)
  
  score = np.sqrt(metrics.mean_squared_error(pred, y_test))
  print(f"Fold score (RMSE) : {score}")

oos_y = np.concatenate(oos_y)
oos_pred = np.concatenate(oos_pred)
score = np.sqrt(metrics.mean_squared_error(oos_pred, oos_y))
print(f"Final, out of sample score (RMSE) : {score}")

oos_y = pd.DataFrame(oos_y)
oos_pred = pd.DataFrame(oos_pred)
oosDF = pd.concat([df, oos_y, oos_pred], axis = 1)

oosDF.to_csv(filename_write, index = False)

 

Training with both a Cross-Validation and a Holdout Set

 

상당한 양의 데이터가 있는 경우 교차 검증하기 전에 홀드아웃 세트를 따로 두는 것이 항상 중요하다. 이 홀드아웃 세트는 실제 사용을 위해 모델을 사용하기 전에 최종 평가가 된다.

 

import pandas as pd
import os
import numpy as np
from sklearn import metrics
from scipy.stats import zscore
from sklearn.model_selection import KFold
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation

# Keep a 10% holdout
x_main , x_holdout , y_main , y_holdout = train_test_split(x, y, test_size = 0.10)

EPOCHS = 500
kf = KFold(5)
oos_y = [ ]
oos_pred = [ ]

fold = 0
for train, test in kf.split(x):
  fold += 1
  print(f"Fold #{fold}")

  x_train = x[train]
  y_train = y[train]
  x_test = x[test]
  y_test = y[test]

  model = Sequential()
  model.add(Dense(20, input_dim = x.shape[1], activation = 'relu'))
  model.add(Dense(10, activation = 'relu'))
  model.add(Dense(1))
  model.compile(loss = 'mean_squared_error', optimizer = 'adam')
  model.fit(x_train, y_train, validation_data = (x_test, y_test), verbose= 0, epochs= EPOCHS)
  pred = model.predict(x_test)
  
  oos_y.append(y_test)
  oos_pred.append(pred)
  
  score = np.sqrt(metrics.mean_squared_error(pred, y_test))
  print(f"Fold score (RMSE) : {score}")

oos_y = np.concatenate(oos_y)
oos_pred = np.concatenate(oos_pred)
score = np.sqrt(metrics.mean_squared_error(oos_pred, oos_y))
print(f"Final, out of sample score (RMSE) : {score}")

holdout_pred = model.predict(x_holdout)
score = np.sqrt(metrics.mean_squared_error(holdout_pred, y_holdout))
print(f"Holdout score (RMSE) : {score}")
728x90
반응형
LIST