GridSearchCV 를 이용한 모델 하이퍼파라미터 최적화

Beginner

This tutorial is from open-source community. Access the source code

소개

이 튜토리얼에서는 Scikit-Learn 의 GridSearchCV 함수에 대해 배웁니다. GridSearchCV 는 주어진 모델에 대한 최상의 하이퍼파라미터를 검색하는 함수입니다. 추정기의 지정된 파라미터 값에 대한 철저한 검색 (exhaustive search) 을 수행합니다. 이러한 방법을 적용하는 데 사용되는 추정기의 파라미터는 파라미터 그리드에 대한 교차 검증 그리드 검색 (cross-validated grid-search) 을 통해 최적화됩니다.

VM 팁

VM 시작이 완료되면 왼쪽 상단 모서리를 클릭하여 Notebook 탭으로 전환하여 연습을 위한 Jupyter Notebook에 접근합니다.

때때로 Jupyter Notebook 이 완전히 로드되기까지 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한으로 인해 작업의 유효성 검사를 자동화할 수 없습니다.

학습 중 문제가 발생하면 Labby 에 문의하십시오. 세션 후 피드백을 제공하면 문제를 신속하게 해결해 드리겠습니다.

라이브러리 가져오기

필요한 라이브러리를 가져오는 것으로 시작해 보겠습니다.

import numpy as np
from matplotlib import pyplot as plt

from sklearn.datasets import make_hastie_10_2
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import make_scorer
from sklearn.metrics import accuracy_score
from sklearn.tree import DecisionTreeClassifier

데이터셋 로드

이 단계에서는 Scikit-Learn 의 make_hastie_10_2 함수를 사용하여 데이터셋을 로드합니다. 이 함수는 이진 분류를 위한 합성 데이터셋을 생성합니다.

X, y = make_hastie_10_2(n_samples=8000, random_state=42)

하이퍼파라미터 및 평가 지표 정의

이 단계에서는 DecisionTreeClassifier 모델의 하이퍼파라미터와 사용할 평가 지표를 정의합니다. AUC (곡선 아래 면적) 및 정확도 지표를 사용할 것입니다.

scoring = {"AUC": "roc_auc", "Accuracy": make_scorer(accuracy_score)}

그리드 검색 수행

이 단계에서는 GridSearchCV 함수를 사용하여 그리드 검색을 수행합니다. DecisionTreeClassifier 모델의 min_samples_split 매개변수에 대한 최적의 하이퍼파라미터를 찾을 것입니다.

gs = GridSearchCV(
    DecisionTreeClassifier(random_state=42),
    param_grid={"min_samples_split": range(2, 403, 20)},
    scoring=scoring,
    refit="AUC",
    n_jobs=2,
    return_train_score=True,
)
gs.fit(X, y)
results = gs.cv_results_

결과 시각화

이 단계에서는 그리드 검색 결과를 플롯을 사용하여 시각화합니다. 학습 데이터 세트와 테스트 데이터 세트의 AUC 및 정확도 점수를 플롯할 것입니다.

plt.figure(figsize=(13, 13))
plt.title("GridSearchCV evaluating using multiple scorers simultaneously", fontsize=16)

plt.xlabel("min_samples_split")
plt.ylabel("Score")

ax = plt.gca()
ax.set_xlim(0, 402)
ax.set_ylim(0.73, 1)

## Get the regular numpy array from the MaskedArray
X_axis = np.array(results["param_min_samples_split"].data, dtype=float)

for scorer, color in zip(sorted(scoring), ["g", "k"]):
    for sample, style in (("train", "--"), ("test", "-")):
        sample_score_mean = results["mean_%s_%s" % (sample, scorer)]
        sample_score_std = results["std_%s_%s" % (sample, scorer)]
        ax.fill_between(
            X_axis,
            sample_score_mean - sample_score_std,
            sample_score_mean + sample_score_std,
            alpha=0.1 if sample == "test" else 0,
            color=color,
        )
        ax.plot(
            X_axis,
            sample_score_mean,
            style,
            color=color,
            alpha=1 if sample == "test" else 0.7,
            label="%s (%s)" % (scorer, sample),
        )

    best_index = np.nonzero(results["rank_test_%s" % scorer] == 1)[0][0]
    best_score = results["mean_test_%s" % scorer][best_index]

    ## Plot a dotted vertical line at the best score for that scorer marked by x
    ax.plot(
        [
            X_axis[best_index],
        ]
        * 2,
        [0, best_score],
        linestyle="-.",
        color=color,
        marker="x",
        markeredgewidth=3,
        ms=8,
    )

    ## Annotate the best score for that scorer
    ax.annotate("%0.2f" % best_score, (X_axis[best_index], best_score + 0.005))

plt.legend(loc="best")
plt.grid(False)
plt.show()

요약

이 튜토리얼에서는 Scikit-Learn 의 GridSearchCV 함수에 대해 배웠습니다. 데이터셋을 로드하고, 하이퍼파라미터와 평가 지표를 정의하고, 그리드 검색을 수행하며, 플롯을 사용하여 결과를 시각화하는 방법을 살펴보았습니다. GridSearchCV 는 주어진 모델에 대한 최적의 하이퍼파라미터를 찾을 때 사용하는 중요한 함수입니다.