Repository navigation
Description
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:
instead of contour lines showing how continuous predicted values change, over the region where that class dominates:
(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:
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)
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity
lucyleeow commentedon Jan 20, 2026
I see similar issues were discussed here: #32867 (comment) and #32867 (comment)
I felt something was 'weird' about the
contourimplementation 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:
levelsto be array of class ints, when plotting thresholded integer response values, so we have a reasonable number of contour linesEdit:
Just adding Annes plot from #32867 (comment), for ease of viewing:
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)
ogrisel commentedon Feb 6, 2026
I think it would be neat to get this display with
plot_method="contour"to behave as follows:predict_probaanddecision_function) add contour lines for different levels with different color intensities in addition to the class boundaries contour lines.lucyleeow commentedon Feb 6, 2026
I agree! @AnneBeyer are you interested in working on this?
AnneBeyer commentedon Feb 23, 2026
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.
AnneBeyer commentedon Mar 4, 2026
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
contourboundaries on top of the class ones (I left thecontourfin for color reference))contourandcontourfhave anantialiasedparameter, which will smooth the lines a bit when set toTrue, 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"withalpha=0.5here, not sure if we should leave it colored forpredict, though). Continuing what @lucyleeow also already mentioned above: We might need to separate the**kwargsinto separateplot-func_args(also with the option of adding a scatter plot in mind).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_classesis 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):
scikit-learn/sklearn/inspection/_plot/decision_boundary.py
Lines 561 to 564 in 0b8b024
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):
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.
lucyleeow commentedon Mar 5, 2026
Some quick responses, I will have a better look tomorrow.
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.
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?
AnneBeyer commentedon Mar 6, 2026
I think it depends on the resolution. Here is a version with grid_resolution 100x140 (which is close to the previous default) with
alpha = 1for the left two:But it goes away with larger grid size, so I'd leave it to the user to set this accordingly if necessary.
AnneBeyer commentedon Mar 6, 2026
I think this makes sense. Should we then add a warning when
multiclass_colorsare passed for the case ofpredict + contourthat the given colors will be ignored for the class boundaries?I will open a draft PR and we can discuss the details there.
lucyleeow commentedon Mar 12, 2026
I looked into this more and you're right. Using the iris example above:
I think it is because
contourinterpolates 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.
jshn9515 commentedon Jul 2, 2026
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:
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"andresponse_method="predict",show_class_boundarieswould effectively need to beTrue; otherwise, there would be nothing to draw. Perhapsshow_class_boundariesshould instead accept"auto"?If needed, I can open a separate issue to discuss the API design in more detail.
cc @lucyleeow @AnneBeyer