Skip to content

feat(inspection): add Accumulated Local Effects (ALE) and AccumulatedLocalEffectsDisplay - #34950

Closed
Shikhar-Kesharwani wants to merge 1 commit into
scikit-learn:mainfrom
Shikhar-Kesharwani:enh/accumulated-local-effects
Closed

Shikhar-Kesharwani wants to merge 1 commit into
scikit-learn:mainfrom
Shikhar-Kesharwani:enh/accumulated-local-effects

Conversation

@Shikhar-Kesharwani

Copy link
Copy Markdown

Summary of Changes

Fixes #30223

This PR implements Accumulated Local Effects (ALE) for continuous features in sklearn.inspection, providing a local-difference alternative to Partial Dependence Plots (PDP) that eliminates extrapolation distortion under correlated features.

Motivation & Background

As discussed and approved in #30223:
Partial Dependence evaluates marginal expectations $\mathbb{E}_{X_c}[f(x_s, X_c)]$, which forces models to evaluate unrealistic or impossible feature combinations when predictors are strongly correlated.

ALE (Apley & Zhu, 2020) resolves this by:

  1. Partitioning continuous feature values into $K$ quantile-based intervals $[z_{k-1}, z_k]$.
  2. Evaluating local prediction differences $\Delta f_k(x) = f(z_k, x_{i,c}) - f(z_{k-1}, x_{i,c})$ for samples $x_{i,s}$ actually falling inside each interval.
  3. Accumulating local differences across intervals.
  4. Mean-centering the accumulated effect so $\mathbb{E}{X}[\hat{f}{ALE}(X_s)] = 0$.

What this PR adds:

  1. Core Engine: accumulated_local_effects(estimator, X, features, *, ...) in sklearn/inspection/_accumulated_local_effects.py returning a Bunch (ale, values, grid_values, feature_names).
  2. Visualization: AccumulatedLocalEffectsDisplay in sklearn/inspection/_plot/accumulated_local_effects.py with .plot() and .from_estimator() adhering to scikit-learn display standards.
  3. Exports: Exported in sklearn/inspection/__init__.py.
  4. Unit Tests:
    • test_accumulated_local_effects.py: Verifies analytical coefficient recovery on 95% correlated linear models, binary & multiclass classification, multi-target regression, sample weights, pandas DataFrame inputs, and input validation.
    • test_plot_accumulated_local_effects.py: Verifies from_estimator, multi-axis subplots, custom axes, and multiclass target selection.

Signed-off-by: Shikhar Kesharwani [email protected]

…LocalEffectsDisplay

Implements Accumulated Local Effects (ALE) as requested in scikit-learn#30223.
ALE calculates local differences in predictions over conditional intervals,
preventing the distortion caused by correlated features in standard
Partial Dependence Plots (PDP).

- Add accumulated_local_effects computation engine in sklearn.inspection._accumulated_local_effects.
- Add AccumulatedLocalEffectsDisplay in sklearn.inspection._plot.accumulated_local_effects.
- Export both in sklearn.inspection.__init__.
- Add comprehensive unit test suites covering regression, binary classification,
  multiclass classification, multi-target output, and plotting utilities.

Fixes scikit-learn#30223

Signed-off-by: Shikhar Kesharwani <[email protected]>
@github-actions

Copy link
Copy Markdown

Thank you for opening your first pull request to scikit-learn! 🎉

To help get your contribution reviewed, please make sure that:

  • You have filled out the pull request template.

  • The pull request addresses an existing issue that is ready for contribution (e.g. not tagged as 'Needs Triage', 'Needs Decision', ...). If you are proposing a new feature, please open an issue to discuss it first.

  • There are no other open pull requests already targeting the same issue.

  • You have followed the pull request checklist. In particular, linting and tests should pass.

@github-actions github-actions Bot added the CI:Linter failure The linter CI is failing on this PR label Sep 13, 2026
@github-actions

Copy link
Copy Markdown

❌ Linting issues

This PR is introducing linting issues. Here's a summary of the issues. Note that you can avoid having linting issues by enabling pre-commit hooks. Instructions to enable them can be found here.

You can see the details of the linting issues under the lint job here


ruff check

ruff detected issues. Please run ruff check --fix --output-format=full locally, fix the remaining issues, and push the changes. Here you can see the detected issues. Note that the installed ruff version is ruff=0.12.2.

Details

