Skip to content

RFC DecisionBoundaryDisplay levels overlap with 'contour' #33108

Closed

Description

@lucyleeow

Warning

This is a request for comment (RFC), please do not open a pull request for this issue. If you wish to contribute to scikit-learn please have a look at our contributing doc and in particular the section New contributors.

Noticed while reviewing #33015. Also related to #32866

#31553 reverted the plotting behaviour when plot_method='contour' such that only thresholded integers are used plotting, for all plot methods, not continuous proba/decision function values.

This means that the contour lines show where the predicted class changes from one to the other:

Image

instead of contour lines showing how continuous predicted values change, over the region where that class dominates:

Image

(figures taken from #31546)

The problem is that without setting levels mpl infers number of levels, 9 seems to be the default, resulting in a lot of overlapping lines.

Details

The contourf docs aren't very helpful - it says levels is optional but does not tell you what the default is. Digging into the code, it seems that _process_contour_level_args is responsible. It calls _ensure_locator_exists which does:

        if self.locator is None:
            if self.logscale:
                self.locator = ticker.LogLocator(numticks=N)
            else:
                if N is None:
                    N = 7  # Hard coded default
                self.locator = ticker.MaxNLocator(N + 1, min_n_ticks=1)

which seems to call MaxNLocator, with n_bins=7+1, which gives max 9 (n_bins + 1) ticks. This does seem to be what happens:

import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.inspection import DecisionBoundaryDisplay
from sklearn.linear_model import LogisticRegression

iris = load_iris()
X = iris.data[:, :2]
classifier = LogisticRegression().fit(X, iris.target)

# Create the contour plot
disp = DecisionBoundaryDisplay.from_estimator(
    classifier,
    X,
    plot_method='contour',
    xlabel=iris.feature_names[0],
    ylabel=iris.feature_names[1],
)

# Access the matplotlib axes and contour object
ax = disp.ax_
contour = disp.surface_

print(f"Number of classes: {len(iris.target_names)}")
print(f"Number of contour levels: {len(contour.levels)}")
print(f"Contour levels (decision values): {contour.levels}")
Number of classes: 3
Number of contour levels: 9
Contour levels (decision values): [0.   0.25 0.5  0.75 1.   1.25 1.5  1.75 2.  ]

The other problem is that we pass n_classes colors, but this does not match the number of levels (the passed colours are used to colour each level). In the case above, we pass 3 colours but there are 9 levels and from the docs:

The sequence is cycled for the levels in ascending order. If the sequence is shorter than the number of levels, it's repeated.

Thus the colours don't make sense and don't really correspond to any individual class.


Not sure what the best solution would be. We could specify levels such that we get n_classes levels, which would be a great improvement already. The question of what colour(s) the lines should be is more difficult. e.g., for the case above with 3 classes and levels at [1,2,3], 2 lines are drawn:

Image
Code
from sklearn.datasets import load_iris
from sklearn.inspection import DecisionBoundaryDisplay
from sklearn.linear_model import LogisticRegression

iris = load_iris()
X = iris.data[:, :2]
classifier = LogisticRegression().fit(X, iris.target)

# Create the contour plot
disp = DecisionBoundaryDisplay.from_estimator(
    classifier,
    X,
    plot_method='contour',
    xlabel=iris.feature_names[0],
    ylabel=iris.feature_names[1],
    levels=[0,1,2],
)

one for level 0: the transition from 0 -> 1 / 0 -> 2 and one for level 1: the transition from 1 -> 2 (the level 1 line also draws a line from 0 -> 2, but I think that is due to interpolation of the 0 -> 2 transition being 1 ? - this is the part where there are both blue and orange lines). The line colours don't really match to a single class, mostly because we have 2 lines for 3 classes.

Maybe it would be best to just draw contour lines in just one colour?

Related: #33015 (comment)

cc @AnneBeyer @ogrisel

Activity

  1. lucyleeow commented on Jan 20, 2026

    @lucyleeow
    MemberAuthor

    I see similar issues were discussed here: #32867 (comment) and #32867 (comment)

    I felt something was 'weird' about the contour implementation after #31553 and I see it's what @AnneBeyer noted - the plots now all look exactly the same no matter what response method was used, which is a bit odd.

    I think your (@AnneBeyer) accident here: #32867 (comment) may be the solution.

    Why don't we draw the contour lines for thresholded integer response values with a single colour for all response methods.
    Then for the probability and decision function methods, we would also add contour lines per class. The only implementation flaw detail I can think of is that it, since we are plotting twice for probability and decision functions, it would be difficult to pass kwargs to both plots, and for the first thresholded contour plot, and we may need to hardcode the line colour etc

    Maybe we could:

    • Specify levels to be array of class ints, when plotting thresholded integer response values, so we have a reasonable number of contour lines
    • Add contour lines per class, using continuous unthresholded response values, when using probability and decision function responses - such that the plots are different when using different response methods

    Edit:
    Just adding Annes plot from #32867 (comment), for ease of viewing:

    Image

    Note that the contour line colours around the class borders (plotted using integer thresholded response values) does not always make sense as they don't match the class it bounds. Also note that now the plots are different, depending on the plot method used.

    WDYT @AnneBeyer @ogrisel (and just in case @jeremiedbb, and @thomasjpfan who added this class originally)

  2. ogrisel commented on Feb 6, 2026

    @ogrisel
    Member

    I think it would be neat to get this display with plot_method="contour" to behave as follows:

    • for all response methods, always get contours at the class boundaries for any 2 pairs of classes (but I don't know how to do this);
    • for the continuous response methods (predict_proba and decision_function) add contour lines for different levels with different color intensities in addition to the class boundaries contour lines.
  3. lucyleeow commented on Feb 6, 2026

    @lucyleeow
    MemberAuthor

    I agree! @AnneBeyer are you interested in working on this?

  4. AnneBeyer commented on Feb 23, 2026

    @AnneBeyer
    Member

    The PR for fixing the levels issue is ready here: #33300.
    I will open a PR for this issue once that one is merged, to keep the conflicts to a minimum.

  5. AnneBeyer commented on Mar 4, 2026

    @AnneBeyer
    Member

    I played around with this a bit more.

    Here is a version with the class contour lines after the level fix (it simply plots the contour boundaries on top of the class ones (I left the contourf in for color reference))

    Image

    contour and contourf have an antialiased parameter, which will smooth the lines a bit when set to True, which I added as the default.

    Regarding the colors not matching a single class with contour: We could easily plot them in a single color like this (I hard-coded it to "black" with alpha=0.5 here, not sure if we should leave it colored for predict, though). Continuing what @lucyleeow also already mentioned above: We might need to separate the **kwargs into separate plot-func_args (also with the option of adding a scatter plot in mind).

    Image

    The only problem I don't know how to solve is the line width, which will increase for multiple overlapping contour lines. But since this mainly happens when n_classes is very high, I'm not sure how big a concern this should be.

    One other thing I noticed about the grid resolution is that we assume quadratic plots here (which is the case in the examples above, but might not necessarily be the case in other scenarios):

    xx0, xx1 = np.meshgrid(
    np.linspace(x0_min, x0_max, grid_resolution),
    np.linspace(x1_min, x1_max, grid_resolution),
    )

    An option could be to use something like this, which could require adapting the default value (though I'm not sure what the best option would be here and what to base this decision on):

    xx0, xx1 = np.meshgrid(
                np.linspace(x0_min, x0_max, int(x0_max - x0_min) * grid_resolution),
                np.linspace(x1_min, x1_max, int(x1_max - x1_min) * grid_resolution),
            )

    The plots above were created with this approach and grid_resolution=50.

    I will open a draft PR for the first version tomorrow, but I already wanted to get this out here in case you have a moment left to think about this, @lucyleeow.

  6. lucyleeow commented on Mar 5, 2026

    @lucyleeow
    MemberAuthor

    Some quick responses, I will have a better look tomorrow.

    I hard-coded it to "black" with alpha=0.5 here, not sure if we should leave it colored for predict, though

    I would vote for still having it as one colour, even for 'predict' as the number of colours won't always match the number of classes and they don't necessarily delineate a single class either.

    The only problem I don't know how to solve is the line width, which will increase for multiple overlapping contour lines.

    Are you sure this is line width and not just transparency? Looking at the image zoomed in, it seems some lines are darker but they are all the same width? It would make sense with: "black" with alpha=0.5 - we could just set alpha to 1?

  7. AnneBeyer commented on Mar 6, 2026

    @AnneBeyer
    Member

    Are you sure this is line width and not just transparency?

    I think it depends on the resolution. Here is a version with grid_resolution 100x140 (which is close to the previous default) with alpha = 1 for the left two:

    Image

    But it goes away with larger grid size, so I'd leave it to the user to set this accordingly if necessary.

  8. AnneBeyer commented on Mar 6, 2026

    @AnneBeyer
    Member

    I would vote for still having it as one colour, even for 'predict' as the number of colours won't always match the number of classes and they don't necessarily delineate a single class either.

    I think this makes sense. Should we then add a warning when multiclass_colors are passed for the case of predict + contour that the given colors will be ignored for the class boundaries?

    I will open a draft PR and we can discuss the details there.

  9. moved this from Todo to In progress in Labson Mar 6, 2026
  10. lucyleeow commented on Mar 12, 2026

    @lucyleeow
    MemberAuthor

    But it goes away with larger grid size,

    I looked into this more and you're right. Using the iris example above:

    Image

    I think it is because contour interpolates the grid values - I think the top boundary with the adjacent orange and blue lines, is the boundary between class 0 and class 2. Contour docs says it uses the "marching squares" algorithm, which from the wiki: "Apply linear interpolation along the boundaries of the cell to calculate the exact contour position."

    While there is effectively a 'hard' boundary going from 0 to 2, the interpolation adds a 1 in between, so one line shows the boundary between 0 and 1 and the other shows the boundary between 1 and 2.

    I don't think there is an easy way to fix this, 'contour' just isn't designed for discrete values. Claude suggested that we can plot differences in predicted score values of each class pair - but I think it is overkill.

    At higher resolutions the interpolation is closer and the effect is less visible.

  11. moved this from In progress to Todo in Labson Mar 23, 2026
  12. moved this from Todo to Done in Labson Apr 13, 2026
  13. jshn9515 commented on Jul 2, 2026

    @jshn9515

    Hi! I'm a little late to this RFC. I'm the author of #31553.

    The motivation behind #31553 was to restore the ability to plot decision boundaries, which was the default behavior in v1.6.0 but changed in v1.7.0. The current behavior is exactly what I was hoping for. Thanks for the great work!

    By the way, I have a suggestion regarding the API. It would be great if users could customize the boundary and surface independently. I would propose an API along the following lines:

    @classmethod
    def from_estimator(
        cls,
        estimator,
        X,
        *,
        grid_resolution=100,
        eps=1.0,
        plot_method="contourf",
        response_method="auto",
        class_of_interest=None,
        target_colors=None,
        show_class_boundaries=False,  # new
        response_kwargs=None,         # new
        boundary_kwargs=None,         # new
        xlabel=None,
        ylabel=None,
        ax=None,
    ):
    show_class_boundaries : bool, default=False
        Whether to overlay boundaries between predicted classes.
    
        The boundaries are computed from discrete predictions and are independent
        of the main response displayed by `plot_method`.
    
    response_kwargs : dict, default=None
        Additional keyword arguments passed to the plotting call for the main
        response, such as `alpha`, `levels`, or `zorder`.
    
    boundary_kwargs : dict, default=None
        Additional keyword arguments passed when drawing class boundaries, such as
        `colors`, `linewidths`, `linestyles`, or `zorder`.
    

    This would provide separate and more explicit control over the response surface and the class boundaries, including their colors and plotting styles.

    There is still one question: when plot_method="contour" and response_method="predict", show_class_boundaries would effectively need to be True; otherwise, there would be nothing to draw. Perhaps show_class_boundaries should instead accept "auto"?

    If needed, I can open a separate issue to discuss the API design in more detail.

    cc @lucyleeow @AnneBeyer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions