부트캠프/구름ICT AI

태태개발일지 - 구름톤 머신러닝

태태코 2025. 7. 2. 17:34
반응형

 

효율적인 AI Code

 

기존 데이터를 처리할 때 train 과 test를 분리하지 않아서 과적합이 일어나는 상황을 볼 수 있었다.

 

1. 과적합(Overfitting)이란?


과적합이란, 모델이 학습 데이터에 너무 맞춰져서 새로운 데이터(테스트 데이터)에서는 성능이 떨어지는 현상이다. 즉, 학습 데이터만 잘 맞추고 실제로는 예측을 잘 못하는 모델이 된다.

 


2. 데이터 분할의 중요성


이 문제를 방지하려면 데이터를 **train set(학습용)**과 **test set(테스트용)**으로 나누는 게 필수다. 일반적으로 8:2(80%:20%) 비율로 많이 나눈다.

 

from sklearn.model_selection import train_test_split

# X: feature 데이터, y: 라벨 데이터라고 가정
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

 

3. Validation Set의 활용


여기서 한 단계 더 나아가, validation set을 따로 두면 모델의 성능을 더 정확하게 평가할 수 있다.
즉, train/validation/test 세트로 나눈다.

 

from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint

early_stop = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)
model_ckpt = ModelCheckpoint('best_model.h5', monitor='val_loss', save_best_only=True)

history = model.fit(
    X_train, y_train,
    validation_data=(X_val, y_val),
    epochs=100,
    callbacks=[early_stop, model_ckpt]
)

 

 

4. 얼리스타핑(Early Stopping)과 모델 저장


모델을 반복적으로 학습시키다 보면, validation loss가 더 이상 줄어들지 않거나 오히려 증가하는 시점이 온다.
이때, Early Stopping을 사용하면 불필요한 학습을 막고, 가장 성능이 좋았던 모델을 저장할 수 있다.

from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint

early_stop = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)
model_ckpt = ModelCheckpoint('best_model.h5', monitor='val_loss', save_best_only=True)

history = model.fit(
    X_train, y_train,
    validation_data=(X_val, y_val),
    epochs=100,
    callbacks=[early_stop, model_ckpt]
)

 

 

5. 원-핫 인코딩(One-Hot Encoding)


마지막으로, 컬럼이 영어/한글 등 문자로 되어 있을 때 머신러닝 모델은 이를 바로 인식하지 못한다.
그래서 원-핫 인코딩을 통해 숫자형 데이터로 변환해줘야 한다.

 

import pandas as pd

# 예시 데이터프레임
df = pd.DataFrame({
    'color': ['red', 'blue', 'green', 'blue', 'red']
})

# 원-핫 인코딩
df_encoded = pd.get_dummies(df, columns=['color'])
print(df_encoded)

 

 

   color_blue  color_green  color_red
0           0            0          1
1           1            0          0
2           0            1          0
3           1            0          0
4           0            0          1

 

 

마무리


데이터를 반드시 train/validation/test로 분할!

Early Stopping과 Model Checkpoint로 과적합 방지!

문자형 컬럼은 원-핫 인코딩으로 숫자로 변환!
반응형