sklearn/inspection/_accumulated_local_effects.py:6:1: I001 [*] Import block is un-sorted or un-formatted
   |
 4 |   # SPDX-License-Identifier: BSD-3-Clause
 5 |
 6 | / from collections.abc import Iterable
 7 | | import warnings
 8 | | import numpy as np
 9 | |
10 | | from sklearn.base import is_classifier, is_regressor
11 | | from sklearn.inspection._pd_utils import _check_feature_names, _get_feature_index
12 | | from sklearn.utils import Bunch, _safe_indexing, check_array
13 | | from sklearn.utils._indexing import _get_column_indices
14 | | from sklearn.utils._param_validation import (
15 | |     HasMethods,
16 | |     Integral,
17 | |     Interval,
18 | |     StrOptions,
19 | |     validate_params,
20 | | )
21 | | from sklearn.utils._response import _get_response_values
22 | | from sklearn.utils.validation import _check_sample_weight, check_is_fitted
   | |__________________________________________________________________________^ I001
23 |
24 |   __all__ = [
   |
   = help: Organize imports

sklearn/inspection/_accumulated_local_effects.py:12:34: F401 [*] `sklearn.utils._safe_indexing` imported but unused
   |
10 | from sklearn.base import is_classifier, is_regressor
11 | from sklearn.inspection._pd_utils import _check_feature_names, _get_feature_index
12 | from sklearn.utils import Bunch, _safe_indexing, check_array
   |                                  ^^^^^^^^^^^^^^ F401
13 | from sklearn.utils._indexing import _get_column_indices
14 | from sklearn.utils._param_validation import (
   |
   = help: Remove unused import: `sklearn.utils._safe_indexing`

sklearn/inspection/_accumulated_local_effects.py:13:37: F401 [*] `sklearn.utils._indexing._get_column_indices` imported but unused
   |
11 | from sklearn.inspection._pd_utils import _check_feature_names, _get_feature_index
12 | from sklearn.utils import Bunch, _safe_indexing, check_array
13 | from sklearn.utils._indexing import _get_column_indices
   |                                     ^^^^^^^^^^^^^^^^^^^ F401
14 | from sklearn.utils._param_validation import (
15 |     HasMethods,
   |
   = help: Remove unused import: `sklearn.utils._indexing._get_column_indices`

sklearn/inspection/_accumulated_local_effects.py:54:89: E501 Line too long (100 > 88)
   |
52 |         )
53 |         # Handle degenerate case: constant feature
54 |         breaks = np.array([x_feat.min(), x_feat.max()]) if x_feat.size > 0 else np.array([0.0, 1.0])
   |                                                                                         ^^^^^^^^^^^^ E501
55 |         # Obtain target dimension by calling prediction once
56 |         pred_sample, _ = _get_response_values(estimator, X[:1], response_method=response_method)
   |

sklearn/inspection/_accumulated_local_effects.py:56:89: E501 Line too long (96 > 88)
   |
54 |         breaks = np.array([x_feat.min(), x_feat.max()]) if x_feat.size > 0 else np.array([0.0, 1.0])
55 |         # Obtain target dimension by calling prediction once
56 |         pred_sample, _ = _get_response_values(estimator, X[:1], response_method=response_method)
   |                                                                                         ^^^^^^^^ E501
57 |         n_targets = pred_sample.shape[1] if pred_sample.ndim > 1 else 1
58 |         return np.zeros((n_targets, len(breaks))), breaks
   |

sklearn/inspection/_accumulated_local_effects.py:65:89: E501 Line too long (90 > 88)
   |
64 |     # Initial prediction to determine output dimension (n_targets)
65 |     pred_init, _ = _get_response_values(estimator, X[:1], response_method=response_method)
   |                                                                                         ^^ E501
66 |     if pred_init.ndim == 1:
67 |         n_targets = 1
   |

sklearn/inspection/_accumulated_local_effects.py:80:1: W293 [*] Blank line contains whitespace
   |
78 |         # Extract samples falling within the interval
79 |         X_bin = X[in_bin].copy()
80 |         
   | ^^^^^^^^ W293
81 |         # Evaluate predictions at left interval boundary
82 |         X_bin[:, feature_idx] = breaks[k]
   |
   = help: Remove whitespace from blank line

sklearn/inspection/_accumulated_local_effects.py:83:89: E501 Line too long (94 > 88)
   |
81 |         # Evaluate predictions at left interval boundary
82 |         X_bin[:, feature_idx] = breaks[k]
83 |         pred_left, _ = _get_response_values(estimator, X_bin, response_method=response_method)
   |                                                                                         ^^^^^^ E501
84 |         if pred_left.ndim == 1:
85 |             pred_left = pred_left[np.newaxis, :]
   |

sklearn/inspection/_accumulated_local_effects.py:91:89: E501 Line too long (95 > 88)
   |
89 |         # Evaluate predictions at right interval boundary
90 |         X_bin[:, feature_idx] = breaks[k + 1]
91 |         pred_right, _ = _get_response_values(estimator, X_bin, response_method=response_method)
   |                                                                                         ^^^^^^^ E501
92 |         if pred_right.ndim == 1:
93 |             pred_right = pred_right[np.newaxis, :]
   |

sklearn/inspection/_accumulated_local_effects.py:127:89: E501 Line too long (100 > 88)
    |
126 |     if sample_weight is not None and np.sum(sample_weight) > 0:
127 |         mean_ale = np.sum(sample_ale * sample_weight, axis=1, keepdims=True) / np.sum(sample_weight)
    |                                                                                         ^^^^^^^^^^^^ E501
128 |     else:
129 |         mean_ale = np.mean(sample_ale, axis=1, keepdims=True)
    |

sklearn/inspection/_accumulated_local_effects.py:138:89: E501 Line too long (134 > 88)
    |
136 | @validate_params(
137 |     {
138 |         "estimator": [HasMethods(["fit", "predict"]), HasMethods(["fit", "predict_proba"]), HasMethods(["fit", "decision_function"])],
    |                                                                                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ E501
139 |         "X": ["array-like"],
140 |         "features": ["array-like", Integral, str],
    |

sklearn/inspection/_accumulated_local_effects.py:143:89: E501 Line too long (99 > 88)
    |
141 |         "sample_weight": ["array-like", None],
142 |         "feature_names": ["array-like", None],
143 |         "response_method": [StrOptions({"auto", "predict_proba", "decision_function", "predict"})],
    |                                                                                         ^^^^^^^^^^^ E501
144 |         "grid_resolution": [Interval(Integral, 2, None, closed="left")],
145 |         "percentiles": [tuple],
    |

sklearn/inspection/_accumulated_local_effects.py:188:89: E501 Line too long (95 > 88)
    |
186 |         Name of each feature; used if `X` does not define `columns`.
187 |
188 |     response_method : {'auto', 'predict_proba', 'decision_function', 'predict'}, default='auto'
    |                                                                                         ^^^^^^^ E501
189 |         Specifies whether to use `predict_proba`, `decision_function`, or `predict`
190 |         as the target response. For regressors, defaults to `'predict'`. For classifiers,
    |

sklearn/inspection/_accumulated_local_effects.py:190:89: E501 Line too long (89 > 88)
    |
188 |     response_method : {'auto', 'predict_proba', 'decision_function', 'predict'}, default='auto'
189 |         Specifies whether to use `predict_proba`, `decision_function`, or `predict`
190 |         as the target response. For regressors, defaults to `'predict'`. For classifiers,
    |                                                                                         ^ E501
191 |         `'auto'` prioritizes `predict_proba` over `decision_function`.
    |

sklearn/inspection/_accumulated_local_effects.py:223:89: E501 Line too long (104 > 88)
    |
221 |         raise ValueError("'percentiles' must be a sequence of 2 elements.")
222 |     if not (0.0 <= percentiles[0] < percentiles[1] <= 1.0):
223 |         raise ValueError("'percentiles' values must be in [0, 1] with percentiles[0] < percentiles[1].")
    |                                                                                         ^^^^^^^^^^^^^^^^ E501
224 |
225 |     if sample_weight is not None:
    |

sklearn/inspection/_plot/accumulated_local_effects.py:6:1: I001 [*] Import block is un-sorted or un-formatted
   |
 4 |   # SPDX-License-Identifier: BSD-3-Clause
 5 |
 6 | / from math import ceil
 7 | | import numpy as np
 8 | |
 9 | | from sklearn.inspection._accumulated_local_effects import accumulated_local_effects
10 | | from sklearn.inspection._pd_utils import _check_feature_names, _get_feature_index
11 | | from sklearn.utils._optional_dependencies import check_matplotlib_support
12 | | from sklearn.utils._plotting import _validate_style_kwargs
   | |__________________________________________________________^ I001
   |
   = help: Organize imports

sklearn/inspection/_plot/accumulated_local_effects.py:12:37: F401 [*] `sklearn.utils._plotting._validate_style_kwargs` imported but unused
   |
10 | from sklearn.inspection._pd_utils import _check_feature_names, _get_feature_index
11 | from sklearn.utils._optional_dependencies import check_matplotlib_support
12 | from sklearn.utils._plotting import _validate_style_kwargs
   |                                     ^^^^^^^^^^^^^^^^^^^^^^ F401
   |
   = help: Remove unused import: `sklearn.utils._plotting._validate_style_kwargs`

sklearn/inspection/_plot/accumulated_local_effects.py:19:89: E501 Line too long (90 > 88)
   |
18 |     It is recommended to use
19 |     :func:`~sklearn.inspection.AccumulatedLocalEffectsDisplay.from_estimator` to create an
   |                                                                                         ^^ E501
20 |     :class:`~sklearn.inspection.AccumulatedLocalEffectsDisplay`.
   |

sklearn/inspection/_plot/accumulated_local_effects.py:88:22: RUF046 Value being cast to `int` is already an integer
   |
86 |         if ax is None:
87 |             n_cols = min(n_cols, n_plots)
88 |             n_rows = int(ceil(n_plots / n_cols))
   |                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^ RUF046
89 |             fig, axes = plt.subplots(n_rows, n_cols, figsize=(4 * n_cols, 3.5 * n_rows), squeeze=False)
90 |         elif isinstance(ax, np.ndarray):
   |
   = help: Remove unnecessary `int` call

sklearn/inspection/_plot/accumulated_local_effects.py:89:89: E501 Line too long (103 > 88)
   |
87 |             n_cols = min(n_cols, n_plots)
88 |             n_rows = int(ceil(n_plots / n_cols))
89 |             fig, axes = plt.subplots(n_rows, n_cols, figsize=(4 * n_cols, 3.5 * n_rows), squeeze=False)
   |                                                                                         ^^^^^^^^^^^^^^^ E501
90 |         elif isinstance(ax, np.ndarray):
91 |             axes = ax.reshape(-1, n_cols) if ax.ndim == 1 else ax
   |

sklearn/inspection/_plot/accumulated_local_effects.py:156:89: E501 Line too long (99 > 88)
    |
154 |         feature_names : array-like of shape (n_features,), default=None
155 |             Names of features.
156 |         response_method : {'auto', 'predict_proba', 'decision_function', 'predict'}, default='auto'
    |                                                                                         ^^^^^^^^^^^ E501
157 |             Prediction method.
158 |         grid_resolution : int, default=100
    |

sklearn/inspection/_plot/tests/test_plot_accumulated_local_effects.py:1:1: I001 [*] Import block is un-sorted or un-formatted
  |
1 | / import pytest
2 | | import numpy as np
3 | |
4 | | from sklearn.datasets import make_classification, make_regression
5 | | from sklearn.inspection import AccumulatedLocalEffectsDisplay
6 | | from sklearn.linear_model import LinearRegression, LogisticRegression
  | |_____________________________________________________________________^ I001
  |
  = help: Organize imports

sklearn/inspection/_plot/tests/test_plot_accumulated_local_effects.py:53:89: E501 Line too long (122 > 88)
   |
51 |     rng = np.random.RandomState(42)
52 |     X, y = make_classification(
53 |         n_samples=150, n_features=5, n_informative=3, n_redundant=1, n_classes=3, n_clusters_per_class=1, random_state=rng
   |                                                                                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ E501
54 |     )
55 |     clf = LogisticRegression().fit(X, y)
   |

sklearn/inspection/tests/test_accumulated_local_effects.py:1:1: I001 [*] Import block is un-sorted or un-formatted
  |
1 | / import numpy as np
2 | | import pytest
3 | |
4 | | from sklearn.datasets import make_classification, make_regression
5 | | from sklearn.exceptions import NotFittedError
6 | | from sklearn.inspection import accumulated_local_effects
7 | | from sklearn.linear_model import LinearRegression, LogisticRegression
8 | | from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier
9 | | from sklearn.utils import Bunch
  | |_______________________________^ I001
  |
  = help: Organize imports

sklearn/inspection/tests/test_accumulated_local_effects.py:13:89: E501 Line too long (93 > 88)
   |
12 | def test_ale_linear_regression_correlated_features():
13 |     """Verify that ALE recovers true linear coefficients despite high feature correlation."""
   |                                                                                         ^^^^^ E501
14 |     rng = np.random.RandomState(42)
15 |     n = 1500
   |

sklearn/inspection/tests/test_accumulated_local_effects.py:55:89: E501 Line too long (96 > 88)
   |
54 | def test_ale_binary_classification():
55 |     """Verify ALE works on binary classifiers with probability and decision_function outputs."""
   |                                                                                         ^^^^^^^^ E501
56 |     rng = np.random.RandomState(42)
57 |     X, y = make_classification(n_samples=300, n_features=4, n_informative=2, n_redundant=1, random_state=rng)
   |

sklearn/inspection/tests/test_accumulated_local_effects.py:57:89: E501 Line too long (109 > 88)
   |
55 |     """Verify ALE works on binary classifiers with probability and decision_function outputs."""
56 |     rng = np.random.RandomState(42)
57 |     X, y = make_classification(n_samples=300, n_features=4, n_informative=2, n_redundant=1, random_state=rng)
   |                                                                                         ^^^^^^^^^^^^^^^^^^^^^ E501
58 |     clf = LogisticRegression().fit(X, y)
   |

sklearn/inspection/tests/test_accumulated_local_effects.py:67:89: E501 Line too long (97 > 88)
   |
66 |     # Explicit decision_function
67 |     res_df = accumulated_local_effects(clf, X, features=[0], response_method="decision_function")
   |                                                                                         ^^^^^^^^^ E501
68 |     assert res_df.ale[0].shape[0] == 1
   |

sklearn/inspection/tests/test_accumulated_local_effects.py:75:89: E501 Line too long (122 > 88)
   |
73 |     rng = np.random.RandomState(42)
74 |     X, y = make_classification(
75 |         n_samples=300, n_features=6, n_informative=3, n_redundant=1, n_classes=3, n_clusters_per_class=1, random_state=rng
   |                                                                                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ E501
76 |     )
77 |     clf = RandomForestClassifier(n_estimators=10, random_state=rng).fit(X, y)
   |

sklearn/inspection/tests/test_accumulated_local_effects.py:150:89: E501 Line too long (96 > 88)
    |
148 |     model = LinearRegression().fit(np.ones((50, 2)), np.ones(50))
149 |     with pytest.raises(ValueError, match="percentiles"):
150 |         accumulated_local_effects(model, np.ones((50, 2)), features=[0], percentiles=(0.9, 0.1))
    |                                                                                         ^^^^^^^^ E501
    |

Found 30 errors.
[*] 8 fixable with the `--fix` option (1 hidden fix can be enabled with the `--unsafe-fixes` option).

ruff format

ruff detected issues. Please run ruff format locally and push the changes. Here you can see the detected issues. Note that the installed ruff version is ruff=0.12.2.

Details

--- sklearn/inspection/_accumulated_local_effects.py
+++ sklearn/inspection/_accumulated_local_effects.py
@@ -51,9 +51,15 @@
             UserWarning,
         )
         # Handle degenerate case: constant feature
-        breaks = np.array([x_feat.min(), x_feat.max()]) if x_feat.size > 0 else np.array([0.0, 1.0])
+        breaks = (
+            np.array([x_feat.min(), x_feat.max()])
+            if x_feat.size > 0
+            else np.array([0.0, 1.0])
+        )
         # Obtain target dimension by calling prediction once
-        pred_sample, _ = _get_response_values(estimator, X[:1], response_method=response_method)
+        pred_sample, _ = _get_response_values(
+            estimator, X[:1], response_method=response_method
+        )
         n_targets = pred_sample.shape[1] if pred_sample.ndim > 1 else 1
         return np.zeros((n_targets, len(breaks))), breaks
 
@@ -62,7 +68,9 @@
     indices = np.clip(indices, 0, n_intervals - 1)
 
     # Initial prediction to determine output dimension (n_targets)
-    pred_init, _ = _get_response_values(estimator, X[:1], response_method=response_method)
+    pred_init, _ = _get_response_values(
+        estimator, X[:1], response_method=response_method
+    )
     if pred_init.ndim == 1:
         n_targets = 1
     else:
@@ -71,16 +79,18 @@
     deltas = np.zeros((n_targets, n_intervals), dtype=np.float64)
 
     for k in range(n_intervals):
-        in_bin = (indices == k)
+        in_bin = indices == k
         if not np.any(in_bin):
             continue
 
         # Extract samples falling within the interval
         X_bin = X[in_bin].copy()
-        
+
         # Evaluate predictions at left interval boundary
         X_bin[:, feature_idx] = breaks[k]
-        pred_left, _ = _get_response_values(estimator, X_bin, response_method=response_method)
+        pred_left, _ = _get_response_values(
+            estimator, X_bin, response_method=response_method
+        )
         if pred_left.ndim == 1:
             pred_left = pred_left[np.newaxis, :]
         else:
@@ -88,7 +98,9 @@
 
         # Evaluate predictions at right interval boundary
         X_bin[:, feature_idx] = breaks[k + 1]
-        pred_right, _ = _get_response_values(estimator, X_bin, response_method=response_method)
+        pred_right, _ = _get_response_values(
+            estimator, X_bin, response_method=response_method
+        )
         if pred_right.ndim == 1:
             pred_right = pred_right[np.newaxis, :]
         else:
@@ -113,7 +125,7 @@
     # Center ALE so the weighted average across sample distribution is zero
     sample_ale = np.zeros((n_targets, n_samples), dtype=np.float64)
     for k in range(n_intervals):
-        in_bin = (indices == k)
+        in_bin = indices == k
         if not np.any(in_bin):
             continue
         interval_width = breaks[k + 1] - breaks[k]
@@ -124,7 +136,9 @@
         sample_ale[:, in_bin] = ale_uncentered[:, [k]] + frac * deltas[:, [k]]
 
     if sample_weight is not None and np.sum(sample_weight) > 0:
-        mean_ale = np.sum(sample_ale * sample_weight, axis=1, keepdims=True) / np.sum(sample_weight)
+        mean_ale = np.sum(sample_ale * sample_weight, axis=1, keepdims=True) / np.sum(
+            sample_weight
+        )
     else:
         mean_ale = np.mean(sample_ale, axis=1, keepdims=True)
 
@@ -135,12 +149,18 @@
 
 @validate_params(
     {
-        "estimator": [HasMethods(["fit", "predict"]), HasMethods(["fit", "predict_proba"]), HasMethods(["fit", "decision_function"])],
+        "estimator": [
+            HasMethods(["fit", "predict"]),
+            HasMethods(["fit", "predict_proba"]),
+            HasMethods(["fit", "decision_function"]),
+        ],
         "X": ["array-like"],
         "features": ["array-like", Integral, str],
         "sample_weight": ["array-like", None],
         "feature_names": ["array-like", None],
-        "response_method": [StrOptions({"auto", "predict_proba", "decision_function", "predict"})],
+        "response_method": [
+            StrOptions({"auto", "predict_proba", "decision_function", "predict"})
+        ],
         "grid_resolution": [Interval(Integral, 2, None, closed="left")],
         "percentiles": [tuple],
     },
@@ -220,7 +240,9 @@
     if not isinstance(percentiles, Iterable) or len(percentiles) != 2:
         raise ValueError("'percentiles' must be a sequence of 2 elements.")
     if not (0.0 <= percentiles[0] < percentiles[1] <= 1.0):
-        raise ValueError("'percentiles' values must be in [0, 1] with percentiles[0] < percentiles[1].")
+        raise ValueError(
+            "'percentiles' values must be in [0, 1] with percentiles[0] < percentiles[1]."
+        )
 
     if sample_weight is not None:
         sample_weight = _check_sample_weight(sample_weight, X)

--- sklearn/inspection/_plot/accumulated_local_effects.py
+++ sklearn/inspection/_plot/accumulated_local_effects.py
@@ -86,7 +86,9 @@
         if ax is None:
             n_cols = min(n_cols, n_plots)
             n_rows = int(ceil(n_plots / n_cols))
-            fig, axes = plt.subplots(n_rows, n_cols, figsize=(4 * n_cols, 3.5 * n_rows), squeeze=False)
+            fig, axes = plt.subplots(
+                n_rows, n_cols, figsize=(4 * n_cols, 3.5 * n_rows), squeeze=False
+            )
         elif isinstance(ax, np.ndarray):
             axes = ax.reshape(-1, n_cols) if ax.ndim == 1 else ax
             fig = axes.flat[0].figure

--- sklearn/inspection/_plot/tests/test_plot_accumulated_local_effects.py
+++ sklearn/inspection/_plot/tests/test_plot_accumulated_local_effects.py
@@ -50,7 +50,13 @@
 
     rng = np.random.RandomState(42)
     X, y = make_classification(
-        n_samples=150, n_features=5, n_informative=3, n_redundant=1, n_classes=3, n_clusters_per_class=1, random_state=rng
+        n_samples=150,
+        n_features=5,
+        n_informative=3,
+        n_redundant=1,
+        n_classes=3,
+        n_clusters_per_class=1,
+        random_state=rng,
     )
     clf = LogisticRegression().fit(X, y)
 

--- sklearn/inspection/tests/test_accumulated_local_effects.py
+++ sklearn/inspection/tests/test_accumulated_local_effects.py
@@ -54,7 +54,9 @@
 def test_ale_binary_classification():
     """Verify ALE works on binary classifiers with probability and decision_function outputs."""
     rng = np.random.RandomState(42)
-    X, y = make_classification(n_samples=300, n_features=4, n_informative=2, n_redundant=1, random_state=rng)
+    X, y = make_classification(
+        n_samples=300, n_features=4, n_informative=2, n_redundant=1, random_state=rng
+    )
     clf = LogisticRegression().fit(X, y)
 
     # Auto response_method defaults to predict_proba
@@ -64,7 +66,9 @@
     assert np.all(res_proba.ale[0] <= 1.0)
 
     # Explicit decision_function
-    res_df = accumulated_local_effects(clf, X, features=[0], response_method="decision_function")
+    res_df = accumulated_local_effects(
+        clf, X, features=[0], response_method="decision_function"
+    )
     assert res_df.ale[0].shape[0] == 1
 
 
@@ -72,7 +76,13 @@
     """Verify ALE outputs separate effects per class for multiclass classification."""
     rng = np.random.RandomState(42)
     X, y = make_classification(
-        n_samples=300, n_features=6, n_informative=3, n_redundant=1, n_classes=3, n_clusters_per_class=1, random_state=rng
+        n_samples=300,
+        n_features=6,
+        n_informative=3,
+        n_redundant=1,
+        n_classes=3,
+        n_clusters_per_class=1,
+        random_state=rng,
     )
     clf = RandomForestClassifier(n_estimators=10, random_state=rng).fit(X, y)
 
@@ -98,11 +108,13 @@
     """Verify ALE properly handles pandas DataFrames with string column names."""
     pd = pytest.importorskip("pandas")
     rng = np.random.RandomState(42)
-    df = pd.DataFrame({
-        "feature_a": rng.normal(size=200),
-        "feature_b": rng.uniform(0, 10, size=200),
-        "feature_c": rng.exponential(1.0, size=200),
-    })
+    df = pd.DataFrame(
+        {
+            "feature_a": rng.normal(size=200),
+            "feature_b": rng.uniform(0, 10, size=200),
+            "feature_c": rng.exponential(1.0, size=200),
+        }
+    )
     y = df["feature_a"] * 2 + df["feature_b"]
 
     model = LinearRegression().fit(df, y)
@@ -147,4 +159,6 @@
     """Verify invalid percentiles raise ValueError."""
     model = LinearRegression().fit(np.ones((50, 2)), np.ones(50))
     with pytest.raises(ValueError, match="percentiles"):
-        accumulated_local_effects(model, np.ones((50, 2)), features=[0], percentiles=(0.9, 0.1))
+        accumulated_local_effects(
+            model, np.ones((50, 2)), features=[0], percentiles=(0.9, 0.1)
+        )

4 files would be reformatted, 961 files already formatted

Generated for commit: bae5dfe. Link to the linter CI: here

@virchan virchan left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for the PR, @Shikhar-Kesharwani.

As I write this, #30223 is still being voted on by the maintainers. Until that vote is resolved, PRs proposing a fix for this issue are unlikely to be reviewed.

With that said, I'm closing this PR.

@virchan virchan added the linked issue not ready PR opened before its linked issue reached consensus label Sep 16, 2026
@virchan virchan closed this Sep 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CI:Linter failure The linter CI is failing on this PR linked issue not ready PR opened before its linked issue reached consensus module:inspection

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add Accumulated local effects (ALE) to inspection

2 participants