Repository navigation
FEAT Polynomial Chaos Expansions - #27842
PieterjanRobbe wants to merge 86 commits into
Conversation
…c) to 88 columns (default value in 'black') to make sure that CI linters pass
|
Here's an overview of all examples (rendered in the docs):
|
|
Sounds interesting. What does the scikit-learn team need to verify this pull-request? |
|
@ogrisel @glemaitre @thomasjpfan - apologies for the ping. Just gauging interest in this PR. |
|
Thanks for the very well written PR description and extensive examples. Unfortunately I am not familiar at all about this branch of the literature so it will require me a significant effort just to understand how it could fit with the rest library and judge whether it's something we would like to maintain as part of scikit-learn or not. To ease this this process, could you please answer the following questions:
|
I really like this suggestion! Let me try to take a stab at this. |
You should avoid this when the degree is larger than 1 because evaluating a polynomial in the canonical basis is numerically unstable. |
This is an interesting output indeed. I implemented and the result is shown here: |
Thank you for pointing the unit tests. As far as I can see, there is only one unit test where the coefficients of a simple PCE are checked. In the other ones, the test checks the predictions from the PCE, but not the multi-indices and the coefficients themselves. Therefore, bugs in the implementation may be unrevealed by these tests. This is the same as the difference between forward and backward stability. So a new unit test is required in my opinion, not an example. |
That is reassuring for both of us! I wonder what happens when the degree gets really large, say 15 to 20 for example. This is the degree required by the Ishigami function to get close to machine precision using the Legendre basis. Moreover, i wonder if it would be possible to provide a SciKit interface to OpenTURNS's PCE instead of developing a brand new implementation from scratch. Let me think about the advantages :
On the other hand, OT users will benefit from the pipeline features from SK that are not available in OT. On top of that, you may save a significant fraction of the source code and be sure that 1) the new feature is really an improvement over what already exists un OpenTURNS, 2) be sure that the component can be extended if needed. @PieterjanRobbe can you see other advantages? |
Ah, sorry, you might be looking at the wrong commit. I've added the unit test for Ishigami with Fourier basis in da25f98. Here's the most recent version of the unit tests (note: these tests are for the |
I was thinking we could print the PCE in terms of the associated
Then the utility would print: import numpy as np
from numpy.polynomial.legendre import Legendre
def pce_model(X):
y = np.zeros(X.shape[0])
# (0, 0)
y += 1.2
# (1, 0)
y += 0.5 * Legendre.basis(1)(X["feature_0"])
# (0, 1)
y += -0.3 * Legendre.basis(1)(X["feature_1"])
# (2, 0)
y += 0.1 * Legendre.basis(2)(X["feature_0"])
# (0, 2)
y += 0.05 * Legendre.basis(1)(X["feature_0"]) * Legendre.basis(1)(X["feature_1"])
return yNote that this is not the most efficient code. For one thing, the basis can be precomputed for each feature up to the maximum degree in that feature by forming the Vandermonde matrix. That's how I do it in the implementation. That is less human readable though, so we'll need to find a balance. |
Hi @mbaudin47, these are all good points, thanks! I’d like to clarify a few points:
I agree that the OpenTURNS implementation is very complete and efficient. At the same time, I’m not sure the scikit-learn team would want to include OpenTURNS as a dependency, since the two projects seem to serve different needs? The current code should be fairly extensible and integrates with scikit-learn’s pipeline approach, as you mention, so I believe it could stand on its own. Also, for context, this PR is about 2 years old. I was not aware of the OpenTURNS implementation at that point 😊 |
Indeed, this is not going to happen. However, OpenTURNS itself could decide to provide a scikit-learn compatible interface to PCE in an hypothetical |
I agree that this does bring value in itself. Having it as part of the scikit-learn main repo would alsp offer a generic way to train non-linear regressor with a somewhat interpretable and smooth learned decision functions, which is quite a unique and interesting feature in itself (glassbox machine learning). |
You mean like https://github.com/mbaudin47/otsurrogate 😅 Yep we have done stuff like that in the past and that can definitely be updated. |
Or perhaps like https://github.com/openturns/otsklearn 😉 |
|
Ah yes I was looking for that one haha. |
mbaudin47
left a comment
There was a problem hiding this comment.
The doc is already very clean: thank you for sharing this work! But there is still room for improvement in the doc in my opinion.
| * If :math:`P \ll n` (many training samples, few basis terms): | ||
|
|
||
| .. math:: | ||
| \mathcal{O()}(nP^2 + P^3) |
| * If :math:`P \gg n` (many basis terms, few training samples): | ||
|
|
||
| .. math:: | ||
| \mathcal{O()}(n^2P + n^3) |
There was a problem hiding this comment.
Same here:
| \mathcal{O()}(n^2P + n^3) | |
| \mathcal{O}(n^2P + n^3) |
(As a side comment, the analysis is interesting : +1)
| * When the output data is noisy, as is the case in almost all real-world | ||
| problems, use regularization to avoid overfitting. See also |
There was a problem hiding this comment.
The fact that "almost all real-world problems" are noisy is likely to be a personal point of view. Furthermore, another motivation for using a sparse solver is the case where the sample size is less than the number of coefficients or not really larger. Here is my suggestion:
| * When the output data is noisy, as is the case in almost all real-world | |
| problems, use regularization to avoid overfitting. See also | |
| * When the output data is noisy or when the sample size is not sufficiently large | |
| compared to the number of coefficients, use regularization to avoid overfitting. | |
| See also |
|
|
||
| References | ||
| ---------- | ||
|
|
There was a problem hiding this comment.
I would suggest to add (Ghanem & Spanos, 1991) because they were the first to make the method popular.
| .. [Ghanem1991] `Ghanem, R. G., & Spanos, P. D. (2003). "Stochastic finite elements: a spectral approach. Springer. | |
| <https://link.springer.com/book/10.1007/978-1-4612-3094-6>`_ | |
| ---------------------------- | ||
|
|
||
| This example illustrates how Polynomial Chaos expansions work by constructing a | ||
| surrogate for a one-dimensional test problem. The first figure below shows the |
There was a problem hiding this comment.
| surrogate for a one-dimensional test problem. The first figure below shows the | |
| surrogate for a one-dimensional test problem with a relatively small noise. The first figure below shows the |
| .. figure:: ../auto_examples/polynomial_chaos/images/sphx_glr_plot_pce_ishigami_004.png | ||
| :target: ../auto_examples/polynomial_chaos/plot_pce_ishigami.html | ||
| :align: center | ||
|
|
There was a problem hiding this comment.
As the sampling method is based on a Monte-Carlo sample, its convergence to the true Sobol' index has order 1/sqrt(n). Hence, we must multiply the sample size by 4 in order to divide the error by 2. In this case, using a logarithmic X-axis would make more sense from my point of view.
| basis growth to perform a Global Sensitivity Analysis of the Sobol function. The | ||
| Sobol function (also known as the :math:`G` function, because it was denoted as | ||
| such in the original paper by Sobol), is another well-known test problem in |
There was a problem hiding this comment.
See e.g. on Wikipedia.
| basis growth to perform a Global Sensitivity Analysis of the Sobol function. The | |
| Sobol function (also known as the :math:`G` function, because it was denoted as | |
| such in the original paper by Sobol), is another well-known test problem in | |
| basis growth to perform a Global Sensitivity Analysis of the Sobol' function. The | |
| Sobol' function (also known as the :math:`G` function, because it was denoted as | |
| such in the original paper by Sobol'), is another well-known test problem in |
| accurate Polynomial Chaos surrogate model. Despite the relatively low dimension | ||
| of the problem, this example demonstrates the challenges faced when constructing | ||
| higher-order accurate Polynomial Chaos surrogates. We then discuss the adaptive |
There was a problem hiding this comment.
I think that this comment somewhat hides the true problem. The difficulty from the PCE's point of view is that this is a product of univariate functions involving the absolute value. Hence, it is continuous, but cannot be differentiated: this is the main issue here.
| higher-order accurate Polynomial Chaos surrogates. We then discuss the adaptive | ||
| basis construction approach from [Gerstner2003]_., that somewhat alleviates this | ||
| issue. | ||
|
|
There was a problem hiding this comment.
The plot presents the sensitivity indices, which is somewhat unrelated to the previous paragraph. Perhaps the next figure (the relative error depending on the number of iterations) would better fit?
| accurate Polynomial Chaos surrogate model. Despite the relatively low dimension | ||
| of the problem, this example demonstrates the challenges faced when constructing | ||
| higher-order accurate Polynomial Chaos surrogates. We then discuss the adaptive | ||
| basis construction approach from [Gerstner2003]_., that somewhat alleviates this |
There was a problem hiding this comment.
| basis construction approach from [Gerstner2003]_., that somewhat alleviates this | |
| basis construction approach from [Gerstner2003]_, that somewhat alleviates this |
|
Disclaimer: I am not an expert on PCE. Polynomial chaos expansion seems to be almost an industry standard for uncertainty quantification. The relevant question is how good a fit it is for scikit-learn. I see 2 main problems: PCE serves another use case than scikit-learn, not prediction but uncertainty quantification. It can only handle a few (dozens) if features, but scikit-learn is usually build to manage many (like maaaany) features. I therefore propose to close this PR and instead open a new project under https://github.com/scikit-learn-contrib/. |
|
I therefore close this PR with best intentions. |
|
Apologies for the long silence here, I haven't looked at this PR in quite a while. I would like to politely push back a little on the argument that PCE is primarily a UQ method rather than a predictive model. In the setting implemented here, PCE is fundamentally a supervised regression/surrogate model: it is fitted from (X, y) data and used to predict outputs at new inputs. The fact that moments and sensitivity indices can also be obtained analytically (i.e., the UQ aspect of the method) is an additional capability, rather than intended use. In that sense, Gaussian process regression already implemented in scikit-learn arguably serves a very similar purpose: it is commonly used as a surrogate for expensive functions, while also providing uncertainty information, and it is likewise most applicable to relatively low-dimensional problems. Of course I'm not suggesting that the existence of Gaussian processes by itself means PCE should necessarily be included. There may be other considerations that I'm not aware of. Given the amount of discussion and work that has gone into the PR, would you be open to reconsidering the closure, or at least discussing the scope question a little further before making this a final decision? |
|
Closing does not mean the discussion can't go on... We usually prefer to open an issue before adding a PR. All references for PCE you gave are in the context of UQ or of sensitivity analysis. As such it seems highly valuable. As supervised learning model, scikit-learn must ask: What is the use case where PCE is (clearly) better than any already existing supervised model in scikit-learn (with a user point of view what "better" means), see #27842 (comment). From what I understand, one missing piece in scikit-learn is to make polynomial expansion orthogonal. We could add this. As this PR is very extensive (and it adds many new "utilities"), I honestly think it would be much easier to ship it under scikit-learn-contrib. If it proves valuable, we can reconsider and, maybe, add a simplified version in the future. This was the path of the successful |


Note: I've labeled this PR as [MRG], following this section from the Developer's Guide, but please let me know if this is inappropriate at this stage.
What is it?
The Polynomial Chaos expansion (PCE) is a supervised learning technique that is used to represent and propagate uncertainties in complex models. It is a well-known tool for sensitivity analysis and uncertainty quantification, that has been used in a variety of applications, see, for example, [Ghanem1991] and [Najm2009].
The basic idea is to represent the parameters (input features) of the model as random variables with an associated probability density function. The model output, which is also a random variable, is then expressed as a polynomial function of the input random variables.
The Polynomial Chaos methodology has found widespread use in engineering and applied sciences in the last decades, because it presents a systematic and efficient framework for dealing with parameteric uncertainty in mathematical models.
This is a proposal for an implementation that adds Polynomial Chaos expansions to
scikit-learn.How does it work?
Given a set of input features$X$ , sampled from an assumed distribution, the Polynomial Chaos approximation for the model output $y = f(X)$ is
where$\Psi_j$ is a multivariate orthogonal polynomial basis function, and $c_j$ is a coefficient in the expansion. The type of orthogonal polynomial depends on the assumed distribution for the input features. For example, the uniform distribution is associated with the Legendre polynomials, the normal distribution is associated with the Hermite polynomials, and other distributions can be matched to similar orthogonal polynomials from the Askey scheme, see [Xiu2002].
(Note that I'm deliberately ignoring some mathematical details in this description - I do take care of these in the actual implementation.)
Implementation details
In
scikit-learnlanguage, the PCE can be interpreted as a pipeline with a nonlinear tranformer that transforms the input features into orthogonal polynomial features, followed by a linear regression step:Thus, this PR introduces two new classes:
OrthogonalPolynomialFeaturesandPolynomialChaosRegressor. The former is a transformer class that is an extension of the existing PolynomialFeatures class, but uses orthogonal polynomials instead of simple monomials. The latter is aBaseEstimatorthat implements the pipeline described above.After fitting, the PCE can be used as a surrogate model to replace further evaluations of the model problem (using the
predictmethod from theBaseEstimatorclass).Why add Polynomial Chaos expansions to
scikit-learn?Existing tools for constructing PCEs are either not written in Python (uqlab, dakota), have poor performance in high dimensions (chaospy) or have complex API designs (pygpc). Recognizing these limitations, I believe there is a clear opportunity for a well-designed PCE tool that overcomes these issues.
The construction scheme (a pipeline with a nonlinear
transformerfollowed by alinear_model) outlined in the previous section, aligns seamlessly withscikit-learns modular API. In addition, we can use the manylinear_models inscikit-learnto help avoid overfitting, a common problem when constructing PCEs with noisy and/or limited data. It's worth mentioning thatchaospyandpygpcalready rely onscikit-learnestimators for similar purposes.To illustrate the efficiency statement above, we compare the performance of
chaospy,pygpcand the scikit-learn implementation by constructing a PCE for the Sobol function in 4 dimensions (i.e., 4 input features). The Sobol function is a well-known test function in sensitivity analysis and uncertainty quantification.The figure on the left shows the time needed to construct the PCE as a function of the maximum degree of the polynomials in the expansion. The figure on the right shows the same, but now with a logarithmic vertical axis. The
scikit-learnimplementation is significantly faster than the established tools, depite the reasonably moderate dimension. When considering dimensions other than 4, we observe a similar or even better speedup, see this notebook.Global Sensitivity Analysis
A common postprocessing step after the Polynomial Chaos expansion has been fitted is to perform a Global Sensitivity Analysis by computing the so-called Sobol sensitivity indices. These indices rank the input features by importance, by computing what fraction of the variance of the output they explain. When a PCE surrogate model has been fitted, these indices can be computed analytically, see for example [Sudret2008].
In the proposed implementation, the sensitivity indices can be computed by calling the
main_sens()andtotal_sens()methods against an instance of thePolynomialChaosRegressorclass.As a side note, I found this PR that also discusses Global Sensitivity Analysis. However, the method proposed in the latter PR is a pure sampling-based method, and sensitivities extracted from Polynomial Chaos expansions can be a lot more reliable (see the Ishigami example in the documentation for a comparison between the two).
Motiviation
This porposal has mainly been written because of my disappointment with the existing tools. I regularly use Polynomial Chaos expansions for research purposes, and not having a reliable, scalable and user-friendly implementation available has hurt me on more than one occasion. Hence the motivation to supply my own implementation.
I sincerely welcome feedback and collaborations to make this porposal a valuable addition to the
scikit-learnecosystem. Thanks!References
The [number] after each reference indicates the number of citations (following Google scholar).
[Ghanem1991] Ghanem, R. G., and Spanos, P. D. "Stochastic finite elements: a spectral approach", Springer New York, 1991. [8500+]
[Xiu2002] Xiu, D., and Karniadakis, G. M. "The Wiener-Askey polynomial chaos for stochastic differential equations." SIAM Journal on scientific computing 24(2), 2002. [5500+]
[Sudret2008] Sudret, B. "Global sensitivity analysis using polynomial chaos expansions." Reliability engineering & system safety 93(7), 2008. [2500+]
[Najm2009] Najm, H. N. "Uncertainty quantification and polynomial chaos techniques in computational fluid dynamics." Annual review of fluid mechanics 41, 2009. [1000+]