0Pricing
Machine Learning Academy · 강의

핵심 하이퍼파라미터: 학습률, n_estimators, max_depth

체계적인 실험을 통해 축소율(학습률), 앙상블 크기, 깊이가 편향-분산 상충 관계에 미치는 영향을 추적합니다.

핵심 하이퍼파라미터: 학습률, n_estimators, max_depth은(는) CoddyKit의 무료 Machine Learning Academy 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Machine Learning Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Machine Learning Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

The Holy Trinity of Gradient Boosting

Gradient boosting has three hyperparameters that interact most strongly and have the biggest impact on model performance: learning_rate (how large each tree's contribution is), n_estimators (how many trees to build), and max_depth (how complex each individual tree can be). Understanding how these three interact is the key to effectively tuning any gradient boosting model — whether scikit-learn's GradientBoostingClassifier, XGBoost, or LightGBM.

Learning Rate (Shrinkage) in Depth

The learning rate η (eta) scales each tree's contribution: F_m(x) = F_{m-1}(x) + η × h_m(x). A smaller η means each tree corrects only a fraction of the residual, requiring more trees to converge but producing a smoother, more regularised prediction surface. Typical values: 0.01-0.3. The inverse relationship between learning_rate and n_estimators is crucial: halving the learning rate requires roughly doubling n_estimators to reach the same training loss. Always use early stopping to find the right n_estimators for your chosen learning rate.

from sklearn.ensemble import GradientBoostingClassifier
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score

X, y = load_breast_cancer(return_X_y=True)
# Inverse relationship between lr and n_estimators
configs = [(0.3, 50), (0.1, 150), (0.05, 300), (0.01, 1000)]
for lr, n in configs:
    model = GradientBoostingClassifier(learning_rate=lr, n_estimators=n, max_depth=3, random_state=42)
    score = cross_val_score(model, X, y, cv=5).mean()
    print(f'lr={lr:.2f}, n={n:4d}: CV={score:.4f}')

n_estimators: More Trees, Not Always Better

n_estimators sets the total number of sequential trees in the ensemble. Unlike random forests (where more is always better), boosting models can overfit with too many trees, especially at high learning rates. The sweet spot is found by monitoring validation loss across rounds. With early stopping, you can safely set n_estimators=2000 — training will stop when validation stops improving. Without early stopping, use cross-validation on a range of values and pick the n_estimators at the elbow of the validation error curve.

from sklearn.ensemble import GradientBoostingClassifier
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score

X, y = load_breast_cancer(return_X_y=True)
for n in [10, 50, 100, 200, 500]:
    model = GradientBoostingClassifier(n_estimators=n, learning_rate=0.1, max_depth=3, random_state=42)
    score = cross_val_score(model, X, y, cv=5).mean()
    print(f'n_estimators={n:4d}: CV accuracy={score:.4f}')

max_depth: Weak Learners Win in Boosting

Gradient boosting works best with weak learners — shallow trees (max_depth 2-6). A depth-1 tree (decision stump) captures only one feature interaction per round; a depth-3 tree captures three-way interactions. Deeper trees are more powerful individually, requiring fewer rounds but risking overfitting. Shallower trees need more rounds but generalise better. In practice: start with max_depth=3 for classification, max_depth=4-6 for complex tabular regression. Very deep trees (>8) are almost never optimal in boosting.

from sklearn.ensemble import GradientBoostingClassifier
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score

X, y = load_breast_cancer(return_X_y=True)
for depth in [1, 2, 3, 5, 8, 15]:
    model = GradientBoostingClassifier(n_estimators=200, learning_rate=0.1, max_depth=depth, random_state=42)
    train_score = model.fit(X, y).train_score_[-1]
    cv_score = cross_val_score(GradientBoostingClassifier(n_estimators=200, learning_rate=0.1, max_depth=depth, random_state=42), X, y, cv=5).mean()
    print(f'max_depth={depth:2d}: train={train_score:.4f}, CV={cv_score:.4f}')

The Learning Rate - n_estimators Trade-Off

The interaction between learning_rate and n_estimators is the most important trade-off to understand. Consider these scenarios:

  • High lr (0.3) + few trees (50): fast training, but risks missing the optimal fit
  • Medium lr (0.1) + medium trees (200): the standard starting point
  • Low lr (0.01) + many trees (2000): most regularised, best generalisation but slow to train
The practical recommendation: set a low-to-medium learning rate (0.05-0.1) and use early stopping to automatically determine the optimal n_estimators.

Training vs Validation Loss Curves

One of the most informative diagnostics in gradient boosting is plotting training and validation loss across boosting rounds. Training loss always decreases monotonically. Validation loss decreases initially but starts to rise when the model overfits. The point where validation loss is minimised is the optimal n_estimators. This plot reveals whether you need more regularisation (validation loss rises quickly), less regularisation (validation loss still decreasing at the end), or whether you have found the sweet spot.

from sklearn.ensemble import GradientBoostingClassifier
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
import numpy as np

X, y = load_breast_cancer(return_X_y=True)
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)

