Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

ENH: Display parameters in HTML representation #30763

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 145 commits into from
May 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
145 commits
Select commit Hold shift + click to select a range
f1540bd
first try
DeaMariaLeon Jan 31, 2025
d4e6359
wip
DeaMariaLeon Jan 31, 2025
53e26d6
wip
DeaMariaLeon Jan 31, 2025
27a2934
wip
DeaMariaLeon Jan 31, 2025
1363a90
wip
DeaMariaLeon Jan 31, 2025
1f44e8d
wip
DeaMariaLeon Jan 31, 2025
ae18394
wip
DeaMariaLeon Jan 31, 2025
bf1774b
wip
DeaMariaLeon Feb 3, 2025
fbddf12
wip
DeaMariaLeon Feb 3, 2025
3cedcf4
changed button color
DeaMariaLeon Feb 3, 2025
65a6fe9
Merge remote-tracking branch 'upstream/main' into get-params
DeaMariaLeon Feb 3, 2025
2e7964d
removed svg - use fontawesome
DeaMariaLeon Feb 3, 2025
4fff750
wip
DeaMariaLeon Feb 6, 2025
5da5276
wip
DeaMariaLeon Feb 6, 2025
719871f
single estimator - broken pipe
DeaMariaLeon Feb 6, 2025
6fb104b
fixed pipeline - I think
DeaMariaLeon Feb 7, 2025
ea83b49
changing size colors
DeaMariaLeon Feb 7, 2025
4de9ee0
removed name
DeaMariaLeon Feb 7, 2025
79c5133
script at the bottom
DeaMariaLeon Feb 8, 2025
0f7fae9
added temporary Copied message
DeaMariaLeon Feb 8, 2025
2bcf71a
removed console log
DeaMariaLeon Feb 8, 2025
9f580f7
correct margin
DeaMariaLeon Feb 10, 2025
38bc5b5
found non-defaults params
DeaMariaLeon Feb 11, 2025
6e4c191
Font color black when non-default
DeaMariaLeon Feb 11, 2025
6a98da6
added padding to summary
DeaMariaLeon Feb 11, 2025
d58137c
correct color
DeaMariaLeon Feb 21, 2025
15a067f
copy button on the left, gave min-width
DeaMariaLeon Feb 21, 2025
235cc59
aligned text
DeaMariaLeon Feb 24, 2025
491b06a
work on green mesage
DeaMariaLeon Feb 26, 2025
aaae98f
wip
DeaMariaLeon Feb 26, 2025
ded88f4
wip
DeaMariaLeon Feb 26, 2025
430f6a0
draft param_prefix
glemaitre Mar 3, 2025
8b475eb
Merge pull request #2 from glemaitre/params_nested
DeaMariaLeon Mar 4, 2025
8c2588e
added quotation marks to str param, removed repeating code
DeaMariaLeon Mar 4, 2025
add9e04
added method names
DeaMariaLeon Mar 4, 2025
eeb39b8
added method table
DeaMariaLeon Mar 4, 2025
63c0c0d
styled method table rows
DeaMariaLeon Mar 5, 2025
8997062
added methods params
DeaMariaLeon Mar 5, 2025
0e0dffb
Added missing methods
DeaMariaLeon Mar 5, 2025
f89e87d
Escaped methods params
DeaMariaLeon Mar 6, 2025
e9907df
Escaped methods params
DeaMariaLeon Mar 6, 2025
ca81c1c
adding padding
DeaMariaLeon Mar 7, 2025
00ad17a
cleaned up get params css
DeaMariaLeon Mar 7, 2025
ff7fbcc
Cleaned up code
DeaMariaLeon Mar 7, 2025
34c882f
adding hover
DeaMariaLeon Mar 10, 2025
24321fc
wip
DeaMariaLeon Mar 10, 2025
e5773dc
split javascript file
DeaMariaLeon Mar 11, 2025
6cefa36
clean up css a bit
DeaMariaLeon Mar 12, 2025
e2b27ad
Revert "wip"
DeaMariaLeon Mar 12, 2025
7b42074
js moved to estimator_html_repr.py
DeaMariaLeon Mar 12, 2025
22671cb
stop tracking js file
DeaMariaLeon Mar 12, 2025
bfd3287
moved css loading to _estimator_html_repr.py
DeaMariaLeon Mar 14, 2025
3fd9607
fixing columntransf
DeaMariaLeon Mar 14, 2025
6e2f121
fixed long name on columtrnaformer
DeaMariaLeon Mar 15, 2025
ea1b36e
[doc build]
DeaMariaLeon Mar 18, 2025
abe463e
doc build
DeaMariaLeon Mar 18, 2025
99b1cde
Merge remote-tracking branch 'origin/main' into get-params
DeaMariaLeon Mar 18, 2025
78c9ebb
[doc build]
DeaMariaLeon Mar 18, 2025
5b5bb2c
sanitizing params
DeaMariaLeon Mar 25, 2025
07354e6
remove extra spaces in table values
DeaMariaLeon Mar 25, 2025
6296135
correct sanitize
DeaMariaLeon Mar 25, 2025
2b31b74
correct methods for table
DeaMariaLeon Mar 26, 2025
a7a796e
Removed methods from HTML diagram as requested
DeaMariaLeon Apr 3, 2025
9ef2b90
wip to add a new _get_params()
DeaMariaLeon Apr 3, 2025
edf9667
Keep get_params original dict per request
DeaMariaLeon Apr 3, 2025
7349c6e
Passing non_default values to ParamsDict
DeaMariaLeon Apr 3, 2025
d5d07ae
Added HTML TEMPLATE
DeaMariaLeon Apr 3, 2025
3defd7b
Improve variable names - maybe?
DeaMariaLeon Apr 4, 2025
dbecf02
clean up a bit added short docstring
DeaMariaLeon Apr 4, 2025
cec643a
Added ellipsis - when param value > 50
DeaMariaLeon Apr 4, 2025
31c3497
adding pretty print - WIP
DeaMariaLeon Apr 4, 2025
71567d3
added important to css so user agent style is not taken
DeaMariaLeon Apr 8, 2025
cd7528c
Remove for loop
DeaMariaLeon Apr 8, 2025
0f0f168
Moving out javascript file from estimator_html_repr
DeaMariaLeon Apr 8, 2025
89e88fd
Read path with Path
DeaMariaLeon Apr 8, 2025
39f70a6
removed extra pre label
DeaMariaLeon Apr 8, 2025
fc0d0d8
Fix fitted hover color - removed commented css style
DeaMariaLeon Apr 11, 2025
7fae07b
Document params in _write_label_html
DeaMariaLeon Apr 14, 2025
7282bf3
Fix pretty print background
DeaMariaLeon Apr 15, 2025
f86be16
Adding tests WIP
DeaMariaLeon Apr 16, 2025
0e4fa18
wip
DeaMariaLeon Apr 16, 2025
679b56e
WIP to add name details to ColumnTransformer elements
DeaMariaLeon Apr 17, 2025
3fdfa49
Adding name_details
DeaMariaLeon Apr 17, 2025
1ebd0ee
fixing test stacking classifier
DeaMariaLeon Apr 17, 2025
3a7b588
clearer name_details logic.. maybe
DeaMariaLeon Apr 17, 2025
bf0042f
Check if estimator has _get_params_html
DeaMariaLeon Apr 18, 2025
5fdd295
Improve name_details
DeaMariaLeon Apr 22, 2025
33f7b94
After feedback - partial
DeaMariaLeon Apr 23, 2025
d01345d
fixing after feedback - 2
DeaMariaLeon Apr 23, 2025
14bc919
replaced pprint, added ReprHTMLMixin, fixed a docstring test
DeaMariaLeon Apr 23, 2025
8b59a8e
Adding docstrings
DeaMariaLeon Apr 23, 2025
c126485
Reworked reprlib on _get_params_html
DeaMariaLeon Apr 24, 2025
c7c4161
sanitize value
DeaMariaLeon Apr 24, 2025
01d7b60
Adding mini-test
DeaMariaLeon Apr 25, 2025
a93f058
Merge remote-tracking branch 'upstream/main' into get-params
DeaMariaLeon Apr 28, 2025
7a46b87
Wip on tests
DeaMariaLeon Apr 29, 2025
2bbae45
wip
DeaMariaLeon Apr 29, 2025
a1ce72a
ordering params and corrected func name after feedback
DeaMariaLeon May 2, 2025
375b7a5
after merge
DeaMariaLeon May 2, 2025
843d615
correcting css after feedback
DeaMariaLeon May 2, 2025
2cb0ec6
refactor after feedback
DeaMariaLeon May 2, 2025
c602955
Adding missing files
DeaMariaLeon May 2, 2025
8502753
Adding test for repr_html
DeaMariaLeon May 5, 2025
780697a
empty commit to run CI tests
DeaMariaLeon May 5, 2025
e5344cc
adding repr_mimebundle test
DeaMariaLeon May 5, 2025
94c8d8b
adding context to test
DeaMariaLeon May 5, 2025
e75546a
fixing test
DeaMariaLeon May 6, 2025
d2ad614
Merge remote-tracking branch 'upstream/main' into get-params
DeaMariaLeon May 6, 2025
306d50e
Merge remote-tracking branch 'upstream/main' into get-params
DeaMariaLeon May 6, 2025
d670878
MAINT: more refactoring by moving more files into _repr_html
glemaitre May 7, 2025
06afd24
fix import
glemaitre May 7, 2025
36a9748
fix internal import
glemaitre May 7, 2025
ccc4517
Merge pull request #3 from glemaitre/move_file
DeaMariaLeon May 7, 2025
d08263a
Merge remote-tracking branch 'upstream/main' into get-params
DeaMariaLeon May 9, 2025
242b656
Modified sklearn.base after feedback
DeaMariaLeon May 9, 2025
3222e0f
moving test
DeaMariaLeon May 9, 2025
5e7c898
renamed and moved test_estimator_html_repr.py
DeaMariaLeon May 9, 2025
9ea4c71
Adding docstrings from feedback
DeaMariaLeon May 9, 2025
fa966a5
small fix test_base
DeaMariaLeon May 9, 2025
b9c2365
Forgot this one too
DeaMariaLeon May 9, 2025
37e1523
add __init__.py in the tests folder
glemaitre May 9, 2025
9220ca0
Merge remote-tracking branch 'upstream/main' into get-params
DeaMariaLeon May 9, 2025
8d1fee7
Merge remote-tracking branch 'origin/get-params' into get-params
DeaMariaLeon May 9, 2025
73c2c4f
adding tests
DeaMariaLeon May 9, 2025
0fe9439
cleaned up after feedback
DeaMariaLeon May 9, 2025
5c8d7c9
changed test, cleaned up css - after feedback
DeaMariaLeon May 9, 2025
770f5d6
Added fragment for whats_new
DeaMariaLeon May 9, 2025
526d0ae
Update sklearn/utils/_repr_html/tests/test_estimator.py
glemaitre May 9, 2025
cc50796
[doc build] trigger doc
DeaMariaLeon May 12, 2025
da13276
Merge remote-tracking branch 'upstream/main' into get-params
DeaMariaLeon May 12, 2025
7863242
[doc build] trigger doc
DeaMariaLeon May 12, 2025
b173b7e
Merge remote-tracking branch 'origin/get-params' into get-params
DeaMariaLeon May 12, 2025
0d94639
[doc build] trigger doc
DeaMariaLeon May 12, 2025
8e2e026
replace fontawesome with base64
glemaitre May 12, 2025
8a457af
tweak css a bit more
glemaitre May 12, 2025
749f920
Merge pull request #4 from glemaitre/replace_font_awesome
DeaMariaLeon May 13, 2025
f40b030
[doc build] trigger doc
DeaMariaLeon May 13, 2025
851a192
Fix docstring
DeaMariaLeon May 13, 2025
17804a2
[doc build] trigger doc
DeaMariaLeon May 13, 2025
e0ca836
Adding padding
DeaMariaLeon May 13, 2025
2110981
Merge remote-tracking branch 'upstream/main' into get-params
DeaMariaLeon May 13, 2025
736bc6b
[doc build] trigger doc
DeaMariaLeon May 13, 2025
f0e7224
[doc build] trigger doc and Merge remote-tracking branch 'upstream/main'
DeaMariaLeon May 13, 2025
e8dd6b8
Added docstring to _repr_html_inner
DeaMariaLeon May 20, 2025
3d5804f
Merge remote-tracking branch 'upstream/main' into get-params
DeaMariaLeon May 20, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
- :class:`base.BaseEstimator` now has a parameter table added to the
estimators HTML representation that can be visualized with jupyter.
By :user:`Guillaume Lemaitre <glemaitre>` and
:user:`Dea María Léon <DeaMariaLeon>`
97 changes: 65 additions & 32 deletions 97 sklearn/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,12 @@
from . import __version__
from ._config import config_context, get_config
from .exceptions import InconsistentVersionWarning
from .utils._estimator_html_repr import _HTMLDocumentationLinkMixin, estimator_html_repr
from .utils._metadata_requests import _MetadataRequester, _routing_enabled
from .utils._missing import is_scalar_nan
from .utils._param_validation import validate_parameter_constraints
from .utils._repr_html.base import ReprHTMLMixin, _HTMLDocumentationLinkMixin
from .utils._repr_html.estimator import estimator_html_repr
from .utils._repr_html.params import ParamsDict
from .utils._set_output import _SetOutputMixin
from .utils._tags import (
ClassifierTags,
Expand Down Expand Up @@ -150,7 +153,7 @@ def _clone_parametrized(estimator, *, safe=True):
return new_object


class BaseEstimator(_HTMLDocumentationLinkMixin, _MetadataRequester):
class BaseEstimator(ReprHTMLMixin, _HTMLDocumentationLinkMixin, _MetadataRequester):
"""Base class for all estimators in scikit-learn.

Inheriting from this class provides default implementations of:
Expand Down Expand Up @@ -194,6 +197,8 @@ class BaseEstimator(_HTMLDocumentationLinkMixin, _MetadataRequester):
array([3, 3, 3])
"""

_html_repr = estimator_html_repr

@classmethod
def _get_param_names(cls):
"""Get parameter names for the estimator"""
Expand Down Expand Up @@ -249,6 +254,64 @@ def get_params(self, deep=True):
out[key] = value
return out

DeaMariaLeon marked this conversation as resolved.
Show resolved Hide resolved
def _get_params_html(self, deep=True):
DeaMariaLeon marked this conversation as resolved.
Show resolved Hide resolved
"""
Get parameters for this estimator with a specific HTML representation.

Parameters
----------
deep : bool, default=True
If True, will return the parameters for this estimator and
contained subobjects that are estimators.

Returns
-------
params : ParamsDict
Parameter names mapped to their values. We return a `ParamsDict`
dictionary, which renders a specific HTML representation in table
form.
"""
out = self.get_params(deep=deep)

DeaMariaLeon marked this conversation as resolved.
Show resolved Hide resolved
init_func = getattr(self.__init__, "deprecated_original", self.__init__)
init_default_params = inspect.signature(init_func).parameters
init_default_params = {
name: param.default for name, param in init_default_params.items()
}

def is_non_default(param_name, param_value):
"""Finds the parameters that have been set by the user."""
if param_name not in init_default_params:
# happens if k is part of a **kwargs
return True
if init_default_params[param_name] == inspect._empty:
# k has no default value
return True
# avoid calling repr on nested estimators
if isinstance(param_value, BaseEstimator) and type(param_value) is not type(
init_default_params[param_name]
):
return True

if param_value != init_default_params[param_name] and not (
is_scalar_nan(init_default_params[param_name])
and is_scalar_nan(param_value)
):
return True
return False

# reorder the parameters from `self.get_params` using the `__init__`
# signature
remaining_params = [name for name in out if name not in init_default_params]
ordered_out = {name: out[name] for name in init_default_params if name in out}
ordered_out.update({name: out[name] for name in remaining_params})

glemaitre marked this conversation as resolved.
Show resolved Hide resolved
non_default_ls = tuple(
[name for name, value in ordered_out.items() if is_non_default(name, value)]
)

return ParamsDict(ordered_out, non_default=non_default_ls)

def set_params(self, **params):
"""Set the parameters of this estimator.

Expand Down Expand Up @@ -409,36 +472,6 @@ class attribute, which is a dictionary `param_name: list of constraints`. See
caller_name=self.__class__.__name__,
)

@property
def _repr_html_(self):
"""HTML representation of estimator.

This is redundant with the logic of `_repr_mimebundle_`. The latter
should be favored in the long term, `_repr_html_` is only
implemented for consumers who do not interpret `_repr_mimbundle_`.
"""
if get_config()["display"] != "diagram":
raise AttributeError(
"_repr_html_ is only defined when the "
"'display' configuration option is set to "
"'diagram'"
)
return self._repr_html_inner

def _repr_html_inner(self):
"""This function is returned by the @property `_repr_html_` to make
`hasattr(estimator, "_repr_html_") return `True` or `False` depending
on `get_config()["display"]`.
"""
return estimator_html_repr(self)

def _repr_mimebundle_(self, **kwargs):
"""Mime bundle used by jupyter kernels to display estimator"""
output = {"text/plain": repr(self)}
if get_config()["display"] == "diagram":
output["text/html"] = estimator_html_repr(self)
return output


class ClassifierMixin:
"""Mixin class for all classifiers in scikit-learn.
Expand Down
2 changes: 1 addition & 1 deletion 2 sklearn/compose/_column_transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@
from ..pipeline import _fit_transform_one, _name_estimators, _transform_one
from ..preprocessing import FunctionTransformer
from ..utils import Bunch
from ..utils._estimator_html_repr import _VisualBlock
from ..utils._indexing import _determine_key_type, _get_column_indices, _safe_indexing
from ..utils._metadata_requests import METHODS
from ..utils._param_validation import HasMethods, Hidden, Interval, StrOptions
from ..utils._repr_html.estimator import _VisualBlock
from ..utils._set_output import (
_get_container_adapter,
_get_output_config,
Expand Down
2 changes: 1 addition & 1 deletion 2 sklearn/ensemble/_stacking.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@
from ..model_selection import check_cv, cross_val_predict
from ..preprocessing import LabelEncoder
from ..utils import Bunch
from ..utils._estimator_html_repr import _VisualBlock
from ..utils._param_validation import HasMethods, StrOptions
from ..utils._repr_html.estimator import _VisualBlock
from ..utils.metadata_routing import (
MetadataRouter,
MethodMapping,
Expand Down
2 changes: 1 addition & 1 deletion 2 sklearn/ensemble/_voting.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@
from ..exceptions import NotFittedError
from ..preprocessing import LabelEncoder
from ..utils import Bunch
from ..utils._estimator_html_repr import _VisualBlock
from ..utils._param_validation import StrOptions
from ..utils._repr_html.estimator import _VisualBlock
from ..utils.metadata_routing import (
MetadataRouter,
MethodMapping,
Expand Down
2 changes: 1 addition & 1 deletion 2 sklearn/model_selection/_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@
get_scorer_names,
)
from ..utils import Bunch, check_random_state
from ..utils._estimator_html_repr import _VisualBlock
from ..utils._param_validation import HasMethods, Interval, StrOptions
from ..utils._repr_html.estimator import _VisualBlock
from ..utils._tags import get_tags
from ..utils.metadata_routing import (
MetadataRouter,
Expand Down
8 changes: 4 additions & 4 deletions 8 sklearn/model_selection/tests/test_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -2662,21 +2662,21 @@ def test_search_html_repr():
search_cv = GridSearchCV(pipeline, param_grid=param_grid, refit=False)
with config_context(display="diagram"):
repr_html = search_cv._repr_html_()
assert "<pre>DummyClassifier()</pre>" in repr_html
assert "<div>DummyClassifier</div>" in repr_html

# Fitted with `refit=False` shows the original pipeline
search_cv.fit(X, y)
with config_context(display="diagram"):
repr_html = search_cv._repr_html_()
assert "<pre>DummyClassifier()</pre>" in repr_html
assert "<div>DummyClassifier</div>" in repr_html

# Fitted with `refit=True` shows the best estimator
search_cv = GridSearchCV(pipeline, param_grid=param_grid, refit=True)
search_cv.fit(X, y)
with config_context(display="diagram"):
repr_html = search_cv._repr_html_()
assert "<pre>DummyClassifier()</pre>" not in repr_html
assert "<pre>LogisticRegression()</pre>" in repr_html
assert "<div>DummyClassifier</div>" not in repr_html
assert "<div>LogisticRegression</div>" in repr_html


# Metadata Routing Tests
Expand Down
2 changes: 1 addition & 1 deletion 2 sklearn/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@
from .exceptions import NotFittedError
from .preprocessing import FunctionTransformer
from .utils import Bunch
from .utils._estimator_html_repr import _VisualBlock
from .utils._metadata_requests import METHODS
from .utils._param_validation import HasMethods, Hidden
from .utils._repr_html.estimator import _VisualBlock
from .utils._set_output import (
_get_container_adapter,
_safe_set_output,
Expand Down
2 changes: 1 addition & 1 deletion 2 sklearn/preprocessing/_function_transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
import numpy as np

from ..base import BaseEstimator, TransformerMixin, _fit_context
from ..utils._estimator_html_repr import _VisualBlock
from ..utils._param_validation import StrOptions
from ..utils._repr_html.estimator import _VisualBlock
from ..utils._set_output import (
_get_adapter_from_container,
_get_output_config,
Expand Down
8 changes: 8 additions & 0 deletions 8 sklearn/tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -992,3 +992,11 @@ def predict(self, X, prop=None):
with warnings.catch_warnings(record=True) as record:
CustomOutlierDetector().set_predict_request(prop=True).fit_predict([[1]], [1])
assert len(record) == 0


def test_get_params_html():
DeaMariaLeon marked this conversation as resolved.
Show resolved Hide resolved
"""Check the behaviour of the `_get_params_html` method."""
est = MyEstimator(empty="test")

assert est._get_params_html() == {"l1": 0, "empty": "test"}
assert est._get_params_html().non_default == ("empty",)
3 changes: 2 additions & 1 deletion 3 sklearn/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from . import metadata_routing
from ._bunch import Bunch
from ._chunking import gen_batches, gen_even_slices
from ._estimator_html_repr import estimator_html_repr

# Make _safe_indexing importable from here for backward compat as this particular
# helper is considered semi-private and typically very useful for third-party
Expand All @@ -20,6 +19,8 @@
shuffle,
)
from ._mask import safe_mask
from ._repr_html.base import _HTMLDocumentationLinkMixin # noqa: F401
from ._repr_html.estimator import estimator_html_repr
from ._tags import (
ClassifierTags,
InputTags,
Expand Down
2 changes: 2 additions & 0 deletions 2 sklearn/utils/_repr_html/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause
Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.