Skip to content

DecisionBoundaryDisplay with response_method="predict" has inconsistent handling for the colormap in the multiclass case #32872

Closed

Description

@ogrisel

Describe the bug

This issue was discovered while reviewing #32867, but since it's not directly related, let's open a dedicated issue to avoid derailing the original discussion.

As can be seen in the plots below, passing multiclass_colors="gist_rainbow" has no impact when response_method="predict" but I don't see any reason why it wouldn't be the case.

Image

I think we should refactor the code to have consistent colormap configuration for all the response methods (in particular for the multiclass case).

Steps/Code to Reproduce

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],
    ]
)
target = np.arange(data.shape[0])
clf = LogisticRegression().fit(data, target)

cmap = "gist_rainbow"
_, axes = plt.subplots(nrows=3, ncols=3, figsize=(12, 12), constrained_layout=True)
for plot_method_idx, plot_method in enumerate(["contourf", "contour", "pcolormesh"]):
    for response_method_idx, response_method in enumerate(
        ["predict_proba", "decision_function", "predict"]
    ):
        ax = axes[plot_method_idx, response_method_idx]
        display = DecisionBoundaryDisplay.from_estimator(
            clf,
            data,
            multiclass_colors=cmap,
            response_method=response_method,
            plot_method=plot_method,
            ax=ax,
            alpha=0.5,
        )
        ax.scatter(
            data[:, 0],
            data[:, 1],
            c=target.astype(int),
            edgecolors="black",
            cmap=cmap,
        )
        ax.set_title(f"plot_method={plot_method}\nresponse_method={response_method}")

Expected Results

I would expect the colored areas of the right most columns to also use the "gist_rainbow" colormap as the other columns.

Actual Results

The right most column seems to ignore the multiclass_colors argument and falls back to the default "viridis" colormap which is not very well suited for multiclass problems with a large number of classes.

Versions

System:
    python: 3.13.7 | packaged by conda-forge | (main, Sep  3 2025, 14:24:46) [Clang 19.1.7 ]
executable: /Users/ogrisel/miniforge3/envs/dev/bin/python3.13
   machine: macOS-15.6.1-arm64-arm-64bit-Mach-O

Python dependencies:
      sklearn: 1.9.dev0
          pip: 25.2
   setuptools: 80.9.0
        numpy: 2.3.3
        scipy: 1.16.3
       Cython: 3.1.4
       pandas: 3.0.0.dev0+2566.g2bb3fef887
   matplotlib: 3.10.6
       joblib: 1.5.2
threadpoolctl: 3.6.0

Built with OpenMP: True

threadpoolctl info:
       user_api: blas
   internal_api: openblas
    num_threads: 10
         prefix: libopenblas
       filepath: /Users/ogrisel/miniforge3/envs/dev/lib/libopenblas.0.dylib
        version: 0.3.30
threading_layer: openmp
   architecture: VORTEX

       user_api: openmp
   internal_api: openmp
    num_threads: 10
         prefix: libomp
       filepath: /Users/ogrisel/miniforge3/envs/dev/lib/libomp.dylib
        version: None

