Repository navigation
Description
Proposal
Add a Sensitivity Analysis (SA) function.
The function would compute Sobol' indices [1,2]. Consider a function f with parameters x1, x2 and x3. Hence y=f(x1,x2,x3). We are interested to know which parameter has the most impact, in terms of variance, on the value y.
I believe scikit-learn, and the wider scientific community, would greatly benefit to have such tool. I believe scikit-learn has something related with feature_importances_ in some regressors.
As an expert in the field, I would propose to develop the initial functionalities and provide long term support.
Background
Sobol’ indices are the cornerstone of SA and UQ and its application is not restricted to any field. It’s a non intrusive method which makes the only assumption that the variables are independent (this constraint can be alleviated).
Being able to compute sensitivity indices allows to reduce the dimensionality of a problem, better understand the importance of each factors and also see how parameters are interacting with each other. As such, it’s an important engineering tool. If you have 2 or more variables and only have the budget to improve your knowledge on one of them, this can help to make an informed choice. There are a lot of successful usage of SA in the literature and in real world applications. The EU (through the JRC), is now requiring to conduce uncertainty analysis when evaluating a system. They are recommending the use of Sobol’ indices.
Example
Let’s take an example with the Ishigami function:
y = sin(x1) + 7*sin(x2)^2 + 0.1*x3^4*sin(x1)
It’s not obvious to tell which variable would impact more y.
The Sobol’ indices are bounded from 0 to 1, with 1 meaning more important. Here they would be:
| Variable | First order Sobol’ | Total Sobol’ |
|---|---|---|
| x1 | 0.31 | 0.56 |
| x2 | 0.41 | 0.44 |
| x3 | 0.00 | 0.24 |
The difference between the first and total indices indicate an interaction between variables. The total indices allow to rank the variable by importance. x1 is the most important. Looking at the first orders, x3 by itself does not have an impact on the variance of the output. It’s its combination with another variable which makes it have a total impact of 0.24. x1 in this case also have a difference in first and total indices while x2 is the same. We can say that x1 and x2 have a second order interaction.
Computing the indices requires a large sample size, to alleviate this constraint, a common approach is to construct a surrogate model with Gaussian Process or Polynomial Chaos (to name the most used strategies). This allows to conduct a SA with a low computational budget (we see lots of engineering applications with expensive HPC codes taking advantage of this strategy).
Implementation
Here is an example implementation I did a while back:
Note that this implementation lack a few things such as higher order indices, other methods, input validation, doc, tests, other wrapping, etc. This is just to show how it works.
Alternatives
Practitioners might be more familiarized with gradient based technics. Keywords include: gradient, adjoint. These methods are local sensitivity analysis methods. And as such they are only capturing the sensitivity of the model in specific areas of the parameter space.
Sobol’ indices are variance based indices. There are other indices using higher moments, namely: moment independant based sensitivity analysis. These methods are very attractive and provide lot of information while being simple to compute/analyse. They have been less studied but there is an increasing interest in the community. I believe this would make a good second step.
References
Upon request, I can provide more information. Following are some fundational references–first 2 cited a few thousand times.
-
[1] Sobol',I.M. (2001), Global sensitivity indices for nonlinear mathematical models and their Monte Carlo estimates, MATH COMPUT SIMULAT,55(1–3),271-280, doi:10.1016/S0378-4754(00)00270-6
-
[2] Saltelli, A. et al., (2008), Global Sensitivity Analysis. The Primer, John Wiley & Sons, doi:10.1002/9780470725184
-
[3] Saltelli, A. et al., (2020), The Future of Sensitivity Analysis: An essential discipline for systems modeling and policy support, Environmental Modelling & Software, doi:10.1016/j.envsoft.2020.104954
For some examples of industrial applications (Part. 3), a visual explanation of some methods (Chap. 2.2) or more bibliography, you can also see my thesis:
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsNeeds decision
Activity
lorentzenchr commentedon Feb 13, 2022
@tupui Thanks for proposing this functionality. I would see it as part of the inspection module, another way of looking at feature importance.
I‘d be interested in the connection to other feature importance measures and whether it is possible to generalize it from "variance explained" to "metric/score explained", e.g., consider explaining a classifier.
tupui commentedon Feb 14, 2022
Thank you for having a look @lorentzenchr
That sounds sensible.
I am not sure how to make the bridge. Although there is a direct link with
sklearn.metrics.r2_score. If you make a model and you get a R2 (Q2 in my field) of 0.8, then your model explains 80% of the variance. If on top you compute Sobol' indices and it says one variable is responsible for 50% of the variance. It in fact can be said that this variable explains up to 50% of 80% of the model's variance.tupui commentedon Jun 29, 2022
@lorentzenchr I was wondering about the status here.
Also, I was thinking about your question a bit more and found this in the process https://hal.archives-ouvertes.fr/hal-03151611
Correct me if I am wrong, but feature importance is computed by looking at the impact a parameter has on the output metric of a model (improving R2 or a classification metric). Then we can say that a given parameter has more impact than another, but just for this modelling. This way a modeller can focus on a given parameter while tuning a model, etc. But choosing another kind of model might lead to a different hierarchy/importance since the inner working would be different. In practice, maybe it does not matter much.
On the other hand, sensitivity analysis does not care about modelling an only take into account the outcome of a system-or model in this case. It would not matter which type of model is used. This metric is useful to inform user, policy makers, etc. to know which parameter is important and they might want to focus their attention on.
TL;DR to me it's a modeller vs user of the model difference. Both are complementary, the modeller seek to improve its model focusing on some parameters, while the user want to understand which parameter impact the system itself.
lorentzenchr commentedon Jul 1, 2022
I think it needs a bit more discussion, in particular from domain experts.
@glemaitre @thomasjpfan @GaelVaroquaux @adrinjalali @ogrisel may have a view w.r.t to the inspection module.
A short notebook with an example would help me a lot in understanding.
Note that there are different kinds of feature importances: Those measuring the drop in some performance/accuracy measure like R2. And those computing feature attribution to the predicted value(s) like SHAP. Global methods do it for a data sample, local ones for single observations.
IIUC, sensitivity analysis can be viewed as a global method measuring drop in R2.
adrinjalali commentedon Jul 1, 2022
The only thing I'm wary of, is that it assumes features are independent, and they pretty much never are. So in reality, this is only useful if we do alleviate those issues.
On the other hand, this can be said about other inspection tools we have I think.
This would make sense, if we could also give users a nice easy guide on how to choose the way they should be inspecting their model.
tupui commentedon Jul 1, 2022
Considering
y = f(x1, x2), sensitivity analysis is looking at whetherx1orx2matters by looking atvar(y|x_i)/var(y).Which is different than measuring a variation on R2. Depending on your model, one parameter could matter more for R2 than it actually matter for
var(f).It depends what you are talking about. Sobol' indices do capture parameters interactions. But it assumes that parameters are independently draws/distributed. So x1 varies in function of x2.
There are ways to deal with parameter dependence with Sobol'. But other methods might be more appropriate/easy. E.g. Shapley values or moment independent methods.
In my experience though, parameter independence does not represent the majority of cases.
100% on more tutorials/doc on feature importance/sensitivity analysis.
tupui commentedon Feb 1, 2023
I will close the issue. Meanwhile, I got this into SciPy: https://scipy.github.io/devdocs/reference/generated/scipy.stats.sobol_indices.html
I am bit sad no decision was made in such a long time (I am not blaming anyone here, we have the same issue in SciPy I am afraid). Thanks for the discussions though 😃
glemaitre commentedon Feb 2, 2023
I would still let the issue open since the discussion happen. I personally did not get time to dedicate to catching up with the topic.
We usually have predefined conditions for inclusion: a couple of hundred citations and a 5+ years old research. Up to now, I don't have the impression that it was used mainstream so we would need to ease the inclusion criterion and thus be sure of what are the limitations of the method.
I will start to have a look at the SobolMDA for trees since it alleviates one of the caveats of the MDA.
API-wise, we are facing some legacy choices and we should probably go back to #9606. It could ease the inclusion of new "feature importance" methods.
tupui commentedon Feb 2, 2023
Thanks @glemaitre
SobolMDA is a specific application of Sobol' to random forest (AFAIU, never looked into it). To be clear, here I was proposing the general Sobol' method.
For Sobol' indices, we are way passed the inclusion criteria. Books like
Global sensitivity analysis: the primerhave thousands of citations (this one mostly talk about Sobol' indices). And the original paper on Sobol' indices also has a few thousands citations.You also have: international conferences/groups like SAMO, MASCOT-NUM, MCM ; Journals like IJUQ ; summer schools (SAMO) ; several labs groups ; a whole JRC group. The common denominator of all that is global sensitivity analysis and the most used method is Sobol' indices.
Real life example are all over the place. E.g. at EDF for nuclear safety, dam analysis or even flood modelling (LNHE, Schapi, ...). The JRC group I mentioned above also used this a lot to drive policies (CO2MPAS was improved with Sobol' indices).
On tools, you have multiple options: SALib , OpenTURNS (from EDF and used quite a bit in France), Dakota, uncertainpy, MUQ, tons of R packages (e.g.
sensobol), UQLab (Matlab framework). And now SciPy.This article is a good read about the state of SA https://doi.org/10.1016/j.envsoft.2020.104954
12 remaining items
PieterjanRobbe commentedon Sep 18, 2025
Here's a very simple and contrived example where the permutation importance and Sobol' indices are different.
Take two independent inputs$X_1, X_2 \sim U[-1, 1]$ , and define the model
The (first-order) Sobol sensitivity indices should be:
That is, there are no main effects, and all of the variance is caused by the interaction term.
So in this example, Sobol' first-order indices say that there's no single-feature contribution (only an interaction term), while using permutation importance, both features will show up as important (because they both appear in the interaction term$X_1X_2$ ).
The total Sobol' sensitivity indices are$S_{T_1} = S_{T_2} = 1$ .
Using a slight adaptation of @ogrisel's code, here are the results:
Details
ogrisel commentedon Sep 22, 2025
Maybe the training dataset size and/or the number of samples are too small to get an accurate estimate of the total SI from either RFs or from the PCE surrogate model for this problem. There is a discrepancy, but it's not a factor of two. I used the same code for all three dataset generators.
ogrisel commentedon Sep 22, 2025
Assuming mutually independent features (which is the case here), and a consistent surrogate regressor, the permutation importance values (computed for the MSE score) should converge to two times the (unormalized) Total Sobol Indices as per section 5.3 of https://arxiv.org/pdf/2507.17306.
I believe the discrepancy observed in the plot of #22453 (comment) is caused by the very small number of points used both as training and test & sampling sets. I tried removing the normalizations, setting
scoring="neg_mean_squared_error"forpermutation_importance(instead ofscoring="r2"), increasing the number of data points (and Sobol samples) and all methods seem to converge up to normalization factors: both features have equal PI values and equal total Sobol indices. However, there seems to be a constant factor problem that would need to be investigated.tupui commentedon Sep 22, 2025
You can use Sobol' indices (by the way, the name includes the ' mark so you have to write Sobol') with discrete inputs as well, there is no problem with that. It works as well with discrete distributions.
The choice of the distribution when sampling is very important as you don't necessarily capture the same information from your space. The one rule is that there is an independence between the parameters (no copula). Though there are extensions to try to work with dependent input variables.
There is a bit of literature there and there comparing all that. The usual comparison people do is not just sampling + Sobol' vs PCE. But GP + Sobol' vs PCE. Otherwise it's not really a fair one. Once you have the GP you can sample pretty fast to get converged indices.
If you use PCE or GP it usually means that your model or experiment is costly and you can only afford a specific computational budget. At that point, the interpolation cost of GP is null basically.
There is no clear winner. Usually experts of PCE will say they are the best. Experts of GP will go the other way around 😅
From my side, the main issue with PCE is that it's way more involved than GP for a random person. If you want something competitive you need to go with LARS, sparse, etc. And even so, at least in my experience and from the literature I've reviewed, GP is either similar or better (and saying that because I am on the GP camp of course).
In the end, as long as you do not have very wrong indices, it's fine since you use the output to say x1 is more important than x2. Does not really matter much if it's 42 or 42.3% of explained variance.
ogrisel commentedon Sep 22, 2025
How would you do that? The GP gives you the ability to sample from an estimate of
Y|X=x_ifor a given p dimensionalx_ibut you probably don't want to draw all your samples from a single choice ofx_i. Do you do some form of 2 level sampling? First samplenx_ivalues and for each of those drawn'samples from your GP estimate ofY|X=x_ito assemblen * n'sample of your estimate ofY|X? If so, how do you choosenandn'?tupui commentedon Sep 22, 2025
Not sure I get the question.
Taking an example. If you have your model like Ishigami
Xi(ideally with a QMC sample like Sobol' or Halton).Xibased on the Saltelli sampling or the method you want to use for calculating Sobol' indices. The Saltelli method is making a few matrices. You generate 2 independent samples (using Sobol' or Halton QMC method) then you do some columns permutations to have 1 or 2 other samples.PieterjanRobbe commentedon Sep 23, 2025
I think that's because the paper compares "unnormalized" total Sobol' sensitivity indices to (conditional) permutation importance values. The normalization factor here is the variance. In our example, this is
I get the same values if I rescale all Sobol' sensitivity indices by the variance and plot raw permutation importance values instead of normalized ones. So I think the relation we're looking for is
where$V$ is the variance of the output.
Details
%%
Import statements
from sklearn.inspection import permutation_importance
from sklearn.model_selection import train_test_split
from sklearn.polynomial_chaos import PolynomialChaosRegressor
import itertools
import numpy as np
from scipy.stats import sobol_indices, uniform
import matplotlib.pyplot as plt
%%
Set seed
seed = 123
np.random.seed(seed)
%%
Generate training data
n_sobol = 4096
n_samples = 4 * n_sobol
distributions = [uniform(loc=-1, scale=2)]*2
X = np.vstack([distribution.rvs(n_samples) for distribution in distributions]).T
y = X[:, 0] * X[:, 1]
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
%%
Use a sparse solver
model = PolynomialChaosRegressor(distribution=[uniform(loc=-1, scale=2)]*2)
%%
Fit the model
model.fit(X_train, y_train)
print(f"R^2 on test set: {model.score(X_test, y_test):.2f}")
%%
Compute permutation importance
pi = permutation_importance(
model, X_test, y_test, n_repeats=10, random_state=0, scoring="neg_mean_squared_error"
)
normalized_pi = pi.importances_mean #/ np.sum(pi.importances_mean)
%%
Compute Sobol indices (from model)
si = sobol_indices(func=lambda x: x[0] * x[1], dists=distributions, n=n_sobol, rng=seed)
%%
Assume model has d input features
d = X.shape[1]
feature_names = [f"x{i+1}" for i in range(d)]
Collect all main effects
indices_first_pce = []
labels = []
for i in range(d):
indices_first_pce.append(model.joint_sens(i) * model.var())
labels.append(feature_names[i])
Collect all joint effects (pairwise and higher order if desired)
for r in range(2, d+1):
for combo in itertools.combinations(range(d), r):
indices_first_pce.append(model.joint_sens(*combo) * model.var())
labels.append(", ".join(feature_names[j] for j in combo))
indices_first_pce = np.array(indices_first_pce).ravel()
indices_total_pce = np.zeros(len(labels))
indices_total_pce[:d] = model.total_sens() * model.var()
Pad external importances (only for main effects)
normalized_pi_full = np.zeros(len(labels))
normalized_pi_full[:d] = normalized_pi # assumes normalized_pi is length d
sobol_first_full = np.zeros(len(labels))
sobol_first_full[:d] = si.first_order * np.var(y) # assumes si.first_order is length d
sobol_total_full = np.zeros(len(labels))
sobol_total_full[:d] = si.total_order * np.var(y) # assumes si.total_order is length d
Collect all importances
importances = [
("1/2 * PI", 0.5*normalized_pi_full),
("Unnormalized Sobol first order", sobol_first_full),
("Unnormalized Sobol total order", sobol_total_full),
("PCE Unnormalized Sobol first order", indices_first_pce),
("PCE Unnormalized Sobol total order", indices_total_pce),
]
Plot
y_pos = np.arange(len(labels))
width = 0.5
fig, ax = plt.subplots(figsize=(10, 6), constrained_layout=True)
for i, (label, values) in enumerate(importances):
ax.barh(
y_pos + i * width / len(importances) - (len(importances) - 1) * width / 2 / len(importances),
values,
width / len(importances),
label=label,
)
ax.set_yticks(y_pos, labels=labels)
ax.invert_yaxis()
ax.set_xlabel("Importance")
ax.set_title("Feature Importance: PI vs Sobol (sampling vs PCE)")
ax.legend(loc="upper left", bbox_to_anchor=(1, 1), frameon=False)
plt.show()
PieterjanRobbe commentedon Sep 23, 2025
Oh, I didn't mean to point fingers 😉 I was talking about sampling-based versus meta-modeling approaches in general.
I'd say GPs have their own issues too (scaling, kernel assumptions, hyperparameter tuning), so it really depends on the problem which one works better.
ogrisel commentedon Sep 23, 2025
@PieterjanRobbe I independently came up to the same conclusion. By further increasing the sample size, the 3 methods converge as expected:
It's nice to see that theory works as expected ;)
ogrisel commentedon Sep 23, 2025
Thanks for the follow-up, @tupui.
But sample speed is GP independent, right? I fail to see why a GP is needed in the procedure described in #22453 (comment).
You could use any other (expressive enough) surrogate model, such as kernel ridge regression (possibly implemented with a Nyström approximation to scale to large training sets), neural networks or gradient boosted regression trees, no? All those models are fast to predict (linear complexity w.r.t. the test sample size), so there should be no reason to limit ourselves to GPs, right?
tupui commentedon Sep 23, 2025
Totally 👍 it's just that in the literature you often see the comparison between GP/PCE for global sensitivity analysis.
ogrisel commentedon Sep 23, 2025
Thanks for the clarifications @tupui.
Now it would be interesting to study the convergence speed for MSE-PI-based and Saltelli-based Total Sobol' indices estimation for a fixed choice of surrogate model when increasing the sample size for various regression tasks (with different complexity and dimensionality) similarly to what @PieterjanRobbe did for the Friedman synthetic datasets in #22453 (comment)
Also, for regression tasks with strong mutual dependencies in the feature space, Permutation Importance no longer converges to the Total Sobol' Index. But CFI (Conditional Feature Importance) does (as discussed in https://arxiv.org/abs/2507.17306). However, CFI require fitting extra auxiliary models (one per feature) to model the conditional expectations of the features. Here is an example implementation of CFI in Python illustrated on a dataset where CFI and PFI do not find the same feature importance values: https://hidimstat.github.io/dev/generated/gallery/examples/plot_pitfalls_permutation_importance.html
tupui commentedon Sep 23, 2025
You have yourself a nice article if you do that comparison 😉
ogrisel commentedon Sep 24, 2025
Ping @GaetandeCast ;)
mbaudin47 commentedon Oct 2, 2025
Hi @tupui There is an interesting benchmark in 1. From my point of view, it reveals that GP performs better when the sample is relatively small or the function is highly non linear (because interpolating the data is more robust) and PCE performs better when the sample size is relatively large and the function is smooth (because of the spectral convergence). The trend used for testing the Morris function using GP is particularly revealing in my opinion (see 1 page 1317).
Footnotes
Gratiet, L. L., Marelli, S., & Sudret, B. (2017). Metamodel-based sensitivity analysis: polynomial chaos expansions and Gaussian processes. R. Ghanem et al. (eds.), Handbook of Uncertainty Quantification. ↩ ↩2