AI/ML

Gradient Boosting and Support Vector Machines Explained with Python and scikit-learn Ep04

Kaveesha Gimhana
Kaveesha GimhanaNov 30, 2026 • 15 min read
Gradient Boosting and Support Vector Machines Explained with Python and scikit-learn Ep04
Series · Part 4 of 18Machine Learning: From 0 to Machine4 of 18 published

“One model learns from its own mistakes, one model looks for the widest gap. Both are hard to beat.”

In Ep03 a random forest beat a single decision tree by letting hundreds of trees vote. Those trees were built independently, each one blind to what the others got wrong. That raises an obvious question: what if every new tree looked at the mistakes so far and focused on fixing them?

That idea is gradient boosting, the algorithm behind XGBoost and LightGBM and behind a huge share of winning solutions on tabular data. In this post we build it by hand in a dozen lines, then use scikit-learn’s version. In the second half we switch to a model with a completely different idea, the support vector machine (SVM), which finds the widest possible gap between two classes and uses the kernel trick when no straight gap exists. These are algorithms five and six of Module 2.

Gradient boosting: the core idea

Think of a student preparing for an exam with past papers. They attempt a paper, mark it, and then study only the questions they got wrong. Next attempt, they make fewer mistakes, so they focus on those. After enough rounds, very few errors are left.

Gradient boosting trains models the same way:

  1. Start simple. For regression the first “model” just predicts the average of all the targets.
  2. Measure what’s still wrong. Compute the residuals, actual minus predicted, for every training example.
  3. Fit a small tree to the residuals, not to the original target. This tree learns where and by how much the current model is wrong.
  4. Add a fraction of it. Update the prediction by the new tree’s output multiplied by the learning rate η (for example 0.1), so no single tree takes over.
  5. Repeat for hundreds of rounds. The final model is the starting average plus every tree’s small correction:
F(x) = mean(y) + η·tree₁(x) + η·tree₂(x) + … + η·treeₙ(x)

The trees are deliberately weak, usually only 2 to 6 levels deep. Each one does a little, and their sum does a lot. The “gradient” in the name comes from the general version of the idea: for squared error the residual is exactly the negative gradient of the loss, so fitting trees to residuals is gradient descent, where each step is a tree instead of a small change to a weight. The same recipe works for classification by swapping in log loss from Ep02.

Step 1: Build gradient boosting by hand

Here is the whole algorithm on a curved, noisy pattern, a sine wave, that no straight line could fit. We keep 50 points aside as a test set:

import numpy as np
from sklearn.tree import DecisionTreeRegressor

rng = np.random.default_rng(0)
x = rng.uniform(0, 6, 200).reshape(-1, 1)
y = np.sin(x).ravel() + rng.normal(0, 0.15, 200)    # a curved pattern plus noise
x_train, y_train, x_test, y_test = x[:150], y[:150], x[150:], y[150:]

learning_rate = 0.3
pred_train = np.full(len(y_train), y_train.mean())  # round 0: predict the average
pred_test = np.full(len(y_test), y_train.mean())

for round_ in range(1, 201):
    residuals = y_train - pred_train                 # what we still get wrong
    tree = DecisionTreeRegressor(max_depth=2).fit(x_train, residuals)
    pred_train += learning_rate * tree.predict(x_train)   # nudge towards the residuals
    pred_test += learning_rate * tree.predict(x_test)
    if round_ in (1, 5, 10, 25, 50, 200):
        train_mse = ((y_train - pred_train) ** 2).mean()
        test_mse = ((y_test - pred_test) ** 2).mean()
        print(f"round {round_:>3}: train MSE = {train_mse:.4f}  test MSE = {test_mse:.4f}")

Output:

round   1: train MSE = 0.2773  test MSE = 0.3347
round   5: train MSE = 0.0499  test MSE = 0.0634
round  10: train MSE = 0.0222  test MSE = 0.0296
round  25: train MSE = 0.0146  test MSE = 0.0227
round  50: train MSE = 0.0100  test MSE = 0.0234
round 200: train MSE = 0.0010  test MSE = 0.0320

What’s actually happening here

Each round fits a depth-2 tree to whatever error is left, and the error drops fast: from 0.28 to 0.02 in ten rounds. The important part is what happens after round 25. Training error keeps falling all the way to 0.001, but test error bottoms out around 0.023 and starts climbing again.

That is boosting’s signature failure. We added noise with a standard deviation of 0.15 (a variance of about 0.0225), so a test MSE near 0.0225 is about as good as any model can do. Once the trees have captured the real sine curve, the only thing left to “fix” is the noise, and fitting noise is overfitting. Unlike a random forest, where adding trees is mostly harmless, more boosting rounds can make the model worse. The number of rounds has to be tuned, ideally with early stopping, which halts training when a validation score stops improving.

Step 2: Gradient boosting with scikit-learn

On real data you use a library, which adds the details we skipped: log loss for classification, row subsampling and regularization. Let’s put it against the random forest from Ep03 on the breast cancer dataset:

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

