Algorithmcore
Regression-based polynomial chaos
Also called least-squares polynomial chaos, point collocation polynomial chaos, polynomial chaos regression.
Fits polynomial chaos coefficients by least squares to model runs at random or designed inputs, with more runs than coefficients.
- Time
- O(N (C + P^2)) worst
- Space
- O(N P) extra
- Where
- C = the cost of one model run; N = the number of model runs (N >= P); P = the number of chaos terms (d+p choose p); d = the number of inputs; p = the total degree
- Model
- Real RAM
- Properties
- randomizednot exactnot intrusive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Albert Cohen, Mark A. Davenport, Dany Leviatan, Geraud Blatman, Bruno Sudret, 2013
Regression-based polynomial chaos fits the coefficients of a polynomial chaos expansion to a set of model runs by least squares. It draws input points, runs the model at each, and chooses the coefficients that minimize the sum of squared differences between the expansion and the outputs. Unlike spectral projection by quadrature, it accepts any set of points, so the runs can come from random sampling, a Latin hypercube or an existing database. The number of runs must exceed the number of coefficients ; a common rule of thumb (a heuristic, not a theorem) is to . The leave-one-out error, computed from one fit by the hat matrix identity, measures how well the expansion predicts new runs.
In plain words
You want a polynomial formula that copies a slow model, so that you can compute averages and sensitivities from the formula instead of the model. Run the model at a few hundred random inputs. Then pick the polynomial that passes as close as possible to all the outputs, in the sense of the smallest total squared miss. This is ordinary curve fitting with special polynomials, and one linear solve gives all the coefficients. To check the fit, leave out one run, fit again, and see how badly the new fit predicts the run you left out; average this over all runs. A simple formula gives this average from the single fit, so you do not need to refit. Take about two or three times as many runs as there are coefficients.
The problem
The input has independent components with laws . The output is square integrable, and can only be evaluated. The basis is orthonormal for the law of , and the index set is with terms. Given points and the outputs , find
together with an estimate of the error of on new inputs. The moments and the Sobol indices then follow from as for any orthonormal expansion.
The algorithm
REGRESSION-PCE(q, ρ, p, N)- 1
Λ ← all α ∈ ℕ^d with |α| ≤ p; P ← |Λ|; require N ≥ P - 2
draw x_1, ..., x_N independently from ρ - 3
y_i ← q(x_i) for i = 1..N ▷ N model runs - 4
A[i, α] ← Ψ_α(x_i) ▷ N × P design matrix - 5
solve (A^T A) c = A^T y by Cholesky - 6
h_i ← A_i (A^T A)^{-1} A_i^T; ε_LOO ← (1/N) Σ_i ((y_i - A_i c) / (1 - h_i))^2 / Var(y) - 7
return c, ε_LOO
Line L1 builds the total degree set. Line L2 draws the points from the input law, which makes an unbiased estimate of the identity, because . Line L3 is the only place that runs the model, and the runs are independent. Line L4 evaluates the one dimensional polynomials by their recurrence and multiplies them. Line L5 solves the normal equations with the Cholesky decomposition of the Gram matrix; when is ill conditioned, a QR decomposition of is the safer choice. Line L6 computes the leverages , the diagonal of the hat matrix , from the same Cholesky factor: . The ratio is exactly the error at of the fit without run , so is the leave-one-out mean squared error, divided by the sample variance of the outputs.
Example
The Ishigami function with and uniform on has mean 3.5, variance 13.84459, and total index . The fit uses the Legendre basis of total degree , so , and random uniform points. Each row of the table is a measurement over the five seeds 0 to 4. The validation error is the mean squared error on 2000 fresh random points divided by the variance.
| mean, range over seeds | , range | median | median validation error | ||
|---|---|---|---|---|---|
| 167 | 1.01 | -0.34 to 4.37 | 0.023 to 0.272 | 5.5 | 2.3 |
| 247 | 1.5 | 3.482 to 3.564 | 0.304 to 0.316 | ||
| 330 | 2 | 3.457 to 3.504 | 0.309 to 0.314 | ||
| 495 | 3 | 3.486 to 3.503 | 0.311 to 0.314 |
With almost as many runs as coefficients, the fit is useless: a relative error above 1 means that the expansion is worse than the constant mean. From on, the error falls fast, and the leave-one-out error tracks the validation error within a factor of about 2 without any extra runs. For comparison, the tensor Gauss rule of spectral projection needs 729 runs at .
Correctness
If the design matrix has full column rank, then is symmetric positive definite, the Cholesky factor exists, and the solution of line L5 is the unique minimizer: for any , because the residual is orthogonal to the columns of . If lies in the span of , , then , and the minimizer is itself, with a zero residual. With random points, full rank holds with probability 1 for polynomial bases and (the zero set of a nonzero polynomial has measure zero). The leave-one-out identity follows from the Sherman-Morrison formula applied to . The proof file gives these steps in full.
Stability is a theorem only for enough runs. Let . Cohen, Davenport and Leviatan proved that if with an explicit constant depending on a chosen , then with probability at least the empirical Gram matrix has all eigenvalues in , and for a bounded the expected error of the fit, truncated at the bound, is close to the best approximation error in , plus a term of order . For the Legendre basis in one dimension, so the theorem asks for of order uniform samples; the to rule is a heuristic that works for smooth outputs, as the example shows, but has no such guarantee.
Proof: The normal equations give the unique least-squares fit, the fit is exact on the span, and the hat matrix gives the leave-one-out residualsfull
We assume exact arithmetic. Let be the design matrix of line L4, with rows , and let . Write and .
Lemma 1 (Cholesky succeeds exactly when has full column rank). is symmetric positive semidefinite, and it is positive definite if and only if the columns of are linearly independent.
Proof. , and , with equality if and only if . So is positive definite if and only if only for . The Cholesky algorithm on a symmetric matrix finds a positive pivot at every step if and only if the matrix is positive definite, so line L5 succeeds exactly in this case.
Lemma 2 (the normal equations give the unique minimizer). If has full column rank, the solution of satisfies for every , so is the unique minimizer of .
Proof. , so the residual is orthogonal to every column of . Then , and the cross term vanishes. The last term is positive for by full rank.
Lemma 3 (exact on the span). If and has full column rank, then line L5 returns .
Proof. Then , so , which is the smallest possible value, and Lemma 2 says the minimizer is unique.
Lemma 4 (the leverages). Let be the Cholesky factor, , and . Then , , and .
Proof. , so . The hat matrix satisfies and , so it is an orthogonal projection, and . Finally .
Lemma 5 (leave-one-out residuals). Suppose with row removed, , still has full column rank, and let be its least-squares fit to with entry removed. Then and
Proof. is positive definite by Lemma 1. By the matrix determinant lemma, , so . The Sherman-Morrison formula gives
Also . Multiply: . Apply on the left and use and :
Then .
Lemma 6 (unbiased Gram matrix). If the points are drawn independently from the input law, then .
Proof. , and each term has expectation by orthonormality.
Theorem. REGRESSION-PCE stops after model runs. If has full column rank, it returns the unique least-squares coefficients; they equal the true coefficients when lies in the span of the basis. If also every has full column rank, the value of line L6 equals divided by the sample variance of , the leave-one-out mean squared error of separate refits.
Proof. Termination: lines L2 to L4 are loops of length and , line L5 is a Cholesky factorization of a matrix and two triangular solves, and line L6 is triangular solves; all are finite. The coefficients are Lemmas 1 to 3, and the leave-one-out value is Lemmas 4 and 5.
The theorem makes no claim about the accuracy of the fit on new inputs for a outside the span. That claim needs the probabilistic stability theorem of Cohen, Davenport and Leviatan, which holds when is large compared with , and which is quoted on the page but not proved here.
Complexity
In the real RAM model, line L3 costs . Line L4 costs . The Gram matrix costs , the Cholesky factor , and the leverages by triangular solves. Since , the total is time, and the design matrix takes space. For , and the reference code takes well under a second in Python; for an expensive model, dominates.
Properties
- Non-intrusive and design free. Any point set works, including runs that exist already.
- Exact for polynomials (theorem). If is in the span of the basis and has full column rank, the fit is exact.
- Randomized. With random points, the coefficients are random; repeated fits with new seeds show the spread, as in the example.
- Free error estimate. The leave-one-out error comes from one fit, by the hat matrix identity.
- Needs more runs than terms. is necessary; close to gives a badly conditioned fit.
- Curse of dimensionality. grows like for fixed , and grows with it.
Variants and improvements
- Weighted least squares. Draw the points from a sampling law adapted to the basis, such as the Chebyshev law for Legendre polynomials, and weight the rows by the density ratio. With the sampling law proportional to , the quantity of the stability theorem becomes , so the run count it needs falls to order .
- Designed points. Latin hypercube, quasi-Monte Carlo points or D-optimal subsets of a candidate set give better conditioned fits than plain random points for the same .
- Sparse fits. When , or when most coefficients are small, use sparse polynomial chaos by l1 minimization, least angle regression or orthogonal matching pursuit, and choose the basis by the leave-one-out error.
- Regularized fits. Ridge regression adds a penalty and keeps the solve stable when is close to .
- Gradient-enhanced regression. If the model also returns derivatives, add rows for ; each run then gives equations.
When to use it
Use regression when the model is a black box, when the runs come from a given design or a database, or when a tensor quadrature grid would be too large. It is the usual choice for moderate dimension (up to about ten inputs) with a smooth output. Use spectral projection when the dimension is small and you can choose the points freely, sparse polynomial chaos when runs are fewer than coefficients, and Monte Carlo integration when the output is not smooth.
Pitfalls
- Too few runs. At the Gram matrix is nearly singular, and the coefficients are dominated by noise in the fit, as the first row of the example shows.
- Unbounded bases. With Gaussian inputs, Hermite polynomials grow fast, and a few points in the tails get large leverage. Check that the leverages are not close to 1, and consider weighted sampling.
- Normal equations square the condition number. The condition number of is the square of that of . For high degrees, use QR on .
- Trusting the training residual. The residual of the fit always falls as grows; the leave-one-out error does not, and it is the one to use to pick .
- Leverage equal to 1. If , removing run makes rank deficient and the leave-one-out formula divides by zero. Such a run is the only one that fixes some coefficient.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/regression-polynomial-chaos/. The authors are listed in prov/MZG7P5.jsonl.
"""Regression-based (least-squares) polynomial chaos with the leave-one-out error.
The input xi = (xi_1..xi_d) has independent components, each "uniform" on
[-1, 1] (orthonormal Legendre basis sqrt(2n+1) P_n) or "normal" (standard
normal, orthonormal Hermite basis He_n / sqrt(n!)). The code draws N random
inputs from the input law, runs the model, and solves the normal equations
(A^T A) c = A^T y by Cholesky, with A[i][a] = Psi_a(x_i). The leave-one-out
error uses the identity e_(-i) = e_i / (1 - h_i), where h_i is the diagonal
of the hat matrix A (A^T A)^(-1) A^T.
"""
import itertools
import math
import random
from typing import Callable
from scimat import cholesky, cholesky_solve
Model = Callable[[list[float]], float]
def recurrence_offdiag(family: str, k: int) -> float:
"""b_k in x psi_(k-1) = b_k psi_k + b_(k-1) psi_(k-2) for the orthonormal family."""
if family == "uniform":
return k / math.sqrt((2 * k - 1) * (2 * k + 1))
if family == "normal":
return math.sqrt(k)
raise ValueError("family must be 'uniform' or 'normal'")
def basis_1d(family: str, x: float, p: int) -> list[float]:
"""psi_0(x)..psi_p(x), orthonormal for the law of the family."""
vals = [1.0]
if p >= 1:
vals.append(x / recurrence_offdiag(family, 1))
for k in range(2, p + 1):
bk, bk1 = recurrence_offdiag(family, k), recurrence_offdiag(family, k - 1)
vals.append((x * vals[k - 1] - bk1 * vals[k - 2]) / bk)
return vals
def total_degree_set(d: int, p: int) -> list[tuple[int, ...]]:
"""All a in N^d with |a| <= p, sorted by total degree; the zero index is first."""
out = [a for a in itertools.product(range(p + 1), repeat=d) if sum(a) <= p]
out.sort(key=lambda a: (sum(a), [-v for v in a]))
return out
def sample(families: list[str], rng: random.Random) -> list[float]:
"""One draw of the input vector from its law."""
return [rng.uniform(-1.0, 1.0) if f == "uniform" else rng.gauss(0.0, 1.0) for f in families]
def design_row(index: list[tuple[int, ...]], families: list[str], x: list[float]) -> list[float]:
"""The row Psi_a(x), a in index."""
p = max(sum(a) for a in index)
tables = [basis_1d(families[k], x[k], p) for k in range(len(x))]
return [math.prod(tables[k][a[k]] for k in range(len(x))) for a in index]
def gram(rows: list[list[float]]) -> list[list[float]]:
"""A^T A for the matrix with the given rows, using symmetry."""
n = len(rows[0])
g = [[0.0] * n for _ in range(n)]
for r in rows:
for i in range(n):
ri = r[i]
gi = g[i]
for j in range(i, n):
gi[j] += ri * r[j]
for i in range(n):
for j in range(i):
g[i][j] = g[j][i]
return g
def forward(low: list[list[float]], b: list[float]) -> list[float]:
"""Solve L z = b for lower triangular L."""
z = [0.0] * len(b)
for i in range(len(b)):
z[i] = (b[i] - sum(low[i][k] * z[k] for k in range(i))) / low[i][i]
return z
def least_squares(rows: list[list[float]], y: list[float]) -> tuple[list[float], list[list[float]]]:
"""Coefficients of min ||A c - y|| by the normal equations; also returns the Cholesky factor of A^T A."""
n = len(rows[0])
rhs = [sum(r[j] * yi for r, yi in zip(rows, y)) for j in range(n)]
low = cholesky(gram(rows))
return cholesky_solve(low, rhs), low
def loo_error(rows: list[list[float]], y: list[float], coeffs: list[float], low: list[list[float]]) -> float:
"""Relative leave-one-out error mean((e_i / (1 - h_i))^2) / var(y)."""
n = len(y)
total = 0.0
for r, yi in zip(rows, y):
e = yi - sum(a * c for a, c in zip(r, coeffs))
z = forward(low, r)
h = sum(v * v for v in z)
total += (e / (1.0 - h)) ** 2
mean = sum(y) / n
var = sum((v - mean) ** 2 for v in y) / (n - 1)
return (total / n) / var
def regression_pce(q: Model, families: list[str], p: int, n: int, rng: random.Random):
"""Least-squares PCE of total degree p from n random runs; returns (index, coeffs, loo)."""
index = total_degree_set(len(families), p) # @line L1
if n < len(index):
raise ValueError("need at least as many runs as coefficients")
xs = [sample(families, rng) for _ in range(n)] # @line L2
y = [q(x) for x in xs] # @line L3
rows = [design_row(index, families, x) for x in xs] # @line L4
coeffs, low = least_squares(rows, y) # @line L5
loo = loo_error(rows, y, coeffs, low) # @line L6
return index, coeffs, loo # @line L7
def mean_variance(coeffs: list[float]) -> tuple[float, float]:
"""Mean c_0 and variance sum_{a != 0} c_a^2 of an orthonormal expansion."""
return coeffs[0], sum(c * c for c in coeffs[1:])
def sobol_from_coefficients(index: list[tuple[int, ...]], coeffs: list[float]) -> tuple[list[float], list[float]]:
"""First order and total Sobol indices of an orthonormal expansion (Sudret 2008)."""
d = len(index[0])
_, var = mean_variance(coeffs)
first = [0.0] * d
total = [0.0] * d
for a, c in zip(index, coeffs):
active = [k for k in range(d) if a[k] > 0]
if len(active) == 1:
first[active[0]] += c * c
for k in active:
total[k] += c * c
return [s / var for s in first], [s / var for s in total]
def ishigami(x: list[float], a: float = 7.0, b: float = 0.1) -> float:
"""The Ishigami function with inputs xi_k uniform on [-1, 1], mapped to pi xi_k."""
x1, x2, x3 = (math.pi * v for v in x)
return math.sin(x1) + a * math.sin(x2) ** 2 + b * x3**4 * math.sin(x1)
scimat.py 227 lines
# SPDX-License-Identifier: MIT
# Shared helper of the scientific-computing pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra and error norms for the scientific-computing pages.
A matrix is a list of rows and a vector is a list. Entries may be int,
float or fractions.Fraction. The routines that do not take a square root
(solve, inv, det and the arithmetic) keep Fraction entries exact.
cholesky, cholesky_solve and norm2 take square roots and return floats.
API (fixed; other pages copy this file byte for byte):
zeros(m, n=None) m by n zero matrix (n = m if not given)
eye(n) n by n identity
add(A, B), sub(A, B) entrywise sum and difference (vectors or matrices)
scale(c, A) c times A (vector or matrix)
matmul(A, B) matrix product
matvec(A, x) matrix times vector
transpose(A) transpose
dot(x, y) inner product of two vectors
norm2(x) Euclidean norm of a vector, as a float
outer(x, y) outer product x y^T
solve(A, b) Gaussian elimination with partial pivoting;
b is a vector or a matrix of right sides
inv(A) inverse of A
det(A) determinant of A
cholesky(A) lower triangular L with A = L L^T (floats)
cholesky_solve(L, b) solve L L^T x = b for a vector b
err_l1(e, dx=1) sum |e_j| dx
err_l2(e, dx=1) sqrt(sum e_j^2 dx), as a float
err_linf(e, dx=1) max |e_j| (dx is not used)
observed_order(errors) [log2(E_i / E_(i+1)) for successive errors]
"""
import math
def zeros(m, n=None):
"""Return an m by n matrix of zeros (n = m if n is None)."""
if n is None:
n = m
return [[0] * n for _ in range(m)]
def eye(n):
"""Return the n by n identity matrix."""
out = zeros(n, n)
for i in range(n):
out[i][i] = 1
return out
def _is_matrix(a):
return len(a) > 0 and isinstance(a[0], list)
def add(a, b):
"""Return a + b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x + y for x, y in zip(a, b)]
def sub(a, b):
"""Return a - b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x - y for x, y in zip(a, b)]
def scale(c, a):
"""Return c times a, for a vector or a matrix a."""
if _is_matrix(a):
return [[c * x for x in row] for row in a]
return [c * x for x in a]
def transpose(a):
"""Return the transpose of the matrix a."""
return [list(col) for col in zip(*a)]
def matmul(a, b):
"""Return the matrix product a b."""
bt = transpose(b)
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a, x):
"""Return the product of the matrix a and the vector x."""
return [sum(aij * xj for aij, xj in zip(row, x)) for row in a]
def dot(x, y):
"""Return the inner product of the vectors x and y."""
return sum(a * b for a, b in zip(x, y))
def norm2(x):
"""Return the Euclidean norm of the vector x, as a float."""
return math.sqrt(float(dot(x, x)))
def outer(x, y):
"""Return the outer product x y^T as a matrix."""
return [[a * b for b in y] for a in x]
def _eliminate(a, rhs):
"""Reduce a to upper triangular form with partial pivoting.
a is a copy of the square matrix, rhs a list of right side rows (one
row per row of a) that receives the same row operations. Return the
number of row swaps. Raise ValueError if a pivot is zero.
"""
n = len(a)
swaps = 0
for k in range(n):
p = max(range(k, n), key=lambda i: abs(a[i][k]))
if a[p][k] == 0:
raise ValueError("matrix is singular")
if p != k:
a[k], a[p] = a[p], a[k]
rhs[k], rhs[p] = rhs[p], rhs[k]
swaps += 1
for i in range(k + 1, n):
f = a[i][k] / a[k][k]
if f == 0:
continue
for j in range(k, n):
a[i][j] -= f * a[k][j]
for j in range(len(rhs[i])):
rhs[i][j] -= f * rhs[k][j]
return swaps
def solve(a, b):
"""Solve a x = b by Gaussian elimination with partial pivoting.
b is a vector (the result is a vector) or a matrix with one column per
right side (the result is a matrix). Fraction entries stay exact.
Raise ValueError if a is singular.
"""
n = len(a)
work = [list(row) for row in a]
vector = not _is_matrix(b)
rhs = [[v] for v in b] if vector else [list(row) for row in b]
_eliminate(work, rhs)
m = len(rhs[0]) if n else 0
x = [[0] * m for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(m):
s = rhs[i][j]
for k in range(i + 1, n):
s -= work[i][k] * x[k][j]
x[i][j] = s / work[i][i]
if vector:
return [row[0] for row in x]
return x
def inv(a):
"""Return the inverse of the square matrix a."""
return solve(a, eye(len(a)))
def det(a):
"""Return the determinant of the square matrix a (0 if singular)."""
work = [list(row) for row in a]
rhs = [[] for _ in a]
try:
swaps = _eliminate(work, rhs)
except ValueError:
return 0
d = -1 if swaps % 2 else 1
for i in range(len(a)):
d *= work[i][i]
return d
def cholesky(a):
"""Return the lower triangular L with a = L L^T, in floats.
Raise ValueError if a is not symmetric positive definite.
"""
n = len(a)
low = [[0.0] * n for _ in range(n)]
for j in range(n):
s = float(a[j][j]) - sum(low[j][k] ** 2 for k in range(j))
if s <= 0.0:
raise ValueError("matrix is not positive definite")
low[j][j] = math.sqrt(s)
for i in range(j + 1, n):
t = float(a[i][j]) - sum(low[i][k] * low[j][k] for k in range(j))
low[i][j] = t / low[j][j]
return low
def cholesky_solve(low, b):
"""Solve L L^T x = b, with L from cholesky, for a vector b."""
n = len(low)
y = [0.0] * n
for i in range(n):
y[i] = (float(b[i]) - sum(low[i][k] * y[k] for k in range(i))) / low[i][i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
x[i] = (y[i] - sum(low[k][i] * x[k] for k in range(i + 1, n))) / low[i][i]
return x
def err_l1(e, dx=1):
"""Return the discrete L1 norm sum |e_j| dx."""
return sum(abs(v) for v in e) * dx
def err_l2(e, dx=1):
"""Return the discrete L2 norm sqrt(sum e_j^2 dx), as a float."""
return math.sqrt(float(sum(v * v for v in e) * dx))
def err_linf(e, dx=1):
"""Return the max norm max |e_j|. dx is accepted for a uniform call and not used."""
return max(abs(v) for v in e)
def observed_order(errors):
"""Return [log2(E_i / E_(i+1))] for a list of errors on meshes h, h/2, h/4, ..."""
return [math.log2(float(errors[i]) / float(errors[i + 1])) for i in range(len(errors) - 1)]
test_regression_polynomial_chaos.py 108 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/regression-polynomial-chaos/. The authors are listed in prov/MZG7P5.jsonl.
import math
import random
import pytest
from regression_polynomial_chaos import (
cholesky,
design_row,
forward,
gram,
ishigami,
least_squares,
loo_error,
mean_variance,
regression_pce,
sample,
sobol_from_coefficients,
total_degree_set,
)
def small_problem(seed):
rng = random.Random(seed)
fams = ["uniform", "normal"]
index = total_degree_set(2, 2)
xs = [sample(fams, rng) for _ in range(15)]
rows = [design_row(index, fams, x) for x in xs]
y = [math.sin(x[0]) + 0.3 * x[1] ** 3 + 0.1 * rng.gauss(0, 1) for x in xs]
return rows, y
def test_polynomial_in_the_span_is_recovered_exactly():
rng = random.Random(5)
fams = ["uniform", "normal"]
index = total_degree_set(2, 3)
true = [rng.uniform(-1, 1) for _ in index]
def q(x):
return sum(a * b for a, b in zip(design_row(index, fams, x), true))
got_index, c, loo = regression_pce(q, fams, 3, 2 * len(index), random.Random(9))
assert got_index == index
assert max(abs(a - b) for a, b in zip(c, true)) < 1e-9
assert loo < 1e-18
def test_loo_identity_matches_brute_force_refits():
for seed in range(3):
rows, y = small_problem(seed)
c, low = least_squares(rows, y)
fast = loo_error(rows, y, c, low)
total = 0.0
for i in range(len(y)):
ci, _ = least_squares(rows[:i] + rows[i + 1 :], y[:i] + y[i + 1 :])
total += (y[i] - sum(a * b for a, b in zip(rows[i], ci))) ** 2
mean = sum(y) / len(y)
var = sum((v - mean) ** 2 for v in y) / (len(y) - 1)
assert abs(fast - total / len(y) / var) < 1e-9 * max(1.0, fast)
def test_hat_diagonal_sums_to_the_number_of_terms():
rows, _ = small_problem(4)
low = cholesky(gram(rows))
h = [sum(v * v for v in forward(low, r)) for r in rows]
assert abs(sum(h) - len(rows[0])) < 1e-10
assert all(0.0 <= v <= 1.0 + 1e-12 for v in h)
def test_residual_is_orthogonal_to_every_basis_column():
rows, y = small_problem(7)
c, _ = least_squares(rows, y)
res = [yi - sum(a * b for a, b in zip(r, c)) for r, yi in zip(rows, y)]
for j in range(len(rows[0])):
assert abs(sum(r[j] * e for r, e in zip(rows, res))) < 1e-10
def test_empirical_gram_matrix_tends_to_identity():
rng = random.Random(2)
index = total_degree_set(1, 3)
rows = [design_row(index, ["uniform"], sample(["uniform"], rng)) for _ in range(4000)]
g = gram(rows)
n = len(rows)
assert max(abs(g[i][j] / n - (1.0 if i == j else 0.0)) for i in range(4) for j in range(4)) < 0.15
def test_exponential_of_gaussian():
_, c, loo = regression_pce(lambda x: math.exp(x[0]), ["normal"], 6, 200, random.Random(1))
exact = [math.exp(0.5) / math.sqrt(math.factorial(n)) for n in range(7)]
assert max(abs(a - b) for a, b in zip(c, exact)) < 0.05
assert loo < 1e-3
def test_ishigami_sobol_indices():
index, c, loo = regression_pce(ishigami, ["uniform"] * 3, 6, 252, random.Random(0))
mean, _ = mean_variance(c)
s, st = sobol_from_coefficients(index, c)
assert abs(mean - 3.5) < 0.1
assert abs(s[0] - 0.3139) < 0.02
assert abs(s[1] - 0.4424) < 0.04
assert abs(st[2] - 0.2437) < 0.03
assert loo < 0.1
def test_too_few_runs_is_rejected():
with pytest.raises(ValueError):
regression_pce(ishigami, ["uniform"] * 3, 2, 9, random.Random(0))
History
The method of least squares goes back to Legendre in 1805 and to Gauss. Regression fits of polynomial chaos coefficients to random model runs came into use in the early 2000s as a non-intrusive alternative to the stochastic Galerkin method and to quadrature. Blatman and Sudret made the leave-one-out error from the hat matrix the standard check, and used it in 2011 to build sparse expansions by least angle regression. Cohen, Davenport and Leviatan gave in 2013 the first sharp theorem on how many random runs a stable least-squares fit needs, which started the work on optimal weighted sampling.
References
- Albert Cohen, Mark A. Davenport and Dany Leviatan, On the stability and accuracy of least squares approximations, Foundations of Computational Mathematics 13(5), 2013, 819-834, the stability condition on the number of random samples, K(P) at most a constant times N / log N, for the empirical Gram matrix to be close to the identity
- Geraud Blatman and Bruno Sudret, Adaptive sparse polynomial chaos expansion based on least angle regression, Journal of Computational Physics 230(6), 2011, 2345-2367, the leave-one-out error of a least-squares chaos expansion computed from the hat matrix diagonal
- Bruno Sudret, Global sensitivity analysis using polynomial chaos expansions, Reliability Engineering and System Safety 93(7), 2008, 964-979, the Sobol indices as sums of squared chaos coefficients, with the regression estimate of the coefficients
- Olivier P. Le Maitre and Omar M. Knio, Spectral Methods for Uncertainty Quantification, Springer, 2010, Chapter 3 (non-intrusive methods)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag MZG7P5 Edit this page History Report an error Markdown