Decision Boundary Plot in Python with scikit-learn

Plot a classifier's decision boundary with scikit-learn's DecisionBoundaryDisplay, compare six models on the same data, and see overfitting as a jagged boundary.

To plot a classifier's decision boundary in scikit-learn, use DecisionBoundaryDisplay.from_estimator(model, X) from sklearn.inspection. It evaluates the fitted model on a grid covering the data and draws the predicted class (or probability) as colored regions, and you scatter your points on top. It needs exactly two features, since the plot is 2D. The code targets scikit-learn 1.9.

Quick Example

This fits a random forest on two-feature data and draws the predicted probability of class 1 across the plane, with the training points on top.

import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_moons
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import DecisionBoundaryDisplay
from sklearn.model_selection import train_test_split

# Sample data: two interleaving half-circles with noise
X, y = make_moons(n_samples=400, noise=0.3, random_state=7)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)

rf = RandomForestClassifier(n_estimators=200, random_state=0).fit(X_train, y_train)

fig, ax = plt.subplots(figsize=(6, 4.6))
disp = DecisionBoundaryDisplay.from_estimator(rf, X_train, response_method="predict_proba", cmap="RdBu_r",
                                              alpha=0.8, levels=np.linspace(0, 1, 11), ax=ax,
                                              xlabel="feature 1", ylabel="feature 2")
ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap="RdBu_r", edgecolor="white", s=28)
fig.colorbar(disp.surface_, ax=ax, label="P(class 1)")
ax.set_title("Random forest: predicted probability")
fig.tight_layout()

Decision surface of a random forest on two-class data. Blue regions on the left, red on the lower right, with a narrow white band of uncertain probability between them and a colorbar from 0 to 1

Pale colors near 0.5 mark the boundary itself, and the saturated areas are where the model is confident. The forest's boundary is made of axis-aligned rectangles, because each tree splits on one feature at a time.

How Do I Plot a Decision Boundary for a Classifier?

The steps are the same for any scikit-learn classifier:

  1. Fit the model on two features.
  2. Call DecisionBoundaryDisplay.from_estimator(model, X, ...).
  3. Scatter the data with ax.scatter, using the same cmap so the point colors match the regions.

The arguments you will use most:

Argument What it does
response_method "predict" for hard class regions, "predict_proba" or "decision_function" for a smooth surface. Default "auto" tries decision_function, then predict_proba, then predict
plot_method "contourf" (default), "contour" for lines only, or "pcolormesh"
grid_resolution Grid points per axis, default 100. Raise it for smoother edges
eps Padding added around the data range, default 1.0
ax Draw into an existing Matplotlib axis

For a binary problem with "predict_proba", it plots the probability of classes_[1]. For more than two classes it draws all of them by default, and class_of_interest picks a single class instead. Since 1.6, "auto" no longer falls back to "predict" for multiclass problems.

The default plot_method draws with Matplotlib's contourf; contour and contourf explains levels, colormaps, and line labels.

Compare Decision Boundaries of Different Models

The same data, six models. Each panel shows the test points over the region the model assigns to each class.

from sklearn.ensemble import GradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier

models = {
    "Logistic regression": LogisticRegression(),
    "k-nearest neighbors (k=15)": KNeighborsClassifier(15),
    "SVM (RBF kernel)": make_pipeline(StandardScaler(), SVC(gamma=1)),
    "Decision tree (depth 4)": DecisionTreeClassifier(max_depth=4, random_state=0),
    "Random forest": RandomForestClassifier(n_estimators=200, random_state=0),
    "Gradient boosting": GradientBoostingClassifier(random_state=0),
}
fig, axes = plt.subplots(2, 3, figsize=(11, 6.8), sharex=True, sharey=True)
for ax, (name, model) in zip(axes.ravel(), models.items()):
    model.fit(X_train, y_train)
    acc = model.score(X_test, y_test)
    DecisionBoundaryDisplay.from_estimator(model, X_train, response_method="predict", cmap="RdBu_r", alpha=0.35, ax=ax)
    ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap="RdBu_r", edgecolor="white", s=26)
    ax.set_title(f"{name}\ntest accuracy {acc:.0%}", fontsize=10)
    ax.set_xlabel("")
    ax.set_ylabel("")
fig.tight_layout()

Six decision boundary plots on the same two-moons data: a straight line for logistic regression, a jagged curve for KNN, a smooth blob for the RBF SVM, rectangular steps for the tree, and finer rectangles for the random forest and gradient boosting

What each shape tells you:

Model Boundary shape Test accuracy
Logistic regression A single straight line, so it cannot follow the curved classes 84%
KNN (k=15) Follows local neighborhoods, irregular but smooth-ish 90%
SVM (RBF) A smooth curved region 88%
Decision tree (depth 4) Axis-aligned rectangles 88%
Random forest Many small rectangles averaged together 92%
Gradient boosting Rectangles with some narrow slivers 90%

With 120 test points, a difference of one or two points is 1 to 2 percentage points, so the ranking among the top four is not reliable. The plots are most useful for seeing how a model fails, not for choosing a winner. For ranking models use ROC curves or cross-validation.

What Does Overfitting Look Like in a Decision Boundary?

Changing k in KNN is the cleanest demonstration. A very small k bends around individual points, and a very large k averages everything into a straight line.

fig, axes = plt.subplots(1, 3, figsize=(11, 3.8), sharex=True, sharey=True)
for ax, k in zip(axes, [1, 15, 150]):
    knn = KNeighborsClassifier(k).fit(X_train, y_train)
    tr, te = knn.score(X_train, y_train), knn.score(X_test, y_test)
    DecisionBoundaryDisplay.from_estimator(knn, X_train, response_method="predict", cmap="RdBu_r", alpha=0.35, ax=ax)
    ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap="RdBu_r", edgecolor="white", s=24)
    ax.set_title(f"k = {k}\ntrain {tr:.0%}, test {te:.0%}", fontsize=10)
    ax.set_xlabel("")
    ax.set_ylabel("")
fig.tight_layout()

Three KNN decision boundaries. With k=1 the boundary is jagged with small islands around single points. With k=15 it is smooth and follows the data. With k=150 it is nearly a straight diagonal line

With k=1 the training accuracy is 100% and the boundary has small islands around single points, but test accuracy is 88%. At k=15 it is 93% train and 90% test. At k=150 the boundary is almost a straight line and both scores fall (84% train, 82% test), which is underfitting. The validation curve post shows how to pick this setting systematically.

What If I Have More Than Two Features?

DecisionBoundaryDisplay only draws two dimensions. Two common options:

  • Train on two features only. Choose the two most informative ones (see feature importance). The plot is honest, but the model is a smaller one than your real model.
  • Reduce to two dimensions first, for example with PCA, then fit and plot on those components. The axes become combinations of your original features, so they are harder to interpret. See PCA explained variance and biplot.

Fitting on all features and plotting only two will not work: from_estimator builds its grid from the two columns of X you pass, so the estimator must have been trained on exactly those two.

Practical Tips

  • Use the same cmap for the region and the scatter, with alpha around 0.3 to 0.4 on the regions so the points stay visible.
  • Scale features before models that depend on distance (KNN, SVM), or the boundary is dominated by the feature with the larger range. Put a StandardScaler in a Pipeline, as in the SVM above.
  • Plot test points to see generalization, and training points to see what the model fit.
  • Use response_method="predict_proba" when probabilities matter. A hard-class plot hides how uncertain the model is near the boundary.
  • These plots come from one seeded two-moons dataset, so exact accuracies will shift with another sample.

Similar Topics