X, y = load_breast_cancer(return_X_y=True)

models = {
    "random forest":     RandomForestClassifier(n_estimators=300, random_state=0, n_jobs=-1),
    "gradient boosting": GradientBoostingClassifier(n_estimators=300, learning_rate=0.05,
                                                    max_depth=3, random_state=0),
}
for name, model in models.items():
    scores = cross_val_score(model, X, y, cv=5)
    print(f"{name:<18} accuracy = {scores.mean():.3f} ± {scores.std():.3f}")

Output:

random forest      accuracy = 0.963 ± 0.022
gradient boosting  accuracy = 0.960 ± 0.017

What’s actually happening here

On this small, clean dataset the two are effectively tied; the difference is well inside the ± spread. That’s an honest result worth remembering: boosting is not magic. It tends to pull ahead on larger, messier tabular data, and only after tuning. The three settings that matter most work together:

  • n_estimators, the number of trees (rounds).
  • learning_rate, how much each tree contributes. Lower values need more trees but usually generalise better; 0.05 to 0.1 is a common starting point.
  • max_depth, the size of each tree, usually 3 to 6.

For anything beyond a few thousand rows, use scikit-learn’s HistGradientBoostingClassifier (and HistGradientBoostingRegressor). It bins features into histograms, trains many times faster, handles missing values natively, and supports early stopping out of the box. Outside scikit-learn, XGBoost, LightGBM and CatBoost are heavily optimised implementations of the same idea, with extra regularization and GPU support; they are what most competition winners and production teams reach for.

Bagging vs boosting in one line each

  • Random forest (bagging): many deep trees built in parallel on random samples, then averaged. Reduces variance. Hard to overfit by adding trees.
  • Gradient boosting: many shallow trees built in sequence, each correcting the last. Reduces bias. Can overfit if you add too many rounds, so tune it.

Support vector machines: find the widest street

Now a completely different way of thinking. Imagine two groups of points on a map and you have to draw a road between them. Many roads would separate the two groups, but some of them pass very close to a point; a slightly different new point would end up on the wrong side. The safest road is the one with the widest possible street, as far from both groups as it can be.

That is a support vector machine. In two dimensions the road is a line; in more dimensions it is a hyperplane, written w·x + b = 0. The street’s half-widths are the margins, and the full width works out to 2/‖w‖, so maximising the margin means minimising ‖w‖.

Only the handful of points sitting exactly on the edges of the street decide where it goes. Those are the support vectors, and they give the algorithm its name. You could delete every other training point and the line would not move. That also makes the trained model compact: it only has to remember its support vectors.

The C parameter: hard vs soft margins

Real data overlaps. A perfectly clean street usually doesn’t exist, and insisting on one means bending the line around every noisy point. So SVMs allow a soft margin: some points may sit inside the street or even on the wrong side, at a cost. The optimisation becomes:

minimise   ½‖w‖² + C · Σ ξᵢ

where ξᵢ (the slack) measures how badly point i violates the margin. C sets the price of each violation:

  • Small C means violations are cheap. The SVM prefers a wide, calm street and tolerates mistakes, which leads to underfitting if C is too small.
  • Large C means violations are expensive, a hard margin. The street narrows and bends to classify every training point, including noise, which leads to overfitting.

Here is that trade-off on two overlapping, noisy half-moon shapes:

from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC

X, y = make_moons(n_samples=300, noise=0.35, random_state=1)   # two noisy half-moons
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)

for C in [0.01, 1, 1000]:
    svm = SVC(kernel="rbf", C=C, gamma=2).fit(X_train, y_train)
    print(f"C={C:<5} support vectors = {len(svm.support_vectors_):>3}  "
          f"train = {svm.score(X_train, y_train):.3f}  test = {svm.score(X_test, y_test):.3f}")

Output:

C=0.01  support vectors = 200  train = 0.524  test = 0.444
C=1     support vectors =  83  train = 0.905  test = 0.878
C=1000  support vectors =  64  train = 0.910  test = 0.811

What’s actually happening here

At C = 0.01 the margin is so soft that almost every training point (200 of 210) is a support vector, and the model barely does better than guessing: underfitting. At C = 1000 the model has fewer support vectors and a higher training score, but its test accuracy drops from 0.878 to 0.811 because it has bent itself around noise: overfitting. C = 1 is the balance. As with tree depth and boosting rounds, you pick C with cross-validation.

The kernel trick: when no straight line exists

Some data can’t be separated by any straight line. In the classic example one class forms a ring around the other. But add a third feature, z = x₁² + x₂² (each point’s squared distance from the centre), and the inner points sit low while the outer ring sits high. A flat plane now separates them perfectly. When you project that plane back down to the original two features, it becomes a circle.

Computing new features for every point gets expensive fast, and some useful feature spaces have infinitely many dimensions. The kernel trick avoids computing them at all. The SVM’s maths only ever needs the dot product between pairs of points, and a kernel function returns the dot product the points would have in the higher-dimensional space, computed directly from the original features. You get a curved boundary at roughly the cost of a straight one.

