Skip to content

FIX Add class-specific contour lines in DecisionBoundaryDisplay for predict_proba and decision_function - #33471

Merged
lucyleeow merged 25 commits into
scikit-learn:mainfrom
AnneBeyer:dbd_fix_contour_lines
Apr 13, 2026
Merged

lucyleeow merged 25 commits into
scikit-learn:mainfrom
AnneBeyer:dbd_fix_contour_lines

Conversation

@AnneBeyer

@AnneBeyer AnneBeyer commented Mar 6, 2026 •

Copy link
Copy Markdown
Member

Reference Issues/PRs

Closes #33108

What does this implement/fix? Explain your changes.

This PR adapts the behaviour when plot_method="contour".
The contour lines for each class are now also drawn when response_method = predict_proba or decision_function.
As discussed in #33108, I went for black lines for the class boundaries, as the boundary lines may overlap and the colors don't necessarily correspond to the classes.

For the same reason, I also changed the contour color for response_method = predict to "black". Given that this display is mainly intended as an inspection tool,
I only added a note on this in the docstring, without throwing a warning or giving other options to set the color.

One could think about making the class boundary contour dotted or even optional when response_method = predict_proba or decision_function, but I'm not sure if it is worth spending too much time on possible refinements unless someone who is using them actually requests it?

WDYT? @lucyleeow @ogrisel (also pinging @snath-xoc, in case you want to have a look)

This is what it looks like now:
image

Code
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.inspection import DecisionBoundaryDisplay

data = np.array(
    [
        [-1, -1],
        [-2, -1],
        [1, 1],
        [2, 1],
        [2, 2],
        [3, 2],
        [3, 3],
        [4, 3],
        [4, 4],
        [5, 4],
        [5, 5],
    ]
)
target = np.arange(11)
clf = LogisticRegression().fit(data, target)

cmap = "gist_rainbow"
_, axes = plt.subplots(nrows=1, ncols=3, figsize=(12, 4), constrained_layout=True)
for response_method_idx, response_method in enumerate(
    ["predict_proba", "decision_function", "predict"]
    ):
    ax = axes[response_method_idx]
    display = DecisionBoundaryDisplay.from_estimator(
        clf,
        data,
        multiclass_colors=cmap,
        grid_resolution=200,
        response_method=response_method,
        plot_method="contour",
        ax=ax,
        )
    ax.scatter(
        data[:, 0],
        data[:, 1],
        c=target.astype(int),
        edgecolors="black",
        cmap=cmap,
    )
    if isinstance(display.surface_, list):
        levels = len(display.surface_[-1].levels)
    else:
        levels = len(display.surface_.levels)
    ax.set_title(f"plot_method=contour\nresponse_method={response_method}\nlevels={levels}")
plt.show()

AI usage disclosure

I used AI assistance for:

  • Code generation (e.g., when writing an implementation or fixing a bug)
  • Test/benchmark generation
  • Documentation (including examples)
  • Research and understanding

Any other comments?

I also added zorder=-1 and antialiased=True as defaults (if not specified otherwise in kwargs)

for idx, quad in enumerate(disp.surface_):
assert quad.cmap == cmaps[idx]
else:
assert_allclose(disp.surface_.colors, colors)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This used to be for the contour case, which is now handled by the changes above.

mpl, self.multiclass_colors, self.n_classes
)

if self.response.ndim == 2: # predict

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This part moved down to line 385

kwargs["antialiased"] = True

# predict_proba and decision_function differ for plotting methods
elif plot_method == "contour":

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This part is now in line 370

@AnneBeyer AnneBeyer added this to Labs Mar 6, 2026
@github-project-automation github-project-automation Bot moved this to Todo in Labs Mar 6, 2026
@AnneBeyer AnneBeyer moved this from Todo to In progress in Labs Mar 6, 2026
@AnneBeyer

Copy link
Copy Markdown
Member Author

@snath-xoc: You can find the code to play around with the contour lines in the PR description above.

@AnneBeyer
AnneBeyer marked this pull request as ready for review March 9, 2026 15:35
@AnneBeyer

Copy link
Copy Markdown
Member Author

Also pinging @antoinebaker, if you have time :)

@antoinebaker antoinebaker left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR @AnneBeyer, on the provided example it looks great! A few formatting nitpicks, but LGTM.

Could you maybe launch the CI with the [doc build] commit message
https://scikit-learn.org/dev/developers/contributing.html#commit-message-markers
so that we can visually check some examples ?

