Repository navigation
MNT fix and refactor color handling in DecisionBoundaryDisplay - Part 1 - #33419
Conversation
| ({"multiclass_colors": "not_cmap"}, "it must be a valid Matplotlib colormap"), | ||
| ({"multiclass_colors": ["red", "green"]}, "it must be of the same length"), | ||
| ( | ||
| {"multiclass_colors": ["red", "green", "blue", "yellow"]}, |
There was a problem hiding this comment.
Added edge case for too many values (could also be accepted and select the first n elements, but currently we check for exact length)
| (None, 11), | ||
| ("plasma", 3), | ||
| ("Blues", 3), | ||
| ("tab20", 20), |
There was a problem hiding this comment.
Edge case with just enough colors
| cmap = mpl.pyplot.get_cmap(multiclass_colors, len(clf.classes_)) | ||
| multiclass_colors = "gist_rainbow" | ||
|
|
||
| if multiclass_colors in ["tab10", "tab20"]: |
There was a problem hiding this comment.
I adapted the test to match the new simplified behaviour in the new _select_colors function
| f"n_features must be equal to 2. Got {num_features} instead." | ||
| ) | ||
|
|
||
| if ( |
There was a problem hiding this comment.
This part is now integrated in _select_colors
| <...> | ||
| >>> plt.show() | ||
| """ | ||
| check_matplotlib_support(f"{cls.__name__}.from_estimator") |
There was a problem hiding this comment.
This was only needed for validating multilcass_colors, which now happens in the new function
Co-authored-by: Olivier Grisel <[email protected]>
|
Since this is mostly an internal refactoring with little user facing impacts, let's merge to unlock the subsequent items in the linked issue TODO list. |
lucyleeow
left a comment
There was a problem hiding this comment.
Sorry late again.
I think we can test the specific colors as suggested (https://github.com/scikit-learn/scikit-learn/pull/33300/changes#r2866814374)
In particular we should check that for qualitative colormaps we are picking the first n_classes colors and not sampling evenly (ref: https://github.com/scikit-learn/scikit-learn/pull/33015/changes#r2703134927)
Maybe we could add some of the test fixes before moving on?
| - If `None`, defaults to `"tab10"` when `n_classes <= 10`, otherwise | ||
| `"gist_rainbow"`. | ||
| - If `str`, interpreted as a Matplotlib colormap name. | ||
| - If `list`, each entry must be a valid Matplotlib color-like value. |
There was a problem hiding this comment.
Could we add a reference to mpl is_color_like function, just to help anyone reading the code.
| "different colormap or provide a list of colors via " | ||
| "'multiclass_colors'." | ||
| ) | ||
| if cmap.N < 256: |
There was a problem hiding this comment.
I think this is a fine way to differentiate between qualitative and continuous colormaps and and I can't see where it would fail - but I think a 'safer' way may be with class.
I think qualitative maps are ListedColormap (note the colors attribute, which we do use later) - it's hard to find documentation but it is mentioned here: https://matplotlib.org/stable/gallery/color/individual_colors_from_cmap.html#extracting-colors-from-a-discrete-colormap
Continuous colormaps are LinearSegmentedColormap - note the default of N=256
WDYT?
There was a problem hiding this comment.
I double checked this, but related to my comment above, not all continuous colormaps are of type LinearSegmentedColormap.
Inspecting the cmaps in matplotlib's colormap reference (see code below for reference) shows that there are also some ListedColormaps in {'Miscellaneous', 'Diverging', 'Cyclic', 'Qualitative', 'Perceptually Uniform Sequential'}, which will have the colors attribute, but also 256 colors, so sampling the first n_colors (which we do in this case) will result in almost indistinguishable colors (all purples in the case of viridis, for example). This is why I went for the approach above.
import matplotlib as mpl
import matplotlib.pyplot as plt
# list taken from https://matplotlib.org/stable/gallery/color/colormap_reference.html
cmaps = [('Perceptually Uniform Sequential', [
'viridis', 'plasma', 'inferno', 'magma', 'cividis']),
('Sequential', [
'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']),
('Sequential (2)', [
'binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', 'pink',
'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia',
'hot', 'afmhot', 'gist_heat', 'copper']),
('Diverging', [
'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',
'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic',
'berlin', 'managua', 'vanimo']),
('Cyclic', ['twilight', 'twilight_shifted', 'hsv']),
('Qualitative', [
'Pastel1', 'Pastel2', 'Paired', 'Accent',
'Dark2', 'Set1', 'Set2', 'Set3',
'tab10', 'tab20', 'tab20b', 'tab20c']),
('Miscellaneous', [
'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern',
'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg',
'gist_rainbow', 'rainbow', 'jet', 'turbo', 'nipy_spectral',
'gist_ncar'])]
listed_cmaps=set()
for cmap_category, cmap_list in cmaps:
for cmap in cmap_list:
if type(plt.get_cmap(cmap)) == mpl.colors.ListedColormap:
print(f"{cmap}({cmap_category})\ncolor counts:{plt.get_cmap(cmap).N}")
print(listed_cmaps)There was a problem hiding this comment.
Ah interesting, thanks for taking the time to explain.
|
|
||
| if ax is None: | ||
| _, ax = plt.subplots() | ||
| _, ax = mpl.pyplot.subplots() |
There was a problem hiding this comment.
Locally this causes problems for me. It seems that importing matplotlib does not automatically import pyplot:
In [1]: import matplotlib as mpl
In [2]: _, ax = mpl.pyplot.subplots()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[2], line 1
----> 1 _, ax = mpl.pyplot.subplots()
File ~/miniconda3/envs/sklearn-env/lib/python3.13/site-packages/matplotlib/_api/__init__.py:217, in caching_module_getattr.<locals>.__getattr__(name)
215 if name in props:
216 return props[name].__get__(instance)
--> 217 raise AttributeError(
218 f"module {cls.__module__!r} has no attribute {name!r}")
AttributeError: module 'matplotlib' has no attribute 'pyplot'The tests indeed all pass, but I wonder if that is because pyplot was already imported by the time decision boundary tests are run?
There was a problem hiding this comment.
I had the same problem after this was merged, and wanted to revert it in the next PR, but at some point I couldn't reproduce it anymore. Inspecting this again, I now realize that it was because I imported pyplot at another point in my notebook to call plt.close("all"), so I'll open a PR to revert this.
Reference Issues/PRs
Towards #33115
Specifically, this implements checkboxes 1, 2, part of 3, and 5 (see next section for details)
What does this implement/fix? Explain your changes.
This PR moves all parts related to color selection based on 'multiclass_colors' into a sepparate function (3,5), unifies and simplifies the color selection mechanism (2) and adds a check that enough distinct colors are available in the given colormap (1).
It also adds a non-regression test for the last point, which is the only functionality change.
See also the comments in the code for more details.
@ogrisel @lucyleeow @StefanieSenger @antoinebaker
AI usage disclosure
I used AI assistance for:
Any other comments?
Unrelated small change:
I converted the error messages in
sklearn/utils/_optional_dependencies.pyto f-strings.