Gradient Boosting 회귀 분석

Beginner

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

소개

이 실습에서는 경사 부스팅 (Gradient Boosting) 을 사용하여 당뇨병 회귀 예측 모델을 구축합니다. diabetes 데이터셋으로 모델을 학습하고 sklearn.ensemble.GradientBoostingRegressor를 사용하여 최소 제곱 손실 (least squares loss) 과 깊이 4 의 500 개 회귀 트리로 결과를 얻습니다.

VM 팁

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

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

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

데이터 로드

먼저, 당뇨병 데이터셋을 로드합니다.

diabetes = datasets.load_diabetes()
X, y = diabetes.data, diabetes.target

데이터 전처리

다음으로, 데이터셋을 훈련에 90% 를 사용하고 나머지를 테스트에 사용하도록 분할합니다. 또한 회귀 모델의 매개변수를 설정합니다.

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=13)

params = {
    "n_estimators": 500,
    "max_depth": 4,
    "min_samples_split": 5,
    "learning_rate": 0.01,
    "loss": "squared_error",
}

회귀 모델 학습

이제 그래디언트 부스팅 회귀 모델을 초기화하고 훈련 데이터로 학습시킵니다. 또한 테스트 데이터의 평균 제곱 오차를 확인해 보겠습니다.

reg = ensemble.GradientBoostingRegressor(**params)
reg.fit(X_train, y_train)

mse = mean_squared_error(y_test, reg.predict(X_test))
print("테스트 데이터의 평균 제곱 오차 (MSE): {:.4f}".format(mse))

학습 편차 시각화

마지막으로, 결과를 시각화합니다. 이를 위해 먼저 테스트 세트의 편차를 계산한 다음, 부스팅 반복 횟수에 따른 편차를 플롯합니다.

test_score = np.zeros((params["n_estimators"],), dtype=np.float64)
for i, y_pred in enumerate(reg.staged_predict(X_test)):
    test_score[i] = mean_squared_error(y_test, y_pred)

fig = plt.figure(figsize=(6, 6))
plt.subplot(1, 1, 1)
plt.title("편차")
plt.plot(
    np.arange(params["n_estimators"]) + 1,
    reg.train_score_,
    "b-",
    label="훈련 세트 편차",
)
plt.plot(
    np.arange(params["n_estimators"]) + 1, test_score, "r-", label="테스트 세트 편차"
)
plt.legend(loc="upper right")
plt.xlabel("부스팅 반복 횟수")
plt.ylabel("편차")
fig.tight_layout()
plt.show()

특성 중요도 시각화

이 예제에서는 불순도 기반 특성 중요도를 사용하여 가장 예측력이 높은 특성을 식별합니다.

feature_importance = reg.feature_importances_
sorted_idx = np.argsort(feature_importance)
pos = np.arange(sorted_idx.shape[0]) + 0.5
fig = plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.barh(pos, feature_importance[sorted_idx], align="center")
plt.yticks(pos, np.array(diabetes.feature_names)[sorted_idx])
plt.title("특성 중요도 (MDI)")

변수 중요도 (Permutation) 시각화

변수의 예측력을 평가하기 위해 순열 방법을 사용합니다.

result = permutation_importance(
    reg, X_test, y_test, n_repeats=10, random_state=42, n_jobs=2
)
sorted_idx = result.importances_mean.argsort()
plt.subplot(1, 2, 2)
plt.boxplot(
    result.importances[sorted_idx].T,
    vert=False,
    labels=np.array(diabetes.feature_names)[sorted_idx],
)
plt.title("순열 중요도 (테스트 세트)")
fig.tight_layout()
plt.show()

요약

이 실습에서는 Gradient Boosting 을 사용하여 당뇨병 회귀 예측 모델을 구축했습니다. 데이터를 로드하고 전처리한 후 회귀 모델을 학습시키고, 학습 편차, 특성 중요도, 순열 중요도를 시각화하여 결과를 확인했습니다.