model = GradientBoostingClassifier(n_estimators=300, learning_rate=0.1, max_depth=3, random_state=42)
model.fit(X_train, y_train)
val_scores = [model.estimators_[:i+1] and model.loss_(y_val, model.staged_predict_proba(X_val).__next__()) for i in range(5)]
# Simplified: use staged_predict to check improvement
val_staged = list(model.staged_predict(X_val))
val_acc = [np.mean(p == y_val) for p in val_staged]
print('Val acc at round 50:', round(val_acc[49], 4))
print('Val acc at round 300:', round(val_acc[299], 4))
print('Best round:', np.argmax(val_acc) + 1)

Regularisation Beyond the Three Parameters

Beyond learning_rate, n_estimators, and max_depth, gradient boosting offers additional regularisation: min_samples_leaf (minimum examples per leaf, prevents overfitting on tiny leaf groups), subsample (stochastic training, reduces variance), max_features (feature subsampling per split, reduces correlation), min_impurity_decrease (only split if the gain exceeds a threshold). These secondary parameters typically matter less than the primary three but can make a meaningful difference on noisy datasets.

Systematic Hyperparameter Search Strategy

A practical 3-step strategy for gradient boosting tuning: (1) Fix learning_rate=0.1, set n_estimators=1000 with early stopping — find optimal number of rounds; (2) Grid search max_depth (try 3, 4, 5, 6) and min_samples_leaf (try 1, 5, 10) with the tree count from step 1; (3) Lower the learning rate to 0.05 or 0.01 and scale n_estimators accordingly to potentially squeeze out more performance. This avoids the curse of dimensionality from searching all parameters simultaneously.

subsample as a Stochastic Regulariser

Setting subsample < 1.0 (e.g., 0.8) in gradient boosting means each tree is trained on a random 80% of the training data (without replacement). This is called stochastic gradient boosting. The stochastic element introduces diversity among trees (similar to dropout in neural networks) and often improves validation performance by 0.5-2%. A typical value is 0.8. If you reduce it further (0.5), you may need more trees to compensate for the higher variance per tree.

from sklearn.ensemble import GradientBoostingClassifier
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score

X, y = load_breast_cancer(return_X_y=True)
for ss in [1.0, 0.8, 0.6, 0.5]:
    model = GradientBoostingClassifier(n_estimators=200, learning_rate=0.1, max_depth=3,
                                        subsample=ss, random_state=42)
    score = cross_val_score(model, X, y, cv=5).mean()
    print(f'subsample={ss}: CV accuracy={score:.4f}')

Balancing Training Time and Performance

In production, training time is a real constraint. Larger n_estimators and more CV folds multiply linearly. Practical shortcuts: (1) use n_jobs=-1 for cross-validation parallelism; (2) use LightGBM or XGBoost instead of sklearn's GradientBoosting for 5-10x speed gains; (3) use RandomizedSearchCV with 30-50 iterations instead of full grid search; (4) use early stopping within cross-validation folds to automatically set n_estimators. The combination of early stopping + LightGBM + RandomizedSearchCV dramatically reduces tuning time without sacrificing accuracy.

Gradient Boosting Default Hyperparameters

Good default starting points for gradient boosting hyperparameters: learning_rate=0.1, n_estimators=200 (with early stopping on hold-out), max_depth=3 for classification or 4-5 for regression, subsample=0.8 for stochastic regularisation, and min_samples_leaf=5-10 to prevent over-splitting on small groups. These defaults work surprisingly well across many datasets and should be your starting point before any tuning. Only tune if the baseline performance is insufficient for your use case.

from sklearn.ensemble import GradientBoostingClassifier
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score

X, y = load_breast_cancer(return_X_y=True)
# Good defaults — try these before tuning
default_gb = GradientBoostingClassifier(
    learning_rate=0.1, n_estimators=200, max_depth=3,
    subsample=0.8, min_samples_leaf=5, random_state=42
)
scores = cross_val_score(default_gb, X, y, cv=5)
print('Default GBM CV:', scores.mean().round(4), '+/-', scores.std().round(4))

Quick Check

Test your understanding of gradient boosting hyperparameters from this lesson.

Lesson Recap

In this lesson you learned: learning rate and n_estimators have an inverse relationship — lower lr requires more trees, shallow trees (max_depth 2-5) are preferable in boosting because they act as weak learners, and subsample and min_samples_leaf provide additional regularisation beyond the primary three parameters. Next up we explore K-Fold Cross-Validation and how to evaluate models without leaking test data.

자주 묻는 질문

“핵심 하이퍼파라미터: 학습률, n_estimators, max_depth” 강의는 무료인가요?

네 — “핵심 하이퍼파라미터: 학습률, n_estimators, max_depth” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Machine Learning Academy 강의 전체를 잠금 해제할 수 있습니다. Machine Learning Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“핵심 하이퍼파라미터: 학습률, n_estimators, max_depth”에서 뭘 배우나요?

체계적인 실험을 통해 축소율(학습률), 앙상블 크기, 깊이가 편향-분산 상충 관계에 미치는 영향을 추적합니다. 브라우저에서 직접 실행하는 실습 코드로 Machine Learning Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Machine Learning Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Machine Learning Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.

“핵심 하이퍼파라미터: 학습률, n_estimators, max_depth” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Machine Learning Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Machine Learning Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 부스팅 직관: 순차적 오차 보정
  2. XGBoost: 정규화, 조기 중단, 특성 중요도
  3. LightGBM: 잎 기준 성장과 속도상의 이점
  4. 핵심 하이퍼파라미터: 학습률, n_estimators, max_depth
← Machine Learning Academy(으)로 돌아가기