Comment on lines +1 to +6
- :class:`inspection.DecisionBoundaryDisplay` with ``plot_method="contour"`` now also
displays class-specific contours for ``response_method="predict_proba"`` and
``response_method="decision_function"``.
Class boundary contour lines are now displayed in black by default for all response
methods to avoid confusion.
By :user:`Anne Beyer <AnneBeyer>`.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The lines look uneven, we should rewrap the text. If you are using vscode, you can use the extension https://marketplace.visualstudio.com/items?itemName=stkb.rewrap

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(And same comment for some docstrings, the lines look uneven).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added the line break on purpose here, because there are two separate things: the intra-class contour lines (that were not displayed before) and changing the color to black for the inter-class contour lines.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Usually (based on the changelogs I've looked at), the changelog is written as one block even if there are separate things done. (Unless these things are very different for example a fix and an API change or affecting different estimators in different ways, then each deserves its own changelog). So in this case I wouldn't put the line break.

Anyway it is really a nitpick :)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the changelog is written as one block

Not sure, but maybe this is because of the bullet list format? Note that towncrier cannot handle >1 bullet point, but it can handle 1 bullet point with several sub-bullet points below. (just FYI)

@AnneBeyer

Copy link
Copy Markdown
Member Author

Thank you for the feedback @antoinebaker!
I'm not sure if we have any examples using this specific parameter combination, but I did notice some inconsistencies in other examples using [doc build] and opened #33557 to check all that use this display class. I'll reference them here if I find any relevant to this PR.

@antoinebaker antoinebaker left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @AnneBeyer you have a few unrelated diff to the PR, otherwise the logic still looks good to me. Ping me when you need a final look /approval on the PR !

@antoinebaker

Copy link
Copy Markdown
Member

I'll reference them here if I find any relevant to this PR.

That list is super useful, thanks ! I'll take a look at the listed examples when doing the final review.

@AnneBeyer

Copy link
Copy Markdown
Member Author

I reverted setting antialiased=True by default because it introduced unnecessary lines in plot_classification_probability (see screenshot below) and actually did not help much with smoothing the contour lines here. It can still be set by the user via the kwargs.

image

@ogrisel ogrisel left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks like a net improvement. +1 for merge once the following simplification is addressed.

I think we could also want to make the binary case consistent with the rendering of the multiclass case by also adding a black line at predict_proba == 0.5 or decision_function == 0 but this can be done in a follow-up PR, and in particular after the refactoring in #33115 is completed.

@jeremiedbb jeremiedbb added this to the 1.9 milestone Apr 8, 2026

@lucyleeow lucyleeow left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mostly nits and test suggestions, otherwise LGTM!

Is it worth adding a test that instantiates the class and then classes plot ? AFAICT no tests currently do this, we always create an instance via from_estimator. I know we do not recommend use this way, but it is possible and may be worthwhile testing?

@AnneBeyer

Copy link
Copy Markdown
Member Author

Is it worth adding a test that instantiates the class and then calls plot ? AFAICT no tests currently do this, we always create an instance via from_estimator. I know we do not recommend use this way, but it is possible and may be worthwhile testing?

There are some cases where plot is called after from_estimator to change/add a display, but there is indeed no test without it. There is an example using this in the docstring of the DecisionBoundaryDisplay class, so this is tested implicitly when building the docs, but we could also make it an explicit test. I would say that this is something for another PR, though.

@AnneBeyer

Copy link
Copy Markdown
Member Author

Getting the test for surface colour and zorder to work turned out to be a bit more complicated than expected: In matplotlib 3.10.0, the API for
QuadContourSet was changed to produce only one collection per plot (as it was and is the case for QuadMesh) and .collections was deprecated, whereas before, a collection was created for each level separately. I added two version-based cases for the test.

@AnneBeyer

Copy link
Copy Markdown
Member Author

Something for another clean-up PR: I noticed that some of the test check for matplotlib < v3.5, since 3.6 is now the minimal version, these can probably be removed?

@lucyleeow lucyleeow left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a nit, thank you for adding the extra test!

@AnneBeyer

Copy link
Copy Markdown
Member Author

Thank you all, for all your feedback!
I think I addressed everything and noted the follow-ups, so this should be ready to be merged now.
@antoinebaker @ogrisel @lucyleeow

@lucyleeow
lucyleeow merged commit 45bad76 into scikit-learn:main Apr 13, 2026
33 checks passed
@github-project-automation github-project-automation Bot moved this from In progress to Done in Labs Apr 13, 2026
@lucyleeow

Copy link
Copy Markdown
Member

Thanks for your work and patience @AnneBeyer !

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.

RFC DecisionBoundaryDisplay levels overlap with 'contour'

5 participants