Skip to content

Add Accumulated local effects (ALE) to inspection #30223

Open

Description

@mayer79

Describe the workflow you want to enable

I'd love to push the inspection module further by adding Accumulated local effects (ALE) from Apley 2020. A great description can be found in Christoph's online book https://christophm.github.io/interpretable-ml-book/ale.html

ALE fix the problem of partial dependence that they force the model to be evaluated on impossible or rare feature combinations. ALE are defined for numeric features that can be binned. From both bin edges, the slope of the partial dependence is calculated locally, i.e., only using observations in the bin. The slopes from all bins are cumsummed and vertically centered to the average response or prediction.

Reference

Apley, Daniel W., and Jingyu Zhu. 2020. Visualizing the Effects of Predictor Variables in Black Box Supervised Learning Models. Journal of the Royal Statistical Society Series B: Statistical Methodology, 82 (4): 1059–1086. doi:10.1111/rssb.12377.

Describe your proposed solution

Pseudo code to calculate ALE for one feature:

pd_slopes = np.zeros_like(bins)

for i, bin in enumerate(bins):
  X_bin = pick n_per_bin = 200 rows from data in bin
  if X_bin is empty:
    next
  pd = partial_dependence_brute(model, X_bin, grid = [lower bin edge, upper bin edge], sample_weights)
  pd_slopes[i] = pd[1] - pd[0]

return np.cumsum(pd_slopes)

Describe alternatives you've considered, if relevant

No response

Additional context

No response