Activity

  1. ogrisel commented on Dec 9, 2025

    @ogrisel
    MemberAuthor
  2. changed the title [-]`DecisionBoundaryDisplay` with `response_method="predict"` has consistent handling for the colormap in the multiclass case[/-] [+]`DecisionBoundaryDisplay` with `response_method="predict"` has inconsistent handling for the colormap in the multiclass case[/+] on Dec 9, 2025
  3. AnneBeyer commented on Dec 9, 2025

    @AnneBeyer
    Member

    Yes, I also came across this here, and it should indeed be fixed separately.

    @lucyleeow let me know if you want to address it or if I should give it a try.

  4. PR-HARIHARAN commented on Dec 10, 2025

    @PR-HARIHARAN
  5. ogrisel commented on Dec 10, 2025

    @ogrisel
    Author
  6. moved this to Todo in Labson Dec 11, 2025
  7. AnneBeyer commented on Dec 12, 2025

    @AnneBeyer
    Member

    Starting to look into this, I have a general question:

    What is the reason for handling colors by different parameters in the binary (currently including multiclass predict) and multiclass cases?
    I find it a bit confusing that one has to use the 'mpl' parameters in the binary case, but multiclass_colors otherwise, where cmap/colors will be ignored/overwritten if given.
    I think it could be changed to use one parameter (class_colors?) to set the colors/color palette in all case, and make the distinction internally. I'm just not sure if I'm overlooking anything here? @lucyleeow

  8. Pushkar881 commented on Dec 14, 2025

    @Pushkar881

    It seems that I can replicate that too. While using response_method="predict", the argument multiclass_colors does not appear to make any difference at all, unlike other response methods.

    As this issue is already allocated, I just wanted to clarify if this is supposed to work in this way or it is expected behavior. Happy to assist with testing or reviewing if required.

  9. lucyleeow commented on Dec 15, 2025

    @lucyleeow
    Member

    Responding to some of the comments from #31693, as well here to have the discussion in a single place.

    With regard to the 2 issues below:

    There is a detailed handling of colors using the multiclass_colors parameter, but this is only taken into account when multiclass predict_proba or decision_function are used. The distinction is made based on the output shape, and predict will always have self.response.ndim == 2, but can still be multiclass.

    (from #31693 (comment))

    What is the reason for handling colors by different parameters in the binary (currently including multiclass predict) and multiclass cases?

    (From above)

    I can't think of a reason why multiclass predict should be handled differently. I think it was an oversight as #29797 was originally about adding support for plotting of multiclass decision_function and predict_probas (predict was already supported), we when the multiclass_colors parameter was added later in the PR, we just didn't think about predict.

    What is the reason for handling colors by different parameters in the binary (currently including multiclass predict) and multiclass cases?

    Again, just because we were thinking about multiclass. I would be happy to deprecate multiclass_colors for class_colors (or maybe label_colors?). Current input options:

            * list: list of Matplotlib
              `color <https://matplotlib.org/stable/users/explain/colors/colors.html#colors-def>`_
              strings, of length `n_classes`
            * str: name of :class:`matplotlib.colors.Colormap`
            * None: 'viridis' colormap is used to sample colors
    

    I think the default multiclass_colors value currently (tab10) would be reasonable for binary case, as the first 2 colors are blue and orange. I do think we should advise against use of a string mpl colormap for use in the binary case in the docs, but probably fine if allow it.


    I see several issues:

    1. current issue: predict ignores multiclass_colors
    2. DecisionBoundaryDisplay.from_estimator only displays up to 7 distinct colours #32866 - mpl bug when number of classes >7, that is propagated
    3. Zooming in on an area of the plot means we calculate the responses only for a subset of the data points, which doesn't necessarily include all classes, and results in inconsistent colors: ENH: Add xlim/ylim parameters to DecisionBoundaryDisplay.from_estimator #31693 (comment)
    4. multiclass_colors -> class_colors (or maybe label_colors?)

    It seems that items 1,2,3 all would benefit from knowing the full number of classes, which we can obtain from the fitted estimator.classes_ (and would avoid expensive calls to np.unique, which is done in #32867). There are 2 ways we could do this, pass number of classes (i.e. n_responses, which we currently use in plot) to plot (probably via class instantiation in from_estimator), or move the color and level logic (currently handled by plot) to from_estimator.
    I think the former (passing n_responses/n_classes) to plot would be preferable (it certainly would reduce the git diff) but you may have a better feel @AnneBeyer when you implement this.

    Also I think issue 1 should be addressed first - it seems a more important bug to fix, and the restructure (i.e. passing of n_classes would be useful for subsequent issues).

  10. Pushkar881 commented on Dec 15, 2025

    @Pushkar881
  11. lucyleeow commented on Dec 15, 2025

    @lucyleeow
  12. AnneBeyer commented on Dec 15, 2025

    @AnneBeyer
    Member

    Thank you for your thoughts on this, @lucyleeow!
    I agree, I'll start with a fix for the current issue, and my plan is also to add n_classes (or maybe n_labels?) to the class constructor as in your first suggestion.

    Then we can look into the rest separately.

  13. lucyleeow commented on Dec 15, 2025

    @lucyleeow
    Member

    I think slight preference for n_classes because we call it estimator.classes_

  14. AnneBeyer commented on Dec 16, 2025

    @AnneBeyer
    Member

    It seems that items 1,2,3 all would benefit from knowing the full number of classes, which we can obtain from the fitted estimator.classes_ (and would avoid expensive calls to np.unique, which is done in #32867).

    One problem I ran into with this approach: DecisionBoundaryDisplay also supports regressors, which don't have n_classes, so in this case we do need to fall back to the unique values of y, right?

  15. AnneBeyer commented on Dec 16, 2025

    @AnneBeyer
    Member

    Two other related side issues:

    1. class_of_interest should also be considered with multiclass predict, right?
      Currently, it can only be set with predict_proba or decision_function and ignored otherwise, but I think it also makes sense in the other multiclass case. I would address this in a separate PR, in order to keep things as simple as possible.

    2. If class_of_interest is set (with predict_proba or decision_function), the colormap is currently also ignored, (as this converts it into a binary problem), which should be fixed once we address Issue 4 in the comment above

  16. lucyleeow commented on Dec 17, 2025

    @lucyleeow
    Member

    One problem I ran into with this approach: DecisionBoundaryDisplay also supports regressors, which don't have n_classes, so in this case we do need to fall back to the unique values of y, right?

    Indeed. It also supports clustering and outlier detection estimators which also do not have classes attribute.

    class_of_interest should also be considered with multiclass predict, right?
    Currently, it can only be set with predict_proba or decision_function and ignored otherwise, but I think it also makes sense in the other multiclass case. I would address this in a separate PR, in order to keep things as simple as possible.

    +1

  17. lucyleeow commented on Dec 23, 2025

    @lucyleeow
    Member

    One problem I ran into with this approach: DecisionBoundaryDisplay also supports regressors, which don't have n_classes, so in this case we do need to fall back to the unique values of y, right?

    Thinking about this more, I realise we will not be able to solve the problem of not all 'prediction' values being represented when we zoom in by setting x/ylim (#31693 (comment)).

    For regression estimators this problem is definitely not solve-able - I do question the usefulness of DecisionBoundaryDisplay on many regression problems though. Not sure of the best approach here, cc @glemaitre in case he has some advice.

    For clustering estimators, I think labels_ is standard - in ClusterMixin you have:

    self.fit(X, **kwargs)
    return self.labels_

    (and of course for outlier detection, you can only have 2 states, outlier or inlier)

  18. moved this from Todo to In progress in Labson Jan 5, 2026
  19. moved this from In progress to In progress - High Priority in Labson Jan 6, 2026
  20. moved this from In progress - High Priority to In progress in Labson Jan 6, 2026
  21. moved this from In progress to Done in Labson Feb 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions