딥러닝

딥러닝(6) validation split

개발연습자1 2022. 12. 29. 11:54

validation은 딥러닝을 할때 새로운 데이터로 얼마나 예측하는지 알아보는 방법이다.

 

코드를 통해 어떻게 쓰이는지 알아보자

 

데이터는 지난시간까지 블로그를 읽어봤다면 알수 있으니 생략하고 중요한 부분 부터 나간다.

 

먼저 딥러닝할 모델을 모델링한다.

# 딥러닝 모델링

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

def build_model():
  #모델링
  model =Sequential()
  model.add ( Dense(units=64, activation= 'relu',input_shape=(9,) ) )
  model.add ( Dense(units=64, activation= 'relu'))
  model.add ( Dense(units=1, activation= 'linear'))
  model.compile(optimizer= tf.keras.optimizers.Adam(learning_rate=0.001),loss='mse',metrics=['mse','mae'])
  return model
  
  from tensorflow.keras.optimizers import Adam
  
  model = build_model()

 

데이터를 학습할시 validation_split 파라미터를 추가해 X_train,y_train데이터의 일부를 새로운 데이터로 쓴다.

#X_train,y_train데이터를 나눠서 validation_split 20%로 추가
epoch_history=model.fit(X_train,y_train,epochs = 200,validation_split=0.2)

 

학습시킨 데이터의 epoch와 validation의 그래프를 한번에 볼수 있게 함수를 만든다.

import matplotlib.pyplot as plt
def plot_history(history) :
  hist = pd.DataFrame(history.history)
  hist['epoch'] = history.epoch

  plt.figure(figsize = (8, 12))

  plt.subplot(2, 1, 1)
  plt.xlabel('Eopoch')
  plt.ylabel('Mean Abs Error [MPG]')
  plt.plot(hist['epoch'], hist['mae'], label = 'Train Error')
  plt.plot(hist['epoch'], hist['val_mae'], label = 'Val Error')
  plt.ylim([0,5])
  plt.legend()

  plt.subplot(2, 1, 2)
  plt.xlabel('Eopoch')
  plt.ylabel('Mean Squared Error [MPG]')
  plt.plot(hist['epoch'], hist['mse'], label = 'Train Error')
  plt.plot(hist['epoch'], hist['val_mse'], label = 'Val Error')
  plt.ylim([0,20])
  plt.legend()
  plt.show()

파란선이 epoch의 history 주황선이 validation의 history이다. 끝에서 둘다 오차가 흔들리지만 서로 잘 맞는걸 알 수 있다.

반응형