0Pricing
Machine Learning Academy · Lekcja

Intuicja stojąca za boostingiem: sekwencyjna korekta błędów

Zasymuluj ręcznie trzy rundy gradient boosting na niewielkim zbiorze danych, dopasowując każde nowe drzewo do reszt zespołu utworzonego do tej pory.

Intuicja stojąca za boostingiem: sekwencyjna korekta błędów to bezpłatna lekcja Machine Learning Academy na CoddyKit. To lekcja 1 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Machine Learning Academy, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Machine Learning Academy zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

Boosting vs Bagging: A Key Distinction

Bagging trains many models in parallel on random subsets of data and combines them, reducing variance. Boosting trains models sequentially: each new model focuses on correcting the mistakes made by the previous ensemble. While bagging reduces variance, boosting primarily reduces bias — it can turn many weak, underfitting models into a powerful learner. This sequential error-correction strategy is the foundation of gradient boosting, AdaBoost, and XGBoost.

The Idea of Sequential Error Correction

Imagine you are predicting house prices. Your first model predicts everything around the mean and makes large errors. Instead of discarding it, you train a second model specifically on the residuals (the errors: actual − predicted) of the first model. The second model learns the patterns the first missed. A third model then corrects what the second still got wrong. Each new model makes a small improvement on the accumulated ensemble's current error. The final prediction is the sum of all models' predictions.

Boosting by Hand: Three Rounds

Consider a tiny regression dataset with 5 examples. Start with a model that predicts the mean. Compute residuals. Train a tree on residuals. Add a fraction of its predictions (the learning rate) to the current ensemble. Compute new residuals. Repeat. Each round, the residuals should shrink if the trees capture some pattern. After enough rounds, the residuals approach zero for the training set. This is the exact algorithm gradient boosting implements for regression with mean squared error loss.

import numpy as np
# Tiny example: manual 3-round gradient boosting for regression
y = np.array([3.0, 5.0, 2.0, 8.0, 1.0])
pred = np.full(5, y.mean())  # Round 0: predict the mean
print('Round 0 pred:', pred, 'Residuals:', y - pred)
# Round 1: suppose our tree predicts half the residual
residuals_1 = y - pred
pred += 0.5 * residuals_1  # learning_rate=0.5
print('Round 1 pred:', pred, 'Residuals:', np.round(y - pred, 2))
# Round 2
residuals_2 = y - pred
pred += 0.5 * residuals_2
print('Round 2 pred:', np.round(pred, 2), 'Residuals:', np.round(y - pred, 3))

The Learning Rate (Shrinkage)

The learning rate (often called shrinkage) scales down each tree's contribution before adding it to the ensemble. Instead of fully correcting the residual in one step (learning rate = 1.0), boosting takes a small step (e.g., 0.1) and lets subsequent trees correct what remains. A smaller learning rate requires more trees to achieve the same fit but generalises better because no single tree dominates. The trade-off: very small learning rates need very large n_estimators, increasing training time.

Gradient Descent in Function Space

Gradient boosting is named after the connection to gradient descent. In standard gradient descent, we update parameters by moving in the direction that reduces the loss. In gradient boosting, we update the prediction function by fitting a new tree to the negative gradient of the loss with respect to the current predictions. For mean squared error loss, the negative gradient is simply the residual (actual − predicted). For other losses (log-loss, absolute error), it computes the appropriate pseudo-residuals.

GradientBoostingClassifier in scikit-learn

scikit-learn provides GradientBoostingClassifier which implements the original Friedman gradient boosting algorithm. Key parameters: n_estimators (number of trees), learning_rate (shrinkage), max_depth (depth of each tree — shallow trees are preferred, typically 3-5), and subsample (fraction of training data for each tree, adding stochastic element that improves generalisation). The combination of small learning rate, many shallow trees, and subsampling is the standard recipe.

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)
gb = GradientBoostingClassifier(
    n_estimators=200,
    learning_rate=0.1,
    max_depth=3,
    subsample=0.8,
    random_state=42
)
scores = cross_val_score(gb, X, y, cv=5)
print('GradientBoosting CV:', round(scores.mean(), 4))

Overfitting in Boosting

Unlike bagging, boosting can overfit with enough estimators, especially at a high learning rate. As you add more rounds, the training loss keeps decreasing but the validation loss eventually rises. The solution is: (1) use early stopping — monitor validation loss and stop when it stops improving; (2) use a small learning rate (0.01-0.1) with many trees rather than a large rate with few; (3) regularise individual trees with shallow depth and minimum samples per leaf. These techniques are all exposed in XGBoost and LightGBM's rich hyperparameter sets.

AdaBoost: The Original Boosting Algorithm

