Skip to content

DOC Use DecisionBoundaryDisplay in plot_svm_margin example - #34058

Closed
mvanhorn wants to merge 1 commit into
scikit-learn:mainfrom
mvanhorn:fix/33980-sklearn-decision-boundary-svm-margin
Closed

mvanhorn wants to merge 1 commit into
scikit-learn:mainfrom
mvanhorn:fix/33980-sklearn-decision-boundary-svm-margin

Conversation

@mvanhorn

Copy link
Copy Markdown

Summary

Single-file edit to examples/svm/plot_svm_margin.py. The refactor replaces the manual mesh+decision_function+contourf block (lines ~70-81 of the current file) with a call to DecisionBoundaryDisplay.from_estimator.

  1. Add from sklearn.inspection import DecisionBoundaryDisplay to the imports.

  2. Inside the per-(name, penalty) loop, restructure to obtain an Axes object so DecisionBoundaryDisplay can draw onto the same figure as the margin lines and scatter:

    fig, ax = plt.subplots(figsize=(4, 3), num=fignum)

    in place of plt.figure(fignum, figsize=(4, 3)); plt.clf().

  3. Replace the explicit YY, XX = np.meshgrid(yy, xx); xy = np.vstack(...).T; Z = clf.decision_function(xy).reshape(...); plt.contourf(XX, YY, Z, cmap=plt.get_cmap("RdBu"), alpha=0.5, ...) block with:

    DecisionBoundaryDisplay.from_estimator(
        clf,
        X,
        response_method="decision_function",
        plot_method="contourf",
        cmap=plt.get_cmap("RdBu"),
        alpha=0.5,
        ax=ax,
        xlabel="",
        ylabel="",
    )

    Note: from_estimator chooses a sensible mesh extent from X. The current example hard-codes x_min=-4.8, x_max=4.2, y_min=-6, y_max=6. Preserve the visual range by calling ax.set_xlim(x_min, x_max) / ax.set_ylim(y_min, y_max) after the display, matching what the file already does.

  4. Convert remaining plt.* calls in this loop iteration to the ax.* form (ax.plot, ax.scatter, ax.set_xticks([]), ax.set_yticks([])) so the margin lines, support vectors, and data points still render on top of the decision region. The two plt.plot(xx, yy_down, "k--") and plt.plot(xx, yy_up, "k--") calls become ax.plot(xx, yy_down, "k--") and ax.plot(xx, yy_up, "k--") respectively; the two plt.scatter calls become ax.scatter.

  5. Leave plt.show() at the end of the file untouched.

PR title: DOC Use DecisionBoundaryDisplay in plot_svm_margin example

PR body (concise, factual):

Towards #33980.

Refactor examples/svm/plot_svm_margin.py to draw the SVC decision region with DecisionBoundaryDisplay.from_estimator(..., response_method="decision_function", plot_method="contourf") instead of the manual meshgrid + decision_function + contourf block. The hard-coded x_min/x_max/y_min/y_max viewport and the dashed margin lines computed from clf.coef_ are kept as-is so the example's visual stays identical.

No behavior change for users; this is a documentation-only refactor matching the pattern established by #33952.

Same checklist entry as the AI usage disclosure section of the PR template (Documentation - examples).

Why this matters

Issue #33980 (DOC refactor examples to use DecisionBoundaryDisplay) is a follow-up to #33557 and tracks five examples that still draw decision boundaries with manual contour math instead of the public sklearn.inspection.DecisionBoundaryDisplay helper. One subtask is already merged (#33952 -> plot_rbf_parameters.py). The remaining four are explicitly listed as unchecked checkbox items: plot_svm_margin.py, plot_kmeans_digits.py, plot_gpc_iris.py, plot_forest_iris.py. This plan covers plot_svm_margin.py.

examples/svm/plot_svm_margin.py currently:

  • builds xx = np.linspace(-5, 5),
  • derives yy, yy_down, yy_up from the linear classifier's coef_ and intercept_ to draw the separating hyperplane and margin lines,
  • builds a meshgrid (YY, XX) and calls clf.decision_function(xy) to produce Z,
  • and finally calls plt.contourf(XX, YY, Z, ...) to fill the decision regions.

The manual decision_function mesh and contourf call is exactly the pattern DecisionBoundaryDisplay.from_estimator(..., response_method="decision_function", plot_method="contourf") exists to replace. The margin lines themselves (yy_down, yy_up) are a special feature of this example, not generic boundary plotting, so they stay - the refactor is targeted at the colored region behind them.

Testing

  • python examples/svm/plot_svm_margin.py runs to completion without exceptions and shows two figures (unreg and reg) with the same hyperplane, margin lines, support-vector circles, and colored decision background as the current main output.
  • Visual diff: render main and the branch side-by-side. The filled RdBu background must look indistinguishable (the underlying decision function value is identical; only the path that draws it changed).
  • sphinx-build doc -b html doc/_build (or the project's make html recipe under the same environment) completes without new warnings or sphinx-gallery rendering errors for the SVM examples gallery page.
  • grep -n "meshgrid\|decision_function" examples/svm/plot_svm_margin.py after the edit returns no matches inside the loop (the manual computation is gone).
  • grep -n "DecisionBoundaryDisplay" examples/svm/plot_svm_margin.py returns one match for the import and one for the call site.
  • Run ruff check examples/svm/plot_svm_margin.py (the repo's configured linter via pyproject.toml) - no new findings.

Fixes #33980

AI was used for assistance.

@jeremiedbb

Copy link
Copy Markdown
Member

The linked issue is not open for contribution, please read the full description #33980 (comment). In addition, please take a look at https://scikit-learn.org/stable/developers/contributing.html#automated-contributions-policy. With that in mind I'm closing this PR.

@jeremiedbb jeremiedbb closed this May 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

DOC refactor examples to use DecisionBoundaryDisplay

2 participants