Skip to content

DOC Use DecisionBoundaryDisplay in plot_forest_iris example - #34060

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

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

Conversation

@mvanhorn

Copy link
Copy Markdown

Summary

Single-file edit to examples/ensemble/plot_forest_iris.py.

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

  2. Capture the current axes object at the start of each subplot iteration so from_estimator can be passed ax=ax:

    ax = plt.subplot(3, 4, plot_idx)

    in place of the existing plt.subplot(3, 4, plot_idx) call (the function already returns an Axes - just assign it).

  3. Replace the if isinstance(model, DecisionTreeClassifier): Z = ...; cs = plt.contourf(xx, yy, Z, cmap=cmap) branch with:

    if isinstance(model, DecisionTreeClassifier):
        DecisionBoundaryDisplay.from_estimator(
            model,
            X,
            response_method="predict",
            plot_method="contourf",
            cmap=cmap,
            ax=ax,
            xlabel="",
            ylabel="",
        )

    The meshgrid / x_min/x_max/y_min/y_max computation a few lines above the branch becomes dead for the DecisionTree case but is still consumed by the else (alpha-blend) branch and by the coarse-grid xx_coarser/yy_coarser scatter, so keep it.

  4. Leave the else branch (alpha-blend over model.estimators_) completely unchanged - both the for tree in model.estimators_: loop and its per-tree plt.contourf calls. Add a single short comment above the else branch noting that this branch intentionally does not use DecisionBoundaryDisplay because the pedagogical point is the per-tree blend.

  5. Leave the coarser-grid plt.scatter overlay, the training-point scatter, the plt.title and plt.suptitle, and plt.tight_layout() / plt.show() untouched.

  6. After step 3, convert the surrounding plt.scatter(...) and plt.title(...) calls inside the loop iteration to the ax.* form so the axes object created in step 2 receives them. The contourf via DecisionBoundaryDisplay is already routed to ax; the scatter and title need the explicit ax.* to match.

PR title: DOC Use DecisionBoundaryDisplay for single-tree case in plot_forest_iris example

PR body (concise, factual):

Towards #33980.

Refactor the single-DecisionTreeClassifier drawing path in examples/ensemble/plot_forest_iris.py to use DecisionBoundaryDisplay.from_estimator(..., response_method="predict", plot_method="contourf").

The ensemble alpha-blend path (for tree in model.estimators_: ... plt.contourf(... alpha=1/n_estimators ...)) is left as-is on purpose: the per-tree blend is the pedagogical point of this example, and DecisionBoundaryDisplay cannot reproduce it without losing that intent. The coarse-grid xx_coarser/yy_coarser prediction-scatter overlay is also unchanged.

No behavior change for users; this is a documentation-only partial refactor matching the pattern established by #33952 and intentionally narrower than a full conversion.

Why this matters

Issue #33980 lists examples/ensemble/plot_forest_iris.py as one of the four remaining examples that should be refactored to use DecisionBoundaryDisplay. The current file is 176 lines and contains TWO decision-region drawing paths inside the inner loop:

  1. Single DecisionTree path (lines ~126-129): standard meshgrid + model.predict(np.c_[xx.ravel(), yy.ravel()]) + plt.contourf. This is the direct analog of the from_estimator helper and is straightforward to refactor.

  2. Ensemble alpha-blend path (lines ~130-139): iterates over model.estimators_ and calls tree.predict(...) for each individual tree in the forest/ExtraTrees/AdaBoost ensemble, drawing one contourf per tree with alpha=1/n_estimators. This visualizes how individual trees vote and is a deliberate pedagogical choice of the example.

  3. There is also a xx_coarser, yy_coarser meshgrid + model.predict + plt.scatter overlay below the contourf, showing predictions on a coarse grid.

The clean refactor is to convert path (1) to DecisionBoundaryDisplay.from_estimator and leave path (2) and (3) untouched. Path (2) cannot be expressed by from_estimator without losing the per-tree alpha-blend semantics; trying to do so would break the example's purpose.

Testing

  • python examples/ensemble/plot_forest_iris.py runs to completion without exceptions and produces the 3x4 grid of subplots with all four classifiers (DecisionTree, RandomForest, ExtraTrees, AdaBoost) showing decision regions, coarse-grid sample predictions, and training points.
  • Visual diff: render main vs the branch.
    • Column 1 (DecisionTreeClassifier) decision regions should look visually equivalent - same boundary geometry, same cmap=plt.cm.RdYlBu.
    • Columns 2-4 (ensemble classifiers) must be byte-identical to main since they use the unchanged alpha-blend path.
    • Coarse-grid scatter overlay and training-point scatter must remain visually equivalent in all 12 subplots.
  • sphinx-build doc -b html doc/_build completes without new warnings for the ensemble gallery page.
  • grep -n "DecisionBoundaryDisplay" examples/ensemble/plot_forest_iris.py returns one import match and one call-site match (inside the isinstance(model, DecisionTreeClassifier) branch).
  • grep -n "for tree in model.estimators_" examples/ensemble/plot_forest_iris.py still returns the existing per-tree alpha-blend loop (proves the ensemble path was preserved).
  • ruff check examples/ensemble/plot_forest_iris.py reports 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