머신러닝

머신러닝 심화 (2) : 데이터 분리

selenaass 2025. 1. 17. 23:30

1. 데이터 분리

 

과대적합(Overfitting): 데이터를 너무 과도하게 학습한 나머지 해당 문제만 잘 맞추고 새로운 현상은 잘 맞추지 못하는 경우

  • 과소 적합: 모형이 지나치게 단순할 때 
  • 과대 적합: 모형이 지나치게 복잡할 때

  • 학습 데이터(Train Data): 모델을 학습(fit)하기 위한 데이터
  • 테스트 데이터(Test Data): 모델을 평가 하기 위한 데이터
  • 함수 및 파라미터 설명

 sklearn.model_selection.train_test_split

  • 파라미터
    • test_size: 테스트 데이터 세트 크기
    • train_size: 학습 데이터 세트 크기
    • shuffle: 데이터 분리 시 섞기
    • random_state: 호출할 때마다 동일한 학습/테스트 데이터를 생성하기 위한 난수 값. 수행할 때 마다 동일한 데이터 세트로 분리하기 위해 숫자를 고정 시켜야 함 → 코드를 실행할 때마다 값이 변경된다. 
  • 반환 값(순서 중요)
    • X_train, X_test, y_train, y_test
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(titanic_train[['Fare', 'Sex']], titanic_train[['Survived']],
                                                    test_size= 0.3,
                                                    shuffle= True, random_state = 42)

print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)

# 원자료 891개 Y값의 분포
sns.countplot(titanic_train, x = 'Survived')

 

 


 

stratify: 현재의 상태를 보존하면서 추출해주는 매소드

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(titanic_train[['Fare', 'Sex']], titanic_train[['Survived']],
                                                    test_size= 0.3,
                                                    shuffle= True, random_state = 42, stratify=titanic_train[['Survived']])