The kernels you will actually use:

  • linear: K(x, x′) = x·x′. No lifting. Best when you have many features relative to samples (text classification) or the classes are already roughly linearly separable. Fast.
  • poly: K(x, x′) = (γ·x·x′ + r)ᵈ, polynomial boundaries of degree d.
  • rbf (radial basis function, the default): K(x, x′) = exp(−γ‖x − x′‖²). It measures similarity to nearby points and corresponds to an infinite-dimensional space, so it can draw almost any smooth boundary. γ controls how far each point’s influence reaches: a large γ makes a wiggly boundary that can overfit, a small γ makes a smooth one.

Here is the ring example in code:

from sklearn.datasets import make_circles
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC

X, y = make_circles(n_samples=400, factor=0.4, noise=0.1, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)

for kernel in ["linear", "poly", "rbf"]:
    svm = SVC(kernel=kernel, degree=2, C=1).fit(X_train, y_train)
    print(f"{kernel:<7} test accuracy = {svm.score(X_test, y_test):.3f}")

Output:

linear  test accuracy = 0.525
poly    test accuracy = 1.000
rbf     test accuracy = 1.000

The linear kernel is stuck at coin-flip accuracy because no line separates a ring. A degree-2 polynomial kernel, which is exactly the x₁² + x₂² idea, and the RBF kernel both get every test point right.

Step 3: Tune an SVM on real data

SVMs measure distances, so feature scaling is not optional: one feature measured in hundreds would drown out the rest. Put the scaler and the SVM in one pipeline, then search over C and γ together:

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42)

pipe = make_pipeline(StandardScaler(), SVC(kernel="rbf"))
grid = GridSearchCV(pipe, {
    "svc__C":     [0.1, 1, 10, 100],
    "svc__gamma": ["scale", 0.01, 0.1, 1],
}, cv=5)
grid.fit(X_train, y_train)

print("best params:", grid.best_params_)
print("cross-val accuracy:", round(grid.best_score_, 3))
print("test accuracy:", round(grid.score(X_test, y_test), 3))

Output:

best params: {'svc__C': 10, 'svc__gamma': 0.01}
cross-val accuracy: 0.98
test accuracy: 0.982

What’s actually happening here

GridSearchCV tries all 16 combinations of C and γ, scores each with 5-fold cross-validation on the training set only, and keeps the best (C = 10, γ = 0.01). The svc__ prefix tells the pipeline which step a parameter belongs to. Only after the search is finished do we touch the test set, once, and get 0.982. Because the scaler lives inside the pipeline, it is re-fitted inside every cross-validation fold, so no information leaks from validation data into training.

When to use which

  • Gradient boosting is the go-to for structured, tabular data when you want maximum accuracy: credit scoring, fraud, churn, demand forecasting, click-through prediction, ranking. Prefer HistGradientBoosting*, XGBoost or LightGBM on anything sizeable, and budget time for tuning.
  • SVMs shine on small to medium datasets with many features, where a clean margin exists or can be made with a kernel: text classification, bioinformatics (thousands of genes, hundreds of patients), image features, and well-defined yes/no problems such as predicting whether a graduate will be employed from their grades.
  • If you need probabilities, boosting gives them directly. SVC gives margins by default; probability=True adds a calibration step that is slower and only approximate.

Common first-time mistakes

  • Not scaling features for an SVM. This is the most common reason an SVM “doesn’t work”.
  • Boosting with too many rounds and no validation. Use early stopping (n_iter_no_change in scikit-learn, or the equivalent in XGBoost and LightGBM).
  • Tuning C and γ separately. They interact; search them together with GridSearchCV or RandomizedSearchCV.
  • Reaching for the RBF kernel on high-dimensional text. A linear kernel (or LinearSVC) is usually as accurate there and much faster.
  • Comparing models on one lucky split. Use cross-validation; the boosting-vs-forest tie above would look like a “win” for either side on some single splits.

The honest limitations

Gradient boosting trains sequentially, so it parallelises less naturally than a forest, has more knobs to tune, and overfits noisy labels if you let it run. Its hundreds of trees are no more readable than a forest’s. SVMs scale poorly: training time grows roughly with the square of the number of samples or worse, so on hundreds of thousands of rows a kernel SVM becomes impractical (use LinearSVC, or gradient boosting). Their decisions are also hard to explain once a kernel is involved, and they don’t output probabilities natively.


Where to go next

Gradient boosting and SVMs are both “eager” learners: they do all their work during training and produce a compact model. In Ep05 we look at two algorithms with very different personalities. K-nearest neighbours does no training at all and simply looks up the most similar examples when asked. Naive Bayes turns classification into probability arithmetic with Bayes’ theorem, and still powers spam filters decades after it was first used for them.


This post is part of the CeyTech series Machine Learning: From 0 to Machine – deep tech, no fluff. Try lowering the boosting learning rate to 0.05 and watch where the test error bottoms out, or give the SVM a gamma=50, and tell me what you saw.




Share this story:

Comments (...)

You must be signed in to join the discussion.

Loading comments...