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

정규화 기술 벤치마킹 (1) (회귀)

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

Benchmarking Regularization Techniques

 

https://www.researchgate.net/figure/Benchmark-for-solving-a-least-squares-regression-problem-regularized-by-the_fig2_228990355

 

하이퍼 파라미터 값을 각각 조정하면 신경망에서 얻은 점수에 영향을 미칠 수 있다. 하이퍼 파라미터 중 일부는 다음과 같다.

 

• 신경망의 레이어 수

• 각 레이어에서 사용할 뉴런 수

• 각 레이어에서 사용할 활성화 기능

• 각 레이어의 드롭아웃 비율

• 각 레이어의 L1 및 L2 값

 

이 하이퍼 파라미터를 사용하기 위해 여러 설정을 사용하여 신경망을 훈련해야 한다. 그러나 신경망은 여러 번 훈련할 때 종종 다소 다른 결과를 낸다는 것이다. 이것은 신경망이 무작위 가중치로 시작하기 때문이다. 이 때문에 한 세트의 하이퍼 파라미터가 실제로 다른 세트보다 더 낫다는 것을 보장하기 위해 신경망 시간을 맞추고 평가해야 한다. 부트스트래핑은 두 개의 하이퍼 파라미터 세트를 벤치마킹 (비교)하는 효과적인 수단이 될 수 있다.

 

부트스트래핑은 교차 검증과 유사하다. 둘 다 검증 및 교육 세트를 제공하는 여러 사이클/폴딩을 거친다. 그러나 부트스트래핑은 사이클 수에 제한이 없다. 부트스트래핑은 새로운 훈련과 유효성 검사를 각 사이클로 분할하여 대체한다. 각 주기가 교체와 함께 선택된다는 사실은 교차 검증과 달리 주기 사이에 반복 행이 선택되는 경우가 많다는 것을 의미한다. 충분한 주기 동안 부트스트랩을 실행하면 중복 주기가 발생한다.

 

SPLITS 상수로 표시된 지정된 분할 수에 대해 신경망을 훈련시킬 것입니다. 주기가 끝날 때까지 평균 점수는 어느 정도 수렴될 것이다. 이 종료 점수는 단일 교차 검증보다 훨씬 더 나은 비교 기준이 될 것이다. 또한, 가능한 최적 값에 대한 아이디어를 제공하기 위해 평균 에포크 수를 추적한다. 조기 중지 유효성 검사 세트는 신경망을 평가하는 데도 사용되기 때문에 약간 부풀려질 수 있다. 왜냐하면 같은 샘플에 대해 중지하고 평가할 수 있기 때문이다.

 

그러나 점수를 다른 하이퍼 파라미터 세트에 대한 우월성을 결정하기 위한 상대적인 척도로만 사용하고 있으므로, 이 약간의 인플레이션은 너무 큰 문제를 나타내지 않을 것이다. 벤치마킹을 하고 있기 때문에 각 사이클에 걸리는 시간을 표시할 것이다. 다음 기능을 사용하여 시간 범위를 적절하게 포맷할 수 있다.

 

# Nicely formatted timestring
def hms_string(sec_elapsed):
  h = int (sec_elapsed / (60 ∗ 60))
  m = int((sec_elapsed % (60 ∗ 60)) / 60)
  s = sec_elapsed % 60
  
  return "{}:{:>02}:{:>05.2f}".format(h, m, s)

 

Bootstrapping for Regression

 

회귀 부트스트래핑은 ShuffleSplit 개체를 사용하여 분할을 수행한다. 이 기법은 교차 검증을 위한 KFold와 유사하며 밸런싱이 수행되지 않는다.

 

import pandas as pd
import os
import numpy as np
import time
import statistics
from sklearn import metrics
from sklearn.model_selection import StratifiedKFold
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation
from tensorflow.keras import regularizers
from tensorflow.keras.callbacks import EarlyStopping
from sklearn.model_selection import ShuffleSplit

EPOCHS = 500
SPLITS = 50

# Bootstrap
boot = ShuffleSplit(n_splits = SPLITS, test_size =0.1, random_state=42)

# Track progress
mean_benchmark = []
epochs_needed = []
num = 0

fold = 0
for train, test in boot.split(x):
  start_time = time.time()
  num += 1
  
  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_train.shape[1], activation = 'relu'))
  model.add(Dense(10, activation = 'relu'))
  model.add(Dense(1))
  model.compile (loss = 'mean_squared_error', optimizer= 'adam')
  monitor = EarlyStopping(monitor= 'val_loss', min_delta = 1e−3,
                          patience = 5, verbose = 0, mode = 'auto', restore_best_weights = True)
  
  model.fit(x_train, y_train, validation_data = (x_test, y_test), callbacks = [monitor], verbose =0, epochs = 1000)
  epochs = monitor.stopped_epoch
  epochs_needed.append(epochs)
  
  pred = model.predict(x_test)
  score = np.sqrt(metrics.mean_squared_error(pred, y_test))
  mean_benchmark.append(score)
  m1 = statistics.mean(mean_benchmark)
  m2 = statistics.mean(epochs_needed)
  mdev = statistics.pstdev(mean_benchmark)
  
  # Record this iteration
  time_took = time.time() − start_time
  print(f"#{num} : score = {score : .6f}, mean score = {m1:.6f}",
        f"stdev = {mdev : .6f}",
        f"epochs = {epochs}, mean epochs = {int(m2)}",
        f"time = {hms_string(time_took)}")
728x90
반응형
LIST