You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Add Accumulated local effects (ALE) to inspection #30223
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.
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?
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.
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.
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.
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.
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.
---------------------------------------------------------------------------IndexErrorTraceback (mostrecentcalllast)
CellIn[16], line84X, y=load_diabetes(return_X_y=True, as_frame=True)
6est=HistGradientBoostingRegressor(max_iter=50, max_depth=4).fit(X, y)
---->8accumulated_local_effect(est, X=X, features=["s3"])
Filec:\Users\mayer\ai-tools-for-actuaries\.venv\Lib\site-packages\sklearn\utils\_param_validation.py:213, invalidate_params.<locals>.decorator.<locals>.wrapper(*args, **kwargs)
207try:
208withconfig_context(
209skip_parameter_validation=(
210prefer_skip_nested_validationorglobal_skip_validation211 )
212 ):
-->213returnfunc(*args, **kwargs)
214exceptInvalidParameterErrorase:
215# When the function is just a wrapper around an estimator, we allow216# the function to delegate validation to the estimator, but we replace217# the name of the estimator by the name of the function in the error218# message to avoid confusion.219msg=re.sub(
220r"parameter of \w+ must be",
221f"parameter of {func.__qualname__} must be",
222str(e),
223 )
CellIn[3], line357, inaccumulated_local_effect(estimator, X, features, sample_weight, categorical_features, feature_names, response_method, grid_resolution, custom_values)
355break356# code partially copy from ALEpython (https://github.com/blent-ai/ALEPython/blob/dev/src/alepython/ale.py)-->357quantile=quantiles[feature_idx]
358indice=indices[feature_idx]
359averaged_predictions, predictions=_partial_dependence_brute(
360estimator,
361 [[quantile[indice]], [quantile[indice+1]]],
(...) 365sample_weight,
366 )
IndexError: listindexoutofrange
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:
Implement accumulated_local_effects(estimator, X, features, *, grid_resolution=100, ...) returning an ALE computation bunch similar to PartialDependenceDisplay.
Compute feature quantiles/grid points, evaluate the local difference predictions on interval margins, and accumulate the uncentered effects before centering by the mean effect.
Provide an intuitive display helper (AccumulatedLocalEffectsDisplay or integration with the display framework).
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!
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).
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.
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:
Implement accumulated_local_effects(estimator, X, features, *, grid_resolution=100, ...) in sklearn/inspection/_accumulated_local_effects.py following the existing partial_dependence conventions.
Compute feature quantiles/grid points, evaluate local difference predictions across interval boundaries, and accumulate the uncentered effects before centering by the mean effect.
Provide an intuitive display helper (AccumulatedLocalEffectsDisplay) consistent with the display API.
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!
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.
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.
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.
Reacted by Stefanie Senger and Christian Lorentzen
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?
Activity
adrinjalali commentedon Nov 5, 2024
@glemaitre or @thomasjpfan maybe have an opinion on the inclusion criteria here.
glemaitre commentedon Nov 5, 2024
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?
mayer79 commentedon Nov 5, 2024
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.
lionelkusch commentedon Jan 20, 2025
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.
mayer79 commentedon Jan 20, 2025
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:
lionelkusch commentedon Feb 25, 2025
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:
mayer79 commentedon Feb 26, 2025
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.
mayer79 commentedon Jun 4, 2025
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.mayer79 commentedon Jun 7, 2025
This is a draft of an (almost...) Scikit-Learn compatible implementation:
https://github.com/mayer79/accumulated_local_effects
lionelkusch commentedon Jun 7, 2025
Can you compare the result with this code?
https://github.com/lionelkusch/scikit-learn/blob/PR_ALE/sklearn/inspection/_accumulated_local_effects.py
mayer79 commentedon Jun 7, 2025
Hello. Your code is actually much further than I had in mind, thx!
gives:
But maybe I did something stupid.
13 remaining items
VimalN2005 commentedon Sep 12, 2026
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_dependenceAPI:accumulated_local_effects(estimator, X, features, *, grid_resolution=100, ...)returning anALEcomputation bunch similar toPartialDependenceDisplay.AccumulatedLocalEffectsDisplayor integration with the display framework).Please let me know if I can go ahead and open a PR with the initial implementation and tests. Thank you!
Shikhar-Kesharwani commentedon Sep 13, 2026
Hi @lorentzenchr, @lucyleeow, and contributors,
I have submitted an implementation of Accumulated Local Effects (ALE) and
AccumulatedLocalEffectsDisplayin PR #34950 (#34950).Summary of Implementation:
accumulated_local_effects(estimator, X, features, ...)computes conditional interval differences and mean-centered ALE curves.AccumulatedLocalEffectsDisplaysupports.from_estimator()and.plot().adam2392 commentedon Sep 14, 2026
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:
Partial dependence:
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
ALE accumulates these local effects up to the bin containing (x):
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.
mayer79 commentedon Sep 17, 2026
Thx @adam2392 . Here is a simple, clean sketch: https://github.com/mayer79/accumulated_local_effects
VimalN2005 commentedon Sep 18, 2026
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:
accumulated_local_effects(estimator, X, features, *, grid_resolution=100, ...)insklearn/inspection/_accumulated_local_effects.pyfollowing the existingpartial_dependenceconventions.AccumulatedLocalEffectsDisplay) consistent with the display API.Could you please confirm if I can go ahead with this plan? Thanks!
StefanieSenger commentedon Sep 21, 2026
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
solegalli commentedon Sep 21, 2026
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.
mayer79 commentedon Sep 23, 2026
@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).
solegalli commentedon Sep 23, 2026
I would add it, sklearn already has 2d plots for partial dependence. I'd try to follow closely that implementation for easy adoption.
lionelkusch commentedon Sep 28, 2026
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.
lorentzenchr commentedon Sep 28, 2026
@lionelkusch As it stands, @solegalli is already working on it. I guess she will open a PR when ready.
solegalli commentedon Sep 28, 2026
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.
lionelkusch commentedon Sep 29, 2026
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.