본문 바로가기

Study/Introduction to ML with python - 한빛

[Book] 5. 모델 평가와 성능 향상 - (2)

Book Title : Introduction to Machine Learning with Python

- 파이썬 라이브러리를 활용한 머신러닝 -

지은이 : 안드레아스 뮐러, 세라 가이도
옮긴이 : 박해선
출판사 : 한빛미디어

 

코드 출처

https://github.com/rickiepark/introduction_to_ml_with_python

 

GitHub - rickiepark/introduction_to_ml_with_python: 도서 "[개정판] 파이썬 라이브러리를 활용한 머신 러닝"의

도서 "[개정판] 파이썬 라이브러리를 활용한 머신 러닝"의 주피터 노트북과 코드입니다. Contribute to rickiepark/introduction_to_ml_with_python development by creating an account on GitHub.

github.com


5.2 그리드 서치

  • -모델에서 중요한 매개변수의 값을 찾는 일은 어려운 작업이지만, 모든 모델과 데이터셋에서 해야 하는 필수적인 일
  • 가장 널리 사용하는 방법은 그리드 서치(grid search)로서 관심 있는 매개 변수들을 대상으로 가능한 모든 조합을 시도해보는 것

5.2.1 GridSearchCV

  • 딕셔너리 형태로 검색 대상 매개변수를 지정해야 함
param_grid = {
    "C" : [0.001, 0.01, 0.1, 1, 10, 100],
    "gamma" : [0.001, 0.01, 0.1, 1, 10, 100]
}

from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVC
from sklearn.datasets import load_iris
grid_search = GridSearchCV(SVC(), param_grid, cv = 5, return_train_score= True)

iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, random_state = 0)
  • grid_search 객체는 분류기와 비슷해서 fit, predict, score 메서드 제공
  • 하지만 fit 메서드 호출하면 param_grid에 설정된 매개변수 조합에 대한 교차 검증 수행
  • fit 메서드는 최적의 매개변수를 찾는 일뿐만 아니라, 교차 검증 성능이 가장 좋은 매개변수로 전체 훈련 데이터셋에 대해 새로운 모델 자동 생성
grid_search.fit(X_train, y_train)

print("테스트 점수", grid_search.score(X_test, y_test))
테스트 점수 0.9736842105263158


print("최적 매개변수", grid_search.best_params_)
최적 매개변수 {'C': 10, 'gamma': 0.1}

print("최고 교차 검증 점수", grid_search.best_score_)
최고 교차 검증 점수 0.9731225296442687

print("최고 성능 모델", grid_search.best_estimator_)
최고 성능 모델 SVC(C=10, gamma=0.1)

 

  • grid_search 객체가 predict와 score 메서드를 가지고 있어서 예측이나 모델 평가를 위해 best_estimator을 사용할 필요는 없음