Algorithmresearch
Kernel-based system identification
Also called regularized FIR identification, stable spline kernel method.
Estimates a long impulse response by regularized least squares with a kernel, such as the TC kernel, that encodes exponential decay.
- Solves
- System identification
- Time
- O(N d^2 + G d^3) worst
- Space
- O(N d + d^2) extra
- Where
- G = the number of grid points; N = the number of samples; d = the FIR length
- Model
- Real RAM
- Properties
- deterministicexactnot iterativeoffline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Gianluigi Pillonetto, Giuseppe De Nicolao, 2010
Kernel-based identification estimates the impulse response of a linear system from input-output data. It fits a long FIR model, with much larger than the true order, by regularized least squares. The regularization matrix comes from a kernel that encodes what we know about asymptotically stable systems: the coefficients decay exponentially and neighbouring coefficients are correlated. The kernel has two or three hyperparameters, and the method chooses them by maximizing the marginal likelihood of the data. This differs from least squares ARX identification and from a prediction error method, which fit a model with a fixed small order and need a choice of that order. Here the model is long and the kernel controls its complexity. The estimate is also the posterior mean of a Gaussian process model of the impulse response.
In plain words
A plain least squares fit of 50 impulse response coefficients from 100 samples is very noisy: each coefficient has little data, and the tail of the estimate wanders around zero. We know more than the data say. The true coefficients get smaller as the lag grows, and they change smoothly from one lag to the next. The kernel writes this knowledge as a prior covariance: large variance for the first lags, smaller variance for later lags, and strong correlation between neighbours. Regularized least squares then pulls the estimate toward such shapes. How fast the prior decays and how large it is are not known in advance, so the method tries values on a grid and keeps the one for which the observed data are most probable.
The problem
Input. Scalar samples and , the FIR length , a kernel family with a finite grid of hyperparameters , and optionally the noise variance .
Output. An estimate of the impulse response, the chosen hyperparameters , and the noise variance used.
Model. with for , and white Gaussian noise with variance . In matrix form , where is the regressor with .
Kernels. The TC (tuned/correlated) kernel is with and . It is also the first order stable spline kernel. The DC (diagonal/correlated) kernel is with ; with it is the TC kernel. In both, sets the decay rate and the scale.
The algorithm
KERNEL-FIR(u, y, d, grid, σ²)- 1
Φ ← the N × d regressor, Φ[k][t] = u_(k-t) - 2
R ← Φ^T Φ; r ← Φ^T y; yy ← y^T y - 3
if σ² is not given: σ² ← the residual sum of squares of the least squares FIR fit / (N - d) - 4
for each η in the grid: - 5
K ← K(η); L ← the Cholesky factor of K; M ← σ² I + L^T R L - 6
cost ← (yy - (L^T r)^T M⁻¹ L^T r) / σ² + (N - d) log σ² + log det M - 7
if cost < the best cost so far: keep η and the cost - 8
ĝ ← L M⁻¹ L^T r for the kept η - 9
return (ĝ, η, σ²)
The estimate is the minimizer of the regularized criterion
with . If has the prior , then has the distribution , and the cost of L6 is , which is minus two times the log marginal likelihood, up to a constant. Choosing this way is empirical Bayes. The code never forms the matrix . With , the push-through identity, the Woodbury identity and Sylvester's determinant identity give the forms of L5, L6 and L8. They also avoid , which is badly conditioned when is small. L3 is the unbiased estimate of the noise variance from the plain least squares fit.
Example
Take the impulse response
a lightly damped mode plus a fast real pole, so . The input is Gaussian white noise with unit variance, the noise has , and the random seed is 1. Measure the quality by the fit in percent.
The TC grid is and , 24 points. The DC grid uses the same , and , 48 points.
With samples, L3 gives (the true value is ). The TC search keeps and the DC search keeps . The fits are:
| estimate | fit, | fit, |
|---|---|---|
| least squares FIR | 59.0 | 83.3 |
| TC kernel | 89.3 | 89.5 |
| DC kernel | 88.5 | 89.5 |
With 100 samples and 50 unknowns, plain least squares is poor, and the kernel estimate is much better. With 200 samples the gap is smaller but still clear. Over the seeds 1 to 5 at , the TC fit was between 84.6 and 89.5 and the least squares fit between 58.8 and 76.9 (measurement).
Correctness
Claim. KERNEL-FIR returns the first grid point that maximizes the Gaussian marginal likelihood of , and the posterior mean of under the kernel at that point, which is also the unique minimizer of the regularized criterion.
Key invariant. For every grid point, with and , the quantities equal the ones: , and .
The TC and DC kernels are positive definite, so exists and is positive definite. The scan keeps a point only when its cost is strictly smaller. The full proof is below.
Proof: The kernel-based FIR estimate is the posterior mean at the grid point of largest marginal likelihoodfull
We work in exact real arithmetic, as in the real RAM. The data are and , the FIR length is , and is the regressor of L1 with ( for ). Write and (L2).
The Bayesian model. with positive definite, and with independent of and . Then with .
Lemma 1 (the TC kernel is positive definite). For and , the matrix , , is positive definite.
Proof. Let have entries 1 at the indices and 0 elsewhere. For ,
so . All weights are positive. If , then for , so , then , and so on: .
The DC kernel with is times times the correlation matrix of a first order autoregressive process times the same diagonal, so it is also positive definite. With it equals the TC kernel, since .
Lemma 2 (posterior mean and regularized least squares). The posterior mean of given is
and it is the unique minimizer of .
Proof. is jointly Gaussian with and , so . The push-through identity gives . The criterion is a quadratic with Hessian , which is positive definite, and its gradient vanishes at .
Lemma 3 (small forms). Let be the Cholesky factorization and . Then
Proof. Put , so and . The push-through identity gives , so . The Woodbury identity gives , which gives the second formula. Sylvester's determinant identity gives .
Lemma 4 (the cost is the marginal likelihood). The cost of L6 is , where is the Gaussian density of under the kernel with hyperparameters .
Proof. . Take . By Lemma 3, the code computes exactly these two terms from , and .
Lemma 5 (the noise variance of L3). If is nonsingular and the data follow the FIR model with taps, then with has expectation , given .
Proof. The residual is with , an orthogonal projection of rank . So . The code computes .
Theorem. KERNEL-FIR returns (or the given ), the first grid point that minimizes over the grid, and the posterior mean of under the kernel , which is also the regularized least squares estimate of Lemma 2.
Proof. L4 to L7 scan the grid and keep a point only when its cost is strictly smaller, so the kept point is the first minimizer of the cost, which by Lemma 4 is the first maximizer of the marginal likelihood. L8 computes for this kernel, which by Lemmas 2 and 3 is the posterior mean.
Remark. The theorem is about the optimization over the grid only. The marginal likelihood is not convex in the hyperparameters, and a continuous search can stop at a local minimum. Whether the empirical Bayes choice gives a small error is a statistical question; the page reports measurements and cites the theory.
Complexity
In the real RAM. L1 is and L2 is . Each grid point costs a Cholesky factorization, two products of matrices, a linear solve and a second Cholesky factorization for , all . With grid points the total is . The extra space is for and for the matrices; a streaming version forms and without storing and needs .
A continuous search over with a quasi-Newton method costs per evaluation of the cost, the same as one grid point.
Properties
- Posterior mean (theorem). Under the Gaussian prior and Gaussian noise, is the posterior mean, and the cost is minus two times the log marginal likelihood up to a constant.
- Bias and variance (theorem). For a fixed kernel, is biased toward zero, but its variance is smaller than that of least squares. The regularization trades bias for variance; see bias-variance tradeoff.
- No order selection. The FIR length only needs to be long enough for the response to decay. The kernel, not , sets the effective number of parameters.
- Decaying estimates. With the TC or DC kernel the prior variance of decays as , so the estimate decays as well. This is a property of the prior, not a guarantee about every data set.
- Better accuracy on short records (measurement). In the example, the TC estimate had a fit near 89 percent where least squares had 59 percent. Chen, Ohlsson and Ljung (2012) report similar gains in Monte Carlo studies, also against prediction error methods with the order chosen by a criterion.
- Nonconvex hyperparameter search. The marginal likelihood is not convex in . A grid is safe for two or three hyperparameters, but a local search can stop at a local optimum.
Variants and improvements
- Stable spline kernels. Pillonetto and De Nicolao (2010) use the second order stable spline kernel, which makes the estimate smoother. The TC kernel is the first order case.
- Other kernels. Sums and products of kernels, kernels for resonant systems, and kernels learned from data. The survey of Pillonetto et al. (2014) describes many.
- Multiple inputs and outputs. One impulse response per input-output pair, each with its own kernel, or a shared kernel.
- Continuous search. Optimize the marginal likelihood over with gradients. A QR factorization of the stacked regressor gives a more accurate cost than the normal equations.
- Other tuning criteria. Cross-validation or Stein's unbiased risk estimate in place of the marginal likelihood.
- From FIR to state space. Fit a low order state-space model to , for example by the Ho-Kalman algorithm or by model reduction, when a compact model is needed.
When to use it
Use kernel-based identification for a linear, asymptotically stable system when the data record is short, the noise is large, or the order is unknown. It gives a good impulse response and frequency response without a choice of order and without local minima in the model parameters. Use it as a reference model or as a starting point for a low order fit. For a system with a very slow mode, must be large, and the cost grows as . For an unstable system, the kernels above are wrong.
Pitfalls
- too short. If is not small, the truncated tail acts as extra noise and biases the result. Check that the estimate has decayed at lag .
- in the code. Forming directly fails when is near the machine epsilon. Use the Cholesky factor of as in L5.
- Initial conditions. The code sets for . If the system was not at rest before the record, drop the first outputs from the fit.
- A grid that is too coarse. If the best point is on the edge of the grid, extend the grid.
- Unknown noise variance. L3 needs and a nonsingular . With close to the estimate of is poor; estimate it from a low order model or include it in the marginal likelihood.
- Colored noise. The model assumes white noise. Colored noise gives a wrong marginal likelihood and a wrong choice of .
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
# Shared helper of the control pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra and polynomial routines for the control pages.
Conventions:
- A matrix is a list of rows. Entries are int, float, Fraction or complex.
- A vector is a flat list of scalars. matvec, dot, solve (with a vector
right side), vec and unvec use flat lists.
- A polynomial is a list of coefficients, highest power first, so
[1, 3, 2] is s^2 + 3 s + 2.
- Routines that divide (solve, inv, det, charpoly) compute in Fraction when
every entry is an int or a Fraction, so the result is exact. With float or
complex entries they compute in floating point.
- transpose does not conjugate complex entries.
Floating point tolerances:
- expm: scaling and squaring with a Taylor series; the scaled matrix has
infinity norm at most 1/2 and the series stops when a term is below
2^-60 times the sum. For matrices that are not far from normal the relative
error is near 1e-14.
- polyroots: Durand-Kerner iteration, then a Newton polish. Simple roots of a
well conditioned polynomial come out with a relative error near 1e-12 (the
tests ask for 1e-9). A root of multiplicity k is ill conditioned: its error
grows like 1e-16^(1/k), about 1e-8 for a double root and 1e-3 for a
fourfold root. For real coefficients the output is closed under
conjugation.
- is_pos_def with float entries: the matrix must be symmetric within
1e-12 times its largest entry, and the Cholesky pivots of A - margin I must
be positive.
This file holds no algorithm of a control page.
"""
import cmath
import math
from fractions import Fraction
__all__ = [
"zeros", "eye", "add", "sub", "scale", "mul", "transpose", "matvec",
"dot", "norm2", "block", "kron", "vec", "unvec", "solve", "inv", "det",
"trace", "charpoly", "polyval", "polyadd", "polymul", "polyder",
"polyroots", "expm", "mat_power", "is_symmetric", "is_pos_def",
]
def _is_exact(v):
return isinstance(v, (int, Fraction))
def _all_exact(*mats):
for m in mats:
for row in m:
if isinstance(row, list):
for v in row:
if not _is_exact(v):
return False
elif not _is_exact(row):
return False
return True
def _to_fraction(a):
return [[Fraction(v) for v in row] for row in a]
def _shape(a):
return len(a), (len(a[0]) if a else 0)
def zeros(n, m=None):
"""Return the n by m zero matrix (n by n if m is None), with int entries."""
if m is None:
m = n
return [[0] * m for _ in range(n)]
def eye(n):
"""Return the n by n identity matrix, with int entries."""
return [[1 if i == j else 0 for j in range(n)] for i in range(n)]
def add(a, b):
"""Return a + b."""
if _shape(a) != _shape(b):
raise ValueError("add: shapes differ")
return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
def sub(a, b):
"""Return a - b."""
if _shape(a) != _shape(b):
raise ValueError("sub: shapes differ")
return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
def scale(c, a):
"""Return the scalar c times the matrix a."""
return [[c * x for x in row] for row in a]
def mul(a, b):
"""Return the matrix product a b."""
n, k = _shape(a)
k2, m = _shape(b)
if k != k2:
raise ValueError("mul: inner dimensions differ")
bt = list(zip(*b)) if b else []
out = []
for row in a:
out_row = []
for col in bt:
s = 0
for x, y in zip(row, col):
s += x * y
out_row.append(s)
out.append(out_row)
return out
def transpose(a):
"""Return the transpose of a (no complex conjugation)."""
return [list(col) for col in zip(*a)]
def matvec(a, x):
"""Return the vector a x, for a flat list x."""
if a and len(a[0]) != len(x):
raise ValueError("matvec: dimensions differ")
out = []
for row in a:
s = 0
for v, w in zip(row, x):
s += v * w
out.append(s)
return out
def dot(x, y):
"""Return sum of x_i y_i (no complex conjugation)."""
if len(x) != len(y):
raise ValueError("dot: lengths differ")
s = 0
for v, w in zip(x, y):
s += v * w
return s
def _sym_eigvals(s):
"""Eigenvalues of a real symmetric float matrix by cyclic Jacobi."""
n = len(s)
a = [list(map(float, row)) for row in s]
for _ in range(100):
off = sum(a[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
diag = sum(a[i][i] ** 2 for i in range(n))
if off <= 1e-30 * max(diag, 1e-300):
break
for p in range(n - 1):
for q in range(p + 1, n):
if a[p][q] == 0.0:
continue
theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(t * t + 1.0)
sn = t * c
for k in range(n):
akp, akq = a[k][p], a[k][q]
a[k][p] = c * akp - sn * akq
a[k][q] = sn * akp + c * akq
for k in range(n):
apk, aqk = a[p][k], a[q][k]
a[p][k] = c * apk - sn * aqk
a[q][k] = sn * apk + c * aqk
return [a[i][i] for i in range(n)]
def norm2(x):
"""Return the 2-norm.
For a flat vector this is the Euclidean norm. For a matrix it is the
induced 2-norm (the largest singular value), computed from the
eigenvalues of M^T M by the Jacobi method, where M is a real matrix with
the same singular values. The result is a float.
"""
if not x:
return 0.0
if not isinstance(x[0], list):
return math.sqrt(sum(abs(complex(v)) ** 2 for v in x))
if any(isinstance(v, complex) for row in x for v in row):
re = [[complex(v).real for v in row] for row in x]
im = [[complex(v).imag for v in row] for row in x]
m = block([[re, scale(-1, im)], [im, re]])
else:
m = [[float(v) for v in row] for row in x]
g = mul(transpose(m), m)
lam = max(_sym_eigvals(g))
return math.sqrt(max(lam, 0.0))
def block(rows):
"""Build a matrix from a list of rows of blocks.
A block is a matrix, or the int 0 for a zero block whose size is taken
from the other blocks in its block row and block column.
"""
heights = []
for r in rows:
h = None
for b in r:
if isinstance(b, list):
h = len(b)
break
if h is None:
raise ValueError("block: a block row has no matrix block")
heights.append(h)
ncols = len(rows[0])
widths = []
for j in range(ncols):
w = None
for r in rows:
if isinstance(r[j], list):
w = len(r[j][0]) if r[j] else 0
break
if w is None:
raise ValueError("block: a block column has no matrix block")
widths.append(w)
out = []
for r, h in zip(rows, heights):
if len(r) != ncols:
raise ValueError("block: block rows have different lengths")
for i in range(h):
line = []
for b, w in zip(r, widths):
if isinstance(b, list):
if len(b) != h or (b and len(b[0]) != w):
raise ValueError("block: block sizes do not match")
line.extend(b[i])
elif b == 0:
line.extend([0] * w)
else:
raise ValueError("block: a scalar block must be 0")
out.append(line)
return out
def kron(a, b):
"""Return the Kronecker product of a and b."""
n, m = _shape(a)
p, q = _shape(b)
return [[a[i // p][j // q] * b[i % p][j % q] for j in range(m * q)] for i in range(n * p)]
def vec(a):
"""Stack the columns of a into one flat list."""
n, m = _shape(a)
return [a[i][j] for j in range(m) for i in range(n)]
def unvec(v, n, m=None):
"""Inverse of vec: return the n by m matrix whose stacked columns are v."""
if m is None:
m = len(v) // n
if n * m != len(v):
raise ValueError("unvec: length does not match the shape")
return [[v[j * n + i] for j in range(m)] for i in range(n)]
def solve(a, b):
"""Solve a x = b by Gaussian elimination with partial pivoting.
b is a flat vector or a matrix; the result has the same form. With int
and Fraction entries the result is exact (Fraction). Raises ValueError
if a is singular (an exactly zero pivot).
"""
n, m = _shape(a)
if n != m:
raise ValueError("solve: matrix is not square")
is_vec = not (b and isinstance(b[0], list))
rhs = [[v] for v in b] if is_vec else [list(row) for row in b]
if len(rhs) != n:
raise ValueError("solve: right side has the wrong length")
if _all_exact(a, rhs):
aa = _to_fraction(a)
rhs = _to_fraction(rhs)
else:
aa = [list(row) for row in a]
k = len(rhs[0]) if rhs else 0
for c in range(n):
p = max(range(c, n), key=lambda r: abs(aa[r][c]))
if aa[p][c] == 0:
raise ValueError("solve: matrix is singular")
if p != c:
aa[c], aa[p] = aa[p], aa[c]
rhs[c], rhs[p] = rhs[p], rhs[c]
piv = aa[c][c]
for r in range(c + 1, n):
f = aa[r][c] / piv
if f == 0:
continue
row_r, row_c = aa[r], aa[c]
for j in range(c, n):
row_r[j] -= f * row_c[j]
rr, rc = rhs[r], rhs[c]
for j in range(k):
rr[j] -= f * rc[j]
x = [[0] * k for _ in range(n)]
for c in range(n - 1, -1, -1):
for j in range(k):
s = rhs[c][j]
for t in range(c + 1, n):
s -= aa[c][t] * x[t][j]
x[c][j] = s / aa[c][c]
return [row[0] for row in x] if is_vec else x
def inv(a):
"""Return the inverse of a (exact with int and Fraction entries)."""
return solve(a, eye(len(a)))
def det(a):
"""Return the determinant of a by elimination with partial pivoting.
With int and Fraction entries the result is an exact Fraction.
"""
n, m = _shape(a)
if n != m:
raise ValueError("det: matrix is not square")
aa = _to_fraction(a) if _all_exact(a) else [list(row) for row in a]
d = Fraction(1) if _all_exact(a) else 1.0
for c in range(n):
p = max(range(c, n), key=lambda r: abs(aa[r][c]))
if aa[p][c] == 0:
return d * 0
if p != c:
aa[c], aa[p] = aa[p], aa[c]
d = -d
piv = aa[c][c]
d *= piv
for r in range(c + 1, n):
f = aa[r][c] / piv
if f == 0:
continue
for j in range(c, n):
aa[r][j] -= f * aa[c][j]
return d
def trace(a):
"""Return the sum of the diagonal entries of a."""
s = 0
for i in range(len(a)):
s += a[i][i]
return s
def charpoly(a):
"""Return [1, a_1, ..., a_n] with det(s I - A) = s^n + a_1 s^(n-1) + ... + a_n.
Uses the Faddeev-LeVerrier recursion M_k = A M_(k-1) + a_(k-1) I,
a_k = -trace(A M_k) / k. Exact with int and Fraction entries.
"""
n, m = _shape(a)
if n != m:
raise ValueError("charpoly: matrix is not square")
aa = _to_fraction(a) if _all_exact(a) else [list(row) for row in a]
coeffs = [1]
mk = zeros(n)
for k in range(1, n + 1):
mk = mul(aa, mk)
c = coeffs[-1]
for i in range(n):
mk[i][i] += c
am = mul(aa, mk)
coeffs.append(-trace(am) / k)
return coeffs
def polyval(p, x):
"""Evaluate the polynomial p at x by Horner's rule."""
s = 0
for c in p:
s = s * x + c
return s
def _strip(p):
i = 0
while i < len(p) - 1 and p[i] == 0:
i += 1
return list(p[i:]) if p else [0]
def polyadd(p, q):
"""Return p + q, with exactly zero leading coefficients removed."""
n = max(len(p), len(q))
pp = [0] * (n - len(p)) + list(p)
qq = [0] * (n - len(q)) + list(q)
return _strip([x + y for x, y in zip(pp, qq)])
def polymul(p, q):
"""Return the product p q."""
if not p or not q:
return [0]
out = [0] * (len(p) + len(q) - 1)
for i, x in enumerate(p):
for j, y in enumerate(q):
out[i + j] += x * y
return _strip(out)
def polyder(p):
"""Return the derivative of p."""
n = len(p) - 1
if n <= 0:
return [0]
return _strip([c * (n - i) for i, c in enumerate(p[:-1])])
def polyroots(p, tol=1e-15, maxiter=1000):
"""Return the complex roots of p, sorted by real part, then imaginary part.
Durand-Kerner (Weierstrass) iteration from points on a circle, stopped
when every relative correction is below tol, then a Newton polish of
each root. For real coefficients the roots are made exactly real or
exact conjugate pairs. See the module notes for the accuracy.
"""
c = [complex(v) for v in p]
while c and c[0] == 0:
c.pop(0)
if not c:
raise ValueError("polyroots: zero polynomial")
real_coeffs = all(v.imag == 0 for v in c)
origin = 0
while len(c) > 1 and c[-1] == 0:
c.pop()
origin += 1
n = len(c) - 1
a = [v / c[0] for v in c]
if n == 0:
z = []
elif n == 1:
z = [-a[1]]
else:
r = 2.0 * max(abs(a[k]) ** (1.0 / k) for k in range(1, n + 1))
if r == 0:
r = 1.0
z = [r * cmath.exp(1j * (2 * math.pi * k / n + 0.4)) for k in range(n)]
for _ in range(maxiter):
worst = 0.0
for i in range(n):
den = 1.0 + 0j
for j in range(n):
if j != i:
den *= z[i] - z[j]
if den == 0:
z[i] += 1e-8 * (1 + abs(z[i])) * cmath.exp(1j * (i + 1))
worst = 1.0
continue
d = polyval(a, z[i]) / den
z[i] -= d
worst = max(worst, abs(d) / (1.0 + abs(z[i])))
if worst < tol:
break
dp = polyder(a)
for i in range(n):
zi = z[i]
fz = abs(polyval(a, zi))
for _ in range(5):
der = polyval(dp, zi)
if der == 0 or fz == 0:
break
step = polyval(a, zi) / der
if abs(step) > 1e-6 * (1.0 + abs(zi)):
break
znew = zi - step
fnew = abs(polyval(a, znew))
if fnew >= fz:
break
zi, fz = znew, fnew
z[i] = zi
z = z + [0j] * origin
if real_coeffs:
thr = 1e-9
upper = [v for v in z if v.imag > thr * (1 + abs(v))]
lower = [v for v in z if v.imag < -thr * (1 + abs(v))]
reals = [complex(v.real, 0.0) for v in z if abs(v.imag) <= thr * (1 + abs(v))]
# A cluster of close roots can leave more roots above the real axis
# than below it (or the other way). The extra roots nearest to the
# axis are then taken as real, so the output is closed under
# conjugation.
if len(upper) < len(lower):
upper, lower = [v.conjugate() for v in lower], [v.conjugate() for v in upper]
upper.sort(key=lambda v: v.imag)
extra = len(upper) - len(lower)
reals += [complex(v.real, 0.0) for v in upper[:extra]]
upper = upper[extra:]
out = list(reals)
rest = list(lower)
for u in upper:
w = min(rest, key=lambda v: abs(v - u.conjugate()))
rest.remove(w)
re = (u.real + w.real) / 2
im = (u.imag - w.imag) / 2
out.append(complex(re, im))
out.append(complex(re, -im))
z = out
return sorted(z, key=lambda v: (v.real, v.imag))
def _norm_inf(a):
return max((sum(abs(v) for v in row) for row in a), default=0.0)
def expm(a):
"""Return e^A in floating point by scaling and squaring with a Taylor series.
A is scaled by 2^-s so that its infinity norm is at most 1/2, the Taylor
series of the scaled matrix is summed until a term is below 2^-60 of the
sum, and the result is squared s times. Entries of the result are float
(complex if A has complex entries).
"""
n, m = _shape(a)
if n != m:
raise ValueError("expm: matrix is not square")
cplx = any(isinstance(v, complex) for row in a for v in row)
conv = complex if cplx else float
x = [[conv(v) for v in row] for row in a]
nrm = _norm_inf(x)
s = 0
while nrm > 0.5:
nrm /= 2.0
s += 1
x = scale(conv(2.0 ** -s), x)
e = [[conv(1.0 if i == j else 0.0) for j in range(n)] for i in range(n)]
term = [row[:] for row in e]
for k in range(1, 60):
term = scale(1.0 / k, mul(term, x))
e = add(e, term)
tn = _norm_inf(term)
if tn == 0.0 or tn <= 2.0 ** -60 * _norm_inf(e):
break
for _ in range(s):
e = mul(e, e)
return e
def mat_power(a, k):
"""Return A^k for an int k by repeated squaring (A^0 = I; k < 0 uses inv)."""
n, m = _shape(a)
if n != m:
raise ValueError("mat_power: matrix is not square")
if k < 0:
a = inv(a)
k = -k
result = eye(n)
base = [list(row) for row in a]
while k:
if k & 1:
result = mul(result, base)
k >>= 1
if k:
base = mul(base, base)
return result
def is_symmetric(a, tol=0):
"""Return True if a is square and |a_ij - a_ji| <= tol for all i, j."""
n, m = _shape(a)
if n != m:
return False
return all(abs(a[i][j] - a[j][i]) <= tol for i in range(n) for j in range(i + 1, n))
def is_pos_def(a, margin=0):
"""Return True if a is symmetric and a - margin I is positive definite.
With int and Fraction entries (and an exact margin) the test is exact:
every leading principal minor of a - margin I must be positive
(Sylvester's criterion), computed in Fraction. With float entries the
matrix must be symmetric within 1e-12 times its largest entry, and the
Cholesky factorization of a - margin I must have positive pivots.
Complex entries are not accepted.
"""
n, m = _shape(a)
if n != m:
return False
if any(isinstance(v, complex) for row in a for v in row):
raise ValueError("is_pos_def: complex entries are not accepted")
if _all_exact(a) and _is_exact(margin):
b = [[Fraction(a[i][j]) - (Fraction(margin) if i == j else 0) for j in range(n)] for i in range(n)]
if not is_symmetric(b):
return False
return all(det([row[:k] for row in b[:k]]) > 0 for k in range(1, n + 1))
b = [[float(a[i][j]) - (float(margin) if i == j else 0.0) for j in range(n)] for i in range(n)]
big = max((abs(float(v)) for row in a for v in row), default=0.0)
if not is_symmetric(b, 1e-12 * max(big, 1e-300)):
return False
low = [[0.0] * n for _ in range(n)]
for j in range(n):
d = b[j][j] - sum(low[j][k] ** 2 for k in range(j))
if not d > 0.0:
return False
low[j][j] = math.sqrt(d)
for i in range(j + 1, n):
low[i][j] = (b[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
return True
def _self_test():
a = [[0, 1], [-2, -3]]
assert charpoly(a) == [1, 3, 2]
assert det(a) == 2
assert mul(inv(a), a) == eye(2)
assert solve(a, [1, 0]) == [Fraction(-3, 2), Fraction(1)]
r = polyroots([1, 3, 2])
assert abs(r[0] + 2) < 1e-12 and abs(r[1] + 1) < 1e-12
t = 0.7
e = expm([[0.0, t], [-t, 0.0]])
want = [[math.cos(t), math.sin(t)], [-math.sin(t), math.cos(t)]]
assert max(abs(e[i][j] - want[i][j]) for i in range(2) for j in range(2)) < 1e-14
assert is_pos_def([[Fraction(5, 4), Fraction(1, 4)], [Fraction(1, 4), Fraction(1, 4)]])
assert not is_pos_def([[1, 2], [2, 1]])
assert abs(norm2([[3.0, 0.0], [0.0, -4.0]]) - 4.0) < 1e-12
return True
if __name__ == "__main__":
_self_test()
kernel_based_identification.py 114 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kernel-based-identification/. The authors are listed in prov/BXFFBH.jsonl.
"""Kernel-based (regularized) FIR identification with the TC and DC kernels.
Input: an input sequence u_0, ..., u_(N-1) and an output sequence
y_0, ..., y_(N-1) (scalars) of a system y_k = sum_(t=1..d) g_t u_(k-t) + e_k
with u_t = 0 for t < 0, the FIR length d, a grid of kernel hyperparameters,
and the noise variance sigma2 (or None to estimate it from the residuals of
the least squares FIR fit).
Model: the impulse response g is a Gaussian vector with zero mean and
covariance K (the kernel matrix), and e is white Gaussian noise with variance
sigma2. Then y is Gaussian with covariance Z = Phi K Phi^T + sigma2 I, and
g_hat = (Phi^T Phi + sigma2 K^-1)^-1 Phi^T y = K Phi^T Z^-1 y
is the posterior mean (the regularized least squares estimate). The
hyperparameters minimize the negative log marginal likelihood
y^T Z^-1 y + log det Z (empirical Bayes) over the grid.
With K = L L^T (Cholesky) and M = sigma2 I + L^T Phi^T Phi L, every step
uses d by d matrices only:
g_hat = L M^-1 L^T Phi^T y,
y^T Z^-1 y = (y^T y - y^T Phi L M^-1 L^T Phi^T y) / sigma2,
log det Z = (N - d) log sigma2 + log det M.
"""
import math
from ctlmat import mul, solve, transpose
__all__ = ["regressor", "tc_kernel", "dc_kernel", "cholesky", "fit", "neg_log_marginal_likelihood", "kernel_fir"]
def regressor(u, d):
"""Return the N by d matrix Phi with Phi[k][t - 1] = u_(k-t) (zero for k - t < 0)."""
return [[float(u[k - t]) if k - t >= 0 else 0.0 for t in range(1, d + 1)] for k in range(len(u))]
def tc_kernel(d, c, lam):
"""Tuned/correlated kernel: K[i][j] = c lam^max(i, j), for i, j = 1, ..., d."""
return [[c * lam ** max(i, j) for j in range(1, d + 1)] for i in range(1, d + 1)]
def dc_kernel(d, c, lam, rho):
"""Diagonal/correlated kernel: K[i][j] = c lam^((i + j) / 2) rho^|i - j|."""
return [[c * lam ** ((i + j) / 2.0) * rho ** abs(i - j) for j in range(1, d + 1)] for i in range(1, d + 1)]
def cholesky(a):
"""Return the lower triangular L with a = L L^T; raise ValueError if a is not positive definite."""
n = len(a)
L = [[0.0] * n for _ in range(n)]
for j in range(n):
s = a[j][j] - sum(L[j][k] ** 2 for k in range(j))
if not s > 0.0:
raise ValueError("cholesky: the matrix is not positive definite")
L[j][j] = math.sqrt(s)
for i in range(j + 1, n):
L[i][j] = (a[i][j] - sum(L[i][k] * L[j][k] for k in range(j))) / L[j][j]
return L
def _parts(R, r, K, sigma2):
d = len(K)
L = cholesky(K)
M = mul(mul(transpose(L), R), L)
for i in range(d):
M[i][i] += sigma2
Ltr = [sum(L[t][i] * r[t] for t in range(d)) for i in range(d)]
w = solve(M, Ltr)
return L, M, Ltr, w
def neg_log_marginal_likelihood(R, r, yy, N, K, sigma2):
"""Return y^T Z^-1 y + log det Z from R = Phi^T Phi, r = Phi^T y and yy = y^T y."""
d = len(K)
L, M, Ltr, w = _parts(R, r, K, sigma2)
logdet_m = 2.0 * sum(math.log(v[i]) for i, v in enumerate(cholesky(M)))
quad = (yy - sum(a * b for a, b in zip(Ltr, w))) / sigma2
return quad + (N - d) * math.log(sigma2) + logdet_m
def fit(R, r, K, sigma2):
"""Return g_hat = L M^-1 L^T r, the regularized least squares estimate."""
L, M, Ltr, w = _parts(R, r, K, sigma2)
d = len(K)
return [sum(L[i][t] * w[t] for t in range(d)) for i in range(d)]
def kernel_fir(u, y, d, grid, kernel=tc_kernel, sigma2=None):
"""Return (g_hat, best, sigma2): the estimate, the chosen hyperparameters and the noise variance.
grid is a list of tuples; kernel(d, *eta) is called for each tuple eta.
"""
N = len(y)
Phi = regressor(u, d) # @line L1
R = mul(transpose(Phi), Phi) # @line L2
r = [sum(Phi[k][t] * y[k] for k in range(N)) for t in range(d)]
yy = sum(v * v for v in y)
if sigma2 is None: # @line L3
g_ls = solve(R, r)
sigma2 = (yy - 2.0 * sum(a * b for a, b in zip(g_ls, r))
+ sum(g_ls[i] * R[i][j] * g_ls[j] for i in range(d) for j in range(d))) / (N - d)
best, best_cost = None, math.inf
for eta in grid: # @line L4
K = kernel(d, *eta) # @line L5
cost = neg_log_marginal_likelihood(R, r, yy, N, K, sigma2) # @line L6
if cost < best_cost: # @line L7
best, best_cost = eta, cost
g_hat = fit(R, r, kernel(d, *best), sigma2) # @line L8
return g_hat, best, sigma2 # @line L9
test_kernel_based_identification.py 99 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kernel-based-identification/. The authors are listed in prov/BXFFBH.jsonl.
import math
import random
from ctlmat import det, mul, solve, transpose
from kernel_based_identification import (cholesky, dc_kernel, fit, kernel_fir, neg_log_marginal_likelihood,
regressor, tc_kernel)
def _true_g(d):
return [0.5 * 0.9 ** (k - 1) * math.cos(0.6 * (k - 1)) + 0.3 * 0.6 ** (k - 1) for k in range(1, d + 1)]
def _data(rng, g, N, sigma):
u = [rng.gauss(0.0, 1.0) for _ in range(N)]
y = [sum(g[t - 1] * u[k - t] for t in range(1, len(g) + 1) if k - t >= 0) + rng.gauss(0.0, sigma)
for k in range(N)]
return u, y
def _normal_eq(u, y, d):
Phi = regressor(u, d)
R = mul(transpose(Phi), Phi)
r = [sum(Phi[k][t] * y[k] for k in range(len(y))) for t in range(d)]
return Phi, R, r
def test_regressor_layout():
assert regressor([1, 2, 3], 2) == [[0.0, 0.0], [1.0, 0.0], [2.0, 1.0]]
def test_dc_kernel_contains_tc_kernel():
# rho = lam^(1/2) turns the DC kernel into the TC kernel
lam = 0.8
a, b = dc_kernel(6, 2.0, lam, math.sqrt(lam)), tc_kernel(6, 2.0, lam)
assert all(abs(x - y) < 1e-14 for ra, rb in zip(a, b) for x, y in zip(ra, rb))
L = cholesky(tc_kernel(6, 1.0, 0.7))
back = mul(L, transpose(L))
assert all(abs(x - y) < 1e-14 for ra, rb in zip(back, tc_kernel(6, 1.0, 0.7)) for x, y in zip(ra, rb))
def test_small_forms_match_the_n_by_n_formulas():
rng = random.Random(3)
d, N, sigma2 = 6, 25, 0.04
u, y = _data(rng, _true_g(d), N, 0.2)
Phi, R, r = _normal_eq(u, y, d)
K = tc_kernel(d, 0.5, 0.8)
Z = mul(mul(Phi, K), transpose(Phi))
for i in range(N):
Z[i][i] += sigma2
zy = solve(Z, y)
direct = [sum(v * w for v, w in zip(row, zy)) for row in mul(K, transpose(Phi))]
assert max(abs(a - b) for a, b in zip(fit(R, r, K, sigma2), direct)) < 1e-10
want = sum(a * b for a, b in zip(y, zy)) + math.log(det(Z))
got = neg_log_marginal_likelihood(R, r, sum(v * v for v in y), N, K, sigma2)
assert abs(got - want) < 1e-8 * abs(want)
def test_noise_free_recovery():
# no noise and a tiny sigma2: the estimate is the exact FIR
rng = random.Random(5)
g = _true_g(8)
u, y = _data(rng, g, 60, 0.0)
grid = [(c, lam) for c in (0.3, 1.0) for lam in (0.7, 0.9)]
g_hat, best, s2 = kernel_fir(u, y, 8, grid, sigma2=1e-10)
assert max(abs(a - b) for a, b in zip(g_hat, g)) < 1e-6
def test_regularization_beats_least_squares():
# measurement: d = 30, N = 120, noise standard deviation 0.3
d, N = 30, 120
g = _true_g(d)
grid = [(c, lam) for c in (0.1, 0.3, 1.0) for lam in (0.7, 0.8, 0.9)]
for seed in (1, 2, 3):
rng = random.Random(seed)
u, y = _data(rng, g, N, 0.3)
g_hat, best, s2 = kernel_fir(u, y, d, grid)
_, R, r = _normal_eq(u, y, d)
g_ls = solve(R, r)
err = math.sqrt(sum((a - b) ** 2 for a, b in zip(g_hat, g)))
err_ls = math.sqrt(sum((a - b) ** 2 for a, b in zip(g_ls, g)))
size = math.sqrt(sum(b * b for b in g))
assert err < err_ls
assert err < 0.2 * size
assert 0.05 < s2 < 0.15
def test_dc_kernel_search():
d, N = 20, 100
g = _true_g(d)
rng = random.Random(8)
u, y = _data(rng, g, N, 0.3)
grid = [(c, lam, rho) for c in (0.3, 1.0) for lam in (0.7, 0.9) for rho in (0.0, 0.9)]
g_hat, best, s2 = kernel_fir(u, y, d, grid, kernel=dc_kernel)
assert best in grid
err = math.sqrt(sum((a - b) ** 2 for a, b in zip(g_hat, g)))
assert err < 0.25 * math.sqrt(sum(b * b for b in g))
History
Tikhonov regularization of ill-posed least squares problems is much older than this method. The kernel approach of this page starts with Pillonetto and De Nicolao (2010), who treated the impulse response as a Gaussian process with a stable spline kernel and tuned it by the marginal likelihood. Chen, Ohlsson and Ljung (2012) introduced the TC and DC kernels and compared the method with classical prediction error methods. Pillonetto, Dinuzzo, Chen, De Nicolao and Ljung (2014) surveyed the field in Automatica.
References
- Gianluigi Pillonetto and Giuseppe De Nicolao, A new kernel-based approach for linear system identification, Automatica 46(1), 81-93, 2010, the stable spline kernel, the Gaussian prior on the impulse response, and the choice of hyperparameters by the marginal likelihood
- Tianshi Chen, Henrik Ohlsson and Lennart Ljung, On the estimation of transfer functions, regularizations and Gaussian processes, Revisited, Automatica 48(8), 1525-1535, 2012, the TC and DC kernels and the comparison of regularized FIR estimates with prediction error methods
- Gianluigi Pillonetto, Francesco Dinuzzo, Tianshi Chen, Giuseppe De Nicolao and Lennart Ljung, Kernel methods in system identification, machine learning and function estimation: A survey, Automatica 50(3), 657-682, 2014, the survey of kernels for asymptotically stable systems, empirical Bayes and the relation to regularized least squares
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 BXFFBH Edit this page History Report an error Markdown