AdaBoost (Adaptive Boosting) was the first practical boosting algorithm. Instead of fitting trees on residuals, it assigns sample weights: misclassified examples get higher weight in the next round, so subsequent trees focus on the hard cases. Each tree's contribution to the final vote is also weighted by its accuracy — better trees get more say. AdaBoost is implemented in scikit-learn as AdaBoostClassifier and is historically important, but gradient boosting (and XGBoost) has largely superseded it in practice.

from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score

X, y = load_breast_cancer(return_X_y=True)
ada = AdaBoostClassifier(
    estimator=DecisionTreeClassifier(max_depth=1),  # stumps
    n_estimators=200,
    learning_rate=0.5,
    random_state=42
)
print('AdaBoost CV:', round(cross_val_score(ada, X, y, cv=5).mean(), 4))

Stochastic Gradient Boosting

Setting subsample < 1.0 in gradient boosting introduces randomness: each tree is trained on a random subset of the training data (without replacement). This stochastic element reduces correlation between trees and often improves generalisation — much like the dropout idea in neural networks. A typical value is subsample=0.8. When subsample is less than 1, scikit-learn also computes an out-of-bag estimate of the improvement at each round, accessible via oob_improvement_.

When Boosting Beats Random Forest

Boosting typically outperforms random forests on clean tabular data where the signal-to-noise ratio is high and there are complex feature interactions. The sequential error-correction mechanism lets boosting squeeze out almost all predictable signal. However, boosting is more sensitive to noisy data and outliers — since each round focuses on hard examples, noise can pull the model in wrong directions. Random forests are more robust to label noise. For noisy, messy real-world data, the choice depends on the specific dataset.

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

X, y = load_breast_cancer(return_X_y=True)
gb = GradientBoostingClassifier(n_estimators=200, learning_rate=0.1, max_depth=3, random_state=42)
rf = RandomForestClassifier(n_estimators=200, random_state=42)
print('Gradient Boosting:', round(cross_val_score(gb, X, y, cv=5).mean(), 4))
print('Random Forest:    ', round(cross_val_score(rf, X, y, cv=5).mean(), 4))

Boosting for Regression Tasks

Gradient boosting is equally powerful for regression. GradientBoostingRegressor minimises a regression loss by default (squared error), but also supports absolute error (loss='absolute_error', robust to outliers) and Huber loss (loss='huber', combining squared for small errors and absolute for large ones). For house price prediction, energy forecasting, and similar tasks, gradient boosting consistently outperforms linear regression and often matches or beats neural networks on tabular data without the need for GPU hardware.

from sklearn.ensemble import GradientBoostingRegressor
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import cross_val_score
import numpy as np

X, y = fetch_california_housing(return_X_y=True)
gbr = GradientBoostingRegressor(n_estimators=200, learning_rate=0.1, max_depth=4,
                                  subsample=0.8, random_state=42)
rmse = np.sqrt(-cross_val_score(gbr, X, y, scoring='neg_mean_squared_error', cv=3).mean())
print('GBR Regression RMSE:', round(rmse, 4))

Quick Check

Test your understanding of Boosting and Sequential Error Correction from this lesson.

Lesson Recap

In this lesson you learned: boosting trains models sequentially, each correcting the residual errors of the previous ensemble, the learning rate scales each tree's contribution and controls overfitting, and gradient boosting minimises a differentiable loss by fitting trees to the negative gradient. Next up we explore XGBoost's regularisation and early stopping features.

Często zadawane pytania

Czy lekcja „Intuicja stojąca za boostingiem: sekwencyjna korekta błędów” jest bezpłatna?

Tak — pełny tekst „Intuicja stojąca za boostingiem: sekwencyjna korekta błędów” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Machine Learning Academy, przejdź na CoddyKit PRO. Kurs Machine Learning Academy zawiera 4 lekcji w sumie.

Co nauczysz się w „Intuicja stojąca za boostingiem: sekwencyjna korekta błędów”?

Zasymuluj ręcznie trzy rundy gradient boosting na niewielkim zbiorze danych, dopasowując każde nowe drzewo do reszt zespołu utworzonego do tej pory. Ćwiczysz Machine Learning Academy z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Machine Learning Academy?

Nie wymagamy żadnego doświadczenia. Machine Learning Academy w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 1 z 4.

Ile czasu zajmuje lekcja „Intuicja stojąca za boostingiem: sekwencyjna korekta błędów”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Machine Learning Academy?

Tak. Każda lekcja Machine Learning Academy zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Intuicja stojąca za boostingiem: sekwencyjna korekta błędów
  2. XGBoost: regularyzacja, wczesne zatrzymanie i ważność cech
  3. LightGBM: rozrost liści i zalety szybkości
  4. Najważniejsze hiperparametry: learning rate, n_estimators i max_depth
← Powrót do Machine Learning Academy