Activity

  1. adrinjalali commented on Nov 5, 2024

    @adrinjalali
    Member

    @glemaitre or @thomasjpfan maybe have an opinion on the inclusion criteria here.

  2. added
    Needs Decision
    and removed
    Needs Triage
    on Nov 5, 2024
  3. glemaitre commented on Nov 5, 2024

    @glemaitre
    Member

    I think that it could be a good addition to the module. The reasoning of what it solves make sense. Regarding the pseudo code, it seems that it would be not a huge amount of code to maintain.

    I have to read more in details the literature to be sure thought.

    @meyer89 Something that I'm thinking looking at your description: does the recursion method of the partial dependence would already lead to not using impossible combination of feature, isn't it?

  4. mayer79 commented on Nov 5, 2024

    @mayer79
    ContributorAuthor

    Something that I'm thinking looking at your description: does the recursion method of the partial dependence would already lead to not using impossible combination of feature, isn't it?

    Good question! I don't think it is better (if the gender node is switched off, then also men will hit the post-menopausal node etc.). But I'd say that the problem is generally smaller for tree-based models than for other types of models.

  5. lionelkusch commented on Jan 20, 2025

    @lionelkusch

    I am also interested in adding this function to scikit-learn.
    I have time to help you with a pull request or I can create one if the decision is positive to include this new functionality.

  6. mayer79 commented on Jan 20, 2025

    @mayer79
    ContributorAuthor

    I have not started yet as I wanted to see this related PR #28375 on Friedman's H^2 statistic being merged first.

    Still, here some aspects the implementation would need to take care of:

    • multivariate output (easy)
    • pandas/polars/numpy input with and without column names
    • with or without plots (I'd tend to "without")
    • optional case weights (easy)
  7. lionelkusch commented on Feb 25, 2025

    @lionelkusch

    I have started a first version of the implementation of ALE. I still need to improve it and I need to include the plot functions, tests and examples.
    You can find it here: https://github.com/lionelkusch/scikit-learn/tree/PR_ALE

    I have based my implementation on the code ALEpython and the implementation of partial dependence function.

    Before continuing, I have some questions:

    • Do we include the ALE at the second order or do we stay only with the first order?
    • I don't understand the way to use weights in the context of ALE. If you can provide me an example of it, I will include it.
    • From the technical part, there will be some parts of the code shared with the partial_dependence function. For the moment, I duplicate the code, but I don't think it's the best solution. The only proposition that I have for the moment is to provide a function for the common initialisation between the two functions, but I don't really like. If you have some ideas, I will be happy to hear them.
  8. mayer79 commented on Feb 26, 2025

    @mayer79
    ContributorAuthor

    Thanks for the initial work! Let's hear what the Scikit-Learn developers mean. My focus is still to first have a solution for #28375 and then care about ALE.

    We need to be patient with the inspection module.

  9. mayer79 commented on Jun 4, 2025

    @mayer79
    ContributorAuthor

    In my opinion, starting with a version for one continuous feature and without any plot would be sufficient. E.g., permutation_importance() only calculates things without plots. The output could be two np.arrays: one with bin breaks, one with corresponding ALE values.

  10. mayer79 commented on Jun 7, 2025

    @mayer79
    ContributorAuthor

    This is a draft of an (almost...) Scikit-Learn compatible implementation:

    https://github.com/mayer79/accumulated_local_effects

    import matplotlib.pyplot as plt
    import numpy as np
    import pandas as pd
    from ale import accumulated_local_effects
    from sklearn.compose import ColumnTransformer
    from sklearn.linear_model import LinearRegression
    from sklearn.pipeline import Pipeline
    from sklearn.preprocessing import SplineTransformer
    rng = np.random.default_rng(1)
    
    age = rng.uniform(0, 40, size=1000)
    living_area = rng.uniform(40, 150, size=1000)
    X = pd.DataFrame({"age": age, "living_area": living_area})
    
    rent = 20 * living_area - 20 * age + (age - 20) ** 2 + rng.normal(0, 10, size=1000)
    
    preprocess_glm = ColumnTransformer(
        transformers=[
            ("spline", SplineTransformer(include_bias=False, knots="quantile"), ["age"]),
            ("linear", "passthrough", ["living_area"]),
        ],
        verbose_feature_names_out=False,
    ).set_output(transform="pandas")
    
    model = Pipeline(
        steps=[
            ("preprocessor", preprocess_glm),
            ("model", LinearRegression()),
        ]
    )
    model.fit(X, y=rent)
    
    fig, axes = plt.subplots(1, 2, figsize=(12, 5))
    
    for feature, ax in zip(("age", "living_area"), axes):
        ale = accumulated_local_effects(X, model.predict, feature=feature)
        ax.plot(ale["breaks"], ale["ale"])
        ax.set_title(f"{feature}")
    plt.show()

    Image

  11. mayer79 commented on Jun 7, 2025

    @mayer79
    ContributorAuthor

    Hello. Your code is actually much further than I had in mind, thx!

    from sklearn.datasets import load_diabetes
    from sklearn.ensemble import HistGradientBoostingRegressor
    
    X, y = load_diabetes(return_X_y=True, as_frame=True)
    
    est = HistGradientBoostingRegressor(max_iter=50, max_depth=4).fit(X, y)
    
    accumulated_local_effect(est, X=X, features=["s3"])

    gives:

    ---------------------------------------------------------------------------
    IndexError                                Traceback (most recent call last)
    Cell In[16], line 8
          4 X, y = load_diabetes(return_X_y=True, as_frame=True)
          6 est = HistGradientBoostingRegressor(max_iter=50, max_depth=4).fit(X, y)
    ----> 8 accumulated_local_effect(est, X=X, features=["s3"])
    
    File c:\Users\mayer\ai-tools-for-actuaries\.venv\Lib\site-packages\sklearn\utils\_param_validation.py:213, in validate_params.<locals>.decorator.<locals>.wrapper(*args, **kwargs)
        207 try:
        208     with config_context(
        209         skip_parameter_validation=(
        210             prefer_skip_nested_validation or global_skip_validation
        211         )
        212     ):
    --> 213         return func(*args, **kwargs)
        214 except InvalidParameterError as e:
        215     # When the function is just a wrapper around an estimator, we allow
        216     # the function to delegate validation to the estimator, but we replace
        217     # the name of the estimator by the name of the function in the error
        218     # message to avoid confusion.
        219     msg = re.sub(
        220         r"parameter of \w+ must be",
        221         f"parameter of {func.__qualname__} must be",
        222         str(e),
        223     )
    
    Cell In[3], line 357, in accumulated_local_effect(estimator, X, features, sample_weight, categorical_features, feature_names, response_method, grid_resolution, custom_values)
        355     break
        356 # code partially copy from ALEpython (https://github.com/blent-ai/ALEPython/blob/dev/src/alepython/ale.py)
    --> 357 quantile = quantiles[feature_idx]
        358 indice = indices[feature_idx]
        359 averaged_predictions, predictions = _partial_dependence_brute(
        360     estimator,
        361     [[quantile[indice]], [quantile[indice + 1]]],
       (...)    365     sample_weight,
        366 )
    
    IndexError: list index out of range

    But maybe I did something stupid.

  12. 13 remaining items

  13. VimalN2005 commented on Sep 12, 2026

    @VimalN2005

    Hi @lorentzenchr @lucyleeow,

    I see the recent +1s for adding Accumulated Local Effects (ALE) to sklearn.inspection. I would be very happy to contribute this feature.

    My proposed approach would align closely with the existing partial_dependence API:

    1. Implement accumulated_local_effects(estimator, X, features, *, grid_resolution=100, ...) returning an ALE computation bunch similar to PartialDependenceDisplay.
    2. Compute feature quantiles/grid points, evaluate the local difference predictions on interval margins, and accumulate the uncentered effects before centering by the mean effect.
    3. Provide an intuitive display helper (AccumulatedLocalEffectsDisplay or integration with the display framework).
    4. Add unit tests covering regression and classification estimators, synthetic correlated data checks against analytical expectations, and documentation in the User Guide.

    Please let me know if I can go ahead and open a PR with the initial implementation and tests. Thank you!

  14. Shikhar-Kesharwani commented on Sep 13, 2026

    @Shikhar-Kesharwani

    Hi @lorentzenchr, @lucyleeow, and contributors,

    I have submitted an implementation of Accumulated Local Effects (ALE) and AccumulatedLocalEffectsDisplay in PR #34950 (#34950).

    Summary of Implementation:

    • accumulated_local_effects(estimator, X, features, ...) computes conditional interval differences and mean-centered ALE curves.
    • AccumulatedLocalEffectsDisplay supports .from_estimator() and .plot().
    • Full pytest test suite covering correlated feature slope recovery, binary/multiclass classification, sample weighting, and pandas DataFrame inputs.
  15. adam2392 commented on Sep 14, 2026

    @adam2392
    Member

    I'm +1 on this approach as (imo) sklearn should lead the way on dissecting one's ML model.

    longer-math summary from what I read in the above links

    To summarize PDP, and ALE based on what I was reading:

    For context, PDP, ALE, and matching-based approaches can be expressed using similar notation. Let:

    • (X) be the feature of interest;
    • (Z) be all remaining features;
    • ((X_i,Z_i)) be observation (i); and
    • (\hat f(x,Z)) be the fitted model.

    Partial dependence:

    $\frac{1}{n}\sum_{i=1}^{n}\hat f(x,Z_i)$

    Estimation procedure: Fix (X=x), evaluate the model using every observed (Z_i), and average. This estimates the model’s average prediction at (x) under the marginal empirical distribution of (Z).

    When (X) and (Z) are correlated, this may evaluate unrealistic combinations of (x) and (Z_i).

    Accumulated local effects:

    First, divide the observed range of (X) into intervals $B_k=[q_{k-1},q_k]$ where the boundaries $(q_0,\ldots,q_K)$ are usually empirical quantiles of (X). Let $N_k={i\in B_k}$ be the observations in bin (k).

    The average local model effect in that bin is

    $\frac{1}{|N_k|} \sum_{i\in N_k} \left[ \hat f(q_k,Z_i)-\hat f(q_{k-1},Z_i) \right]$

    ALE accumulates these local effects up to the bin containing (x):

    $\sum_{k\leq K(x)}\hat\delta_k-C$

    where (C) centers the resulting curve at zero, and K(x) is the index of the bin containing x.

    Thus, ALE changes (X) only across a local interval and averages over the (Z_i) values that naturally occur within that interval. This reduces the off-distribution evaluation that can occur with PDP.

  16. mayer79 commented on Sep 17, 2026

    @mayer79
    ContributorAuthor
  17. VimalN2005 commented on Sep 18, 2026

    @VimalN2005

    Hi @lorentzenchr @lucyleeow,

    I see the recent +1s for adding Accumulated Local Effects (ALE) to sklearn.inspection. I would be very glad to take this up and implement it.

    My proposed implementation plan is:

    1. Implement accumulated_local_effects(estimator, X, features, *, grid_resolution=100, ...) in sklearn/inspection/_accumulated_local_effects.py following the existing partial_dependence conventions.
    2. Compute feature quantiles/grid points, evaluate local difference predictions across interval boundaries, and accumulate the uncentered effects before centering by the mean effect.
    3. Provide an intuitive display helper (AccumulatedLocalEffectsDisplay) consistent with the display API.
    4. Add comprehensive unit tests covering regression and classification estimators, synthetic correlated data checks against analytical expectations, and documentation in the User Guide.

    Could you please confirm if I can go ahead with this plan? Thanks!

  18. StefanieSenger commented on Sep 21, 2026

    @StefanieSenger
    Member

    Hallo @VimalN2005, sorry but we cannot let you work on this. You have opened 47 PRs on 30 open source projects in only the last 3 weeks, many of them closed, because you didn't check for if this task was taken or otherwise solved already. In scikit-learn, we require contributors to do extensive research before opening a PR and we don't support fly-by generated PRs.

    Please refer to our Automated Contributions Policy

  19. solegalli commented on Sep 21, 2026

    @solegalli
    Contributor

    Hey everyone! I would like to work on this issue! @StefanieSenger @lucyleeow @lorentzenchr

    My proposal is to take the partial dependence function and its corresponding display function to produce the ALE values and plot. ALE is mostly a visual tool, so I think the plot needs to be there in addition to the values.

    I'll use @mayer79 's draft as a starter.

    ALE plots basically want to eliminate the caveat of PDP, which is that it can generate feature combinations that are not plausible given the data. For example, a man with menopause following @mayer79 's example, or polar bears living in australia.

    Having said this, this caveat is only eliminated if we build ALE plots for continuous features, because it takes derivatives on a small area rather than shift the values in large steps (in practice, it takes quantiles/intervals).

    For discrete features: the values are taken to the immediately small and immediately large values and then the effect is calculated. For categorical data, the procedure is the same after the encoding, but this, basically kills the purpose of ALE, so I would add a massive warning in the docs for example, or discourage the behaviour altogether, but need to think how.

    Let me know if this works.

  20. mayer79 commented on Sep 23, 2026

    @mayer79
    ContributorAuthor

    @solegalli : Thanks for the fat warning with discrete features. No need to start with my snippet.

    API related question: Do we want 2D ALEs? (I usually don't, but other people might like them).

  21. solegalli commented on Sep 23, 2026

    @solegalli
    Contributor

    I would add it, sklearn already has 2d plots for partial dependence. I'd try to follow closely that implementation for easy adoption.

  22. lionelkusch commented on Sep 28, 2026

    @lionelkusch

    I had made a possible modification here: https://github.com/lionelkusch/scikit-learn/tree/PR_ALE
    However, there is a need to make a decision about the way of computing quantiles because the scikitlearn's implementation and PyALE implementation are different.

    PyALE and you are using quantile from numpy. This function provides the value of quantiles from the data. In this case, using function unique, you remove all the empty quantiles and reduce the number of bins. In my case, I use mquantiles for calculating the quantiles. This function provides an estimation of the quantile. I can't use the function unique for removing empty ones because my quantile is not based on the data. However, I returned the number of bins expected.
    @mayer79 What do you think is the best strategy for computing the quantiles?

  23. lorentzenchr commented on Sep 28, 2026

    @lorentzenchr
    Member

    @lionelkusch As it stands, @solegalli is already working on it. I guess she will open a PR when ready.

  24. solegalli commented on Sep 28, 2026

    @solegalli
    Contributor

    Hi @lionelkusch yes, i am on it. Taking a little longer than expected. Hopefully I make a PR tomorrow, Wednesday the latest. Thanks for the patience.

  25. lionelkusch commented on Sep 29, 2026

    @lionelkusch

    This was the work that I have done one 1 year ago and the problem that I get when I want it to implement it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

ModerateNew Featuremodule:inspection

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions