Algorithmadvanced
Innovations algorithm
Also called Brockwell-Davis innovations algorithm.
Computes one-step predictors and their error variances from a covariance function by orthogonalizing the observations. It gives the exact Gaussian likelihood.
- Time
- Θ(n^3) worstΘ(n q^2) banded
- Space
- Θ(n^2) extra
- Where
- n = the number of observations; q = the band width of the covariance (the MA order)
- Model
- Real RAM
- Properties
- deterministicexactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Peter J. Brockwell, Richard A. Davis, Craig F. Ansley, 1987
The innovations algorithm turns a covariance function into one-step predictions. Given for a series with mean 0, it computes the best linear predictor of each value from the ones before it, and the mean squared error of that prediction. The predictors are written in terms of the past prediction errors , called innovations, which are uncorrelated. This makes the recursion a Gram-Schmidt orthogonalization of the observations, or equally an Cholesky factorization of their covariance matrix. Unlike the Levinson-Durbin recursion, it does not need stationarity. For a moving-average process of order the covariance is banded and the work falls from to . The errors and variances give the exact Gaussian likelihood, so the algorithm is the standard way to fit MA and ARMA models by maximum likelihood.
In plain words
Watch a series one value at a time and predict the next value from all you have seen. When the value arrives, the gap between it and your prediction is the new information it brings, the innovation. Innovations from different times are unrelated to each other, so you can build each new prediction as a weighted sum of the past innovations, with weights that the covariances tell you. The recursion finds these weights one time step at a time. It also tells you how large each prediction error should be, and that is all the likelihood of normal data needs. If values far apart in time are unrelated, most weights are zero and the work is small.
The problem
Model. have mean 0 and known covariance . The covariance matrix is positive definite. Stationarity is not needed. For a stationary series, .
Output. For , the coefficients and the error variances such that
where is the best linear predictor of from .
Uses.
- Prediction. The predictors follow from the data and the in more operations, or when the covariance has band width .
- Likelihood. For Gaussian data,
with no matrix inverse or determinant.
- MA estimation. Run on the sample autocovariances, estimate the MA() coefficients when is large (Brockwell and Davis 1991, Section 8.3).
The algorithm
INNOVATIONS(κ, n)- 1
v[0] ← κ(1, 1) - 2
for m ← 1 to n - 1 do - 3
for k ← 0 to m - 1 do - 4
s ← κ(m+1, k+1) - Σ_{j=0}^{k-1} θ[k][k-j] · θ[m][m-j] · v[j] - 5
θ[m][m-k] ← s / v[k] - 6
v[m] ← κ(m+1, m+1) - Σ_{j=0}^{m-1} θ[m][m-j]² · v[j] - 7
return (θ, v)
For a covariance with band width ( when ), start the loops in L3, L4 and L6 at instead of 0; the skipped coefficients are 0. The code takes q as an optional argument for this. Line L5 divides by , which is positive when is positive definite. The code raises an error if some . It uses only the four field operations, so it runs exactly on Fraction values.
Example
Take the MA(1) process with , so , and for .
- .
- : , and .
- : , then , and .
- : , , .
In general and with and , so and .
Now observe .
| innovation | ||||
|---|---|---|---|---|
| 1 | 1 | 0 | 1 | 5/4 |
| 2 | -1 | 21/20 | ||
| 3 | 2 | 85/84 | ||
| 4 | 341/340 |
The quadratic form is , and the product of the variances is . So . The tests check these values against the determinant and the inverse of in exact arithmetic.
Correctness
The full proof is in proofs/correctness.md. The innovations are orthogonal and span the same space as , so is the sum of the projections of on each , with coefficient . Expanding by its own predictor gives line L4, and Pythagoras gives line L6. In matrix form, with unit lower triangular, so with . This proves the likelihood formula. A banded covariance makes orthogonal to every with , which justifies the shortened loops.
Proof: The innovations algorithm computes the best linear one-step predictors, their error variances and the LDL factorization of the covariance matrixfull
Setting. are real random variables with mean 0 and finite variance, and . The matrix is positive definite. Work in the Hilbert space with . Let , with , let be the orthogonal projection of on , and let and . In the code, is .
Claim 1 (the innovations are an orthogonal basis). For every , are pairwise orthogonal, , and .
Proof. By induction on . For , and . Suppose the claim holds for . Then is orthogonal to , which contains . Since , . If , then almost surely, so is a linear combination of and is singular. This contradicts the positive definiteness of , because is a leading principal submatrix. So .
Claim 2 (the predictor in terms of innovations). For ,
and .
Proof. By Claim 1, is an orthogonal basis of with nonzero vectors, so the projection on is the sum of the projections on each . That is the first formula. By Pythagoras, and . This is the formula for , which is line L6.
Claim 3 (lines L4 and L5). For ,
So, if lines L3 to L5 compute in the order , every value on the right side is known when it is needed, and line L5 stores the correct .
Proof. By Claim 2 applied to step , (for the sum is empty). Hence
and by Claim 2. The right side uses from an earlier step and with , which line L5 set earlier in the same step. Dividing by (Claim 1) gives line L5.
By induction on , Claims 2 and 3 show that after step the code holds the exact and . Line L1 sets , which is correct because .
Claim 4 (the factorization and the likelihood). Let be the unit lower triangular matrix with for , and . Then and . Hence and , where is the predictor of Claim 2 evaluated at the data. For Gaussian ,
Proof. and Claim 2 give row of . By Claim 1, , so . Then . The map from to with is , and because the predictors computed from the data satisfy the same triangular relation. So . The Gaussian density gives the formula.
Claim 5 (banded covariance). If whenever , then for . So starting the loops in L3, L4 and L6 at gives the same result.
Proof. By Claim 1, . If , then for every , so is orthogonal to each in that span and . By Claim 2, . The terms dropped from the sums in L4 and L6 all contain such a factor with , so they are 0.
Claim 6 (exact arithmetic). Lines L1 to L7 use only addition, subtraction, multiplication and division by . On rational covariances in exact rational arithmetic they return the exact and .
Proof. Claims 1 to 5. No square root or rounding occurs.
The tests check Claim 4 against an independent factorization of random positive definite matrices in Fraction arithmetic, and the likelihood against a direct determinant and quadratic form. They check Claim 5 by comparing the banded and full versions on MA() covariances, and the MA(1) closed form with in exact arithmetic.
Cited, not proved here. For an invertible MA() process, and as (Brockwell and Davis 1991, Chapter 5). If with , the estimates from sample autocovariances are consistent and asymptotically normal (Brockwell and Davis 1991, Section 8.3). The simulation on the page measures the finite-sample behaviour for MA(1).
Complexity
- Full recursion. L4 and L6 do multiplications, counting both products in each term, so the time is , the same order as the Cholesky decomposition it is equivalent to. A run with a counting number type gave 330 multiplications for and 170640 for , equal to the formula.
- Banded, MA(). Each step costs about multiplications, so the total is about , which is and for . Measured counts for were 198, 590, 1172 and 1940 for , just under .
- Predictions. Given the coefficients, the predictors cost , or in the banded case.
- Space. The code keeps all rows of , which is . The banded case needs only the last rows and the last variances, for the recursion, if the predictors are computed on the fly.
For a stationary series with no band, the Durbin-Levinson recursion finds the same predictors in , so the innovations algorithm is the better choice only for banded or nonstationary covariances.
Properties
-
Exact. In exact arithmetic it returns the exact predictors, error variances and likelihood. There is no truncation, and no stationary start-up assumption: the first predictions use only the data actually seen.
-
Online. Step uses only for , so a new observation adds one step, which costs in general and in the banded case.
-
Convergence to the Wold quantities. For a stationary invertible MA() process, and as . The rate is geometric when the roots of are outside the unit circle. For MA(1) with , which is not invertible, , so the convergence is only like .
-
Preliminary MA estimates (measured). MA(1) with , from the sample autocovariances, 200 series per row:
mean sd maximum likelihood sd 200 5 0.4902 0.0746 0.0707 0.0612 200 10 0.4891 0.0704 0.0707 0.0612 200 20 0.4989 0.0682 0.0707 0.0612 1000 5 0.4957 0.0345 0.0316 0.0274 1000 10 0.4972 0.0332 0.0316 0.0274 1000 20 0.4970 0.0350 0.0316 0.0274 The theory (Brockwell and Davis 1991, Section 8.3) gives when slowly with , so the asymptotic variance is , not the of maximum likelihood. The simulation agrees: the estimate is consistent but not efficient, and it is a good start for the likelihood search.
Variants and improvements
- ARMA processes. For a causal ARMA(, ) process, apply the recursion to for and for , with . The covariance of is banded after the first rows, so the cost is (Brockwell and Davis 1991, Section 5.3). This is Ansley's method for the exact ARMA likelihood.
- Durbin-Levinson recursion. For stationary series it computes the predictor coefficients on instead of on the innovations, in ; see the Yule-Walker equations and Levinson-Durbin recursion pages.
- Kalman filter. For a process in state space form, the Kalman filter produces the same innovations and variances in for a state of dimension , and also handles missing values and nonstationary starts.
- Multivariate series. The same recursion holds with matrices: are matrices and are covariance matrices.
- Preliminary ARMA estimates. Combining the innovations estimates of the MA() weights with the relation gives preliminary ARMA estimates (Brockwell and Davis 1991, Section 8.4).
When to use it
Use it to compute the exact Gaussian likelihood or exact finite-sample forecasts of an MA or ARMA model, and for nonstationary covariances where Durbin-Levinson does not apply. It is the core of the prediction error method for these models. For a long stationary AR series, use Durbin-Levinson. For models with missing data, regression effects or time-varying parameters, a state space form with the Kalman filter is usually easier.
Pitfalls
- Indices. The book indexes by the step and the lag of the innovation, so in L5 is the weight on the innovation . Mixing the two indices is the most common error.
- The cost without a band. The full recursion is cubic, not quadratic. It is the predictor step, once the coefficients are known, that is quadratic.
- A covariance that is not positive definite. Sample autocovariances with the divisor can give a negative . Use the divisor .
- Noninvertible MA models. With a root of on the unit circle, converges to slowly and the estimates of often pile up at the boundary. Restrict the search to the invertible region.
- Floating point. The recursion is a Cholesky factorization in disguise and has the same rounding behaviour. Its error grows with the condition number of , which is large when the spectral density is close to 0 at some frequency.
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/innovations-algorithm/. The authors are listed in prov/1XEA6P.jsonl.
"""The innovations algorithm (Brockwell and Davis 1991, section 5.2).
For a zero-mean series X_1, ..., X_n with covariances kappa(i, j) = E[X_i X_j], it returns the
coefficients theta[m][j] (1 <= j <= m) and the mean squared errors v[m] of the one-step
predictors
Xhat_1 = 0, Xhat_(m+1) = sum_(j=1..m) theta[m][j] (X_(m+1-j) - Xhat_(m+1-j)).
The recursion uses only +, -, * and /, so it runs unchanged on fractions.Fraction values.
Indices follow the book: kappa is called with 1-based arguments.
"""
from __future__ import annotations
import math
from typing import Callable, Sequence
def innovations(kappa: Callable[[int, int], object], n: int, q: int | None = None):
"""Return (theta, v). theta[m] is a list with theta[m][j] at index j (index 0 unused).
If q is given, kappa(i, j) must be 0 whenever |i - j| > q (an MA(q) process). Then
theta[m][j] = 0 for j > q and the loops skip those zeros, so the cost is O(n q^2).
"""
if n < 1:
raise ValueError("need n >= 1")
theta: list[list] = [[0]]
v = [kappa(1, 1)] # @line L1
if not v[0] > 0:
raise ValueError("kappa(1, 1) must be positive")
for m in range(1, n): # @line L2
row = [0] * (m + 1)
k_lo = 0 if q is None else max(0, m - q)
for k in range(k_lo, m): # @line L3
s = kappa(m + 1, k + 1)
for j in range(k_lo, k):
s -= theta[k][k - j] * row[m - j] * v[j] # @line L4
row[m - k] = s / v[k] # @line L5
theta.append(row)
vm = kappa(m + 1, m + 1) - sum(row[m - j] * row[m - j] * v[j] for j in range(k_lo, m)) # @line L6
if not vm > 0:
raise ValueError("the covariance matrix is not positive definite")
v.append(vm)
return theta, v # @line L7
def one_step_predictors(x: Sequence, theta: list[list]) -> list:
"""Return Xhat_1, ..., Xhat_n (and Xhat_(n+1) if theta has n rows past row 0)."""
n = len(x)
xhat = [0 * x[0] if n else 0]
for m in range(1, min(n, len(theta) - 1) + 1):
xhat.append(sum(theta[m][j] * (x[m - j] - xhat[m - j]) for j in range(1, m + 1)))
return xhat
def gaussian_neg2_loglik(x: Sequence[float], kappa: Callable[[int, int], float],
q: int | None = None) -> float:
"""-2 log L of a zero-mean Gaussian vector with covariance kappa, by the innovations.
-2 log L = n log(2 pi) + sum_j log v_(j-1) + sum_j (X_j - Xhat_j)^2 / v_(j-1).
"""
n = len(x)
theta, v = innovations(kappa, n, q)
xhat = one_step_predictors(list(x), theta)
total = n * math.log(2 * math.pi)
total += math.fsum(math.log(v[j]) for j in range(n))
total += math.fsum((x[j] - xhat[j]) ** 2 / v[j] for j in range(n))
return total
def ma_autocovariance(theta: Sequence, sigma2, max_lag: int) -> list:
"""gamma(h) of X_t = e_t + theta_1 e_(t-1) + ... + theta_q e_(t-q), e ~ WN(0, sigma2)."""
c = [1] + list(theta)
q = len(c) - 1
return [sigma2 * sum(c[j] * c[j + h] for j in range(q - h + 1)) if h <= q else 0 * sigma2
for h in range(max_lag + 1)]
def stationary_kappa(gamma: Sequence) -> Callable[[int, int], object]:
"""kappa(i, j) = gamma(|i - j|) for a stationary series, with gamma(h) = 0 past the list."""
zero = 0 * gamma[0]
def kappa(i: int, j: int):
h = abs(i - j)
return gamma[h] if h < len(gamma) else zero
return kappa
def ma_preliminary_estimate(x: Sequence[float], q: int, m: int) -> tuple[list[float], float]:
"""Preliminary MA(q) estimate (Brockwell and Davis 1991, section 8.3).
Run the recursion on the sample autocovariances (divisor n) up to step m and return
(theta_hat[m][1..q], v_hat[m]).
"""
n = len(x)
if not q <= m < n:
raise ValueError("need q <= m < n")
mean = math.fsum(x) / n
d = [xi - mean for xi in x]
gamma = [math.fsum(d[t + h] * d[t] for t in range(n - h)) / n for h in range(m + 1)]
theta, v = innovations(stationary_kappa(gamma), m + 1)
return [theta[m][j] for j in range(1, q + 1)], v[m]
test_innovations_algorithm.py 153 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/innovations-algorithm/. The authors are listed in prov/1XEA6P.jsonl.
import math
import random
from fractions import Fraction
import pytest
from innovations_algorithm import (
gaussian_neg2_loglik,
innovations,
ma_autocovariance,
ma_preliminary_estimate,
one_step_predictors,
stationary_kappa,
)
def ldl(a: list[list[Fraction]]) -> tuple[list[list[Fraction]], list[Fraction]]:
"""The LDL^T factorization of a symmetric positive definite matrix in exact arithmetic."""
n = len(a)
low = [[Fraction(int(i == j)) for j in range(n)] for i in range(n)]
d = [Fraction(0)] * n
for j in range(n):
d[j] = a[j][j] - sum(low[j][k] ** 2 * d[k] for k in range(j))
for i in range(j + 1, n):
low[i][j] = (a[i][j] - sum(low[i][k] * low[j][k] * d[k] for k in range(j))) / d[j]
return low, d
def solve_and_det(a: list[list[Fraction]], b: list[Fraction]) -> tuple[list[Fraction], Fraction]:
"""Gaussian elimination in Fractions: the solution of a y = b and det(a)."""
n = len(b)
m = [row[:] + [b[i]] for i, row in enumerate(a)]
det = Fraction(1)
for c in range(n):
piv = next(r for r in range(c, n) if m[r][c] != 0)
if piv != c:
m[c], m[piv] = m[piv], m[c]
det = -det
det *= m[c][c]
for r in range(c + 1, n):
f = m[r][c] / m[c][c]
m[r] = [x - f * y for x, y in zip(m[r], m[c])]
y = [Fraction(0)] * n
for i in reversed(range(n)):
y[i] = (m[i][n] - sum(m[i][j] * y[j] for j in range(i + 1, n))) / m[i][i]
return y, det
def random_spd(n: int, rng: random.Random) -> list[list[Fraction]]:
b = [[Fraction(rng.randint(-3, 3)) for _ in range(n)] for _ in range(n)]
return [[sum(b[i][k] * b[j][k] for k in range(n)) + (1 if i == j else 0) for j in range(n)]
for i in range(n)]
def test_matches_ldl_of_the_covariance_matrix():
rng = random.Random(1)
for n in range(1, 8):
for _ in range(5):
a = random_spd(n, rng)
theta, v = innovations(lambda i, j: a[i - 1][j - 1], n)
low, d = ldl(a)
assert v == d
for m in range(1, n):
for k in range(m):
assert theta[m][m - k] == low[m][k]
def test_ma1_closed_form():
th, s2 = Fraction(1, 2), Fraction(3)
g = ma_autocovariance([th], s2, 1)
theta, v = innovations(stationary_kappa(g), 12)
def big_s(k: int) -> Fraction:
return sum(th ** (2 * i) for i in range(k + 1))
for m in range(12):
assert v[m] == s2 * big_s(m + 1) / big_s(m)
if m >= 1:
assert theta[m][1] == th * s2 / v[m - 1]
assert all(t == 0 for t in theta[m][2:])
def test_banded_version_equals_full_version_for_ma_q():
rng = random.Random(2)
for q in (1, 2, 3):
for _ in range(4):
th = [Fraction(rng.randint(-5, 5), 4) for _ in range(q)]
g = ma_autocovariance(th, Fraction(1), q)
full = innovations(stationary_kappa(g), 15)
band = innovations(stationary_kappa(g), 15, q=q)
assert full == band
assert all(t == 0 for m in range(q + 1, 15) for t in full[0][m][q + 1:])
def test_ma_autocovariance_against_expansion():
rng = random.Random(3)
for q in range(5):
th = [Fraction(rng.randint(-6, 6), 3) for _ in range(q)]
c = [Fraction(1)] + th
s2 = Fraction(rng.randint(1, 5))
got = ma_autocovariance(th, s2, q + 3)
for h in range(q + 4):
# X_(t+h) = sum_i c_i e_(t+h-i) and X_t = sum_j c_j e_(t-j); only equal noise indices
# contribute, each with variance s2.
brute = sum(c[i] * c[j] * s2 for i in range(q + 1) for j in range(q + 1) if h - i == -j)
assert got[h] == brute
def test_ar1_predictor_is_phi_times_last_value():
phi = Fraction(3, 5)
g = [phi ** h / (1 - phi ** 2) for h in range(10)]
theta, v = innovations(stationary_kappa(g), 10)
x = [Fraction(v_) for v_ in (2, -1, 3, 0, 5, -4, 1, 1, 2, -2)]
xhat = one_step_predictors(x, theta)
assert xhat[0] == 0
assert all(xhat[m] == phi * x[m - 1] for m in range(1, 10))
assert v[0] == 1 / (1 - phi ** 2) and all(vm == 1 for vm in v[1:])
def test_likelihood_matches_direct_determinant_and_quadratic_form():
rng = random.Random(4)
for n in (1, 3, 6, 9):
a = random_spd(n, rng)
x = [Fraction(rng.randint(-5, 5)) for _ in range(n)]
y, det = solve_and_det(a, x)
quad = sum(xi * yi for xi, yi in zip(x, y))
direct = n * math.log(2 * math.pi) + math.log(det) + float(quad)
got = gaussian_neg2_loglik([float(t) for t in x], lambda i, j: float(a[i - 1][j - 1]))
assert got == pytest.approx(direct, rel=1e-12, abs=1e-9)
def test_preliminary_ma1_estimate_is_near_truth():
# Measured, not proved: mean over r = 20 series of n = 2000 with theta = 0.5, seed 5.
rng = random.Random(5)
r, total = 20, 0.0
for _ in range(r):
e = [rng.gauss(0, 1) for _ in range(2001)]
x = [e[t] + 0.5 * e[t - 1] for t in range(1, 2001)]
est, v = ma_preliminary_estimate(x, 1, 20)
total += est[0]
# The innovations estimate has asymptotic variance 1/n here (Brockwell and Davis 1991,
# section 8.3), so the standard error of the mean is about 0.005; the bias for m = 20 is small.
assert abs(total / r - 0.5) < 0.04
def test_errors():
with pytest.raises(ValueError):
innovations(lambda i, j: 1.0, 2) # a singular all-ones matrix
with pytest.raises(ValueError):
innovations(lambda i, j: 0.0, 1)
History
The innovations idea comes from filtering theory, where Kailath's innovations approach of the late 1960s wrote linear estimation in terms of the uncorrelated prediction errors. For time series models, Ansley (1979) computed the exact Gaussian likelihood of an ARMA process by a Cholesky factorization of the banded covariance matrix of . Brockwell and Davis gave the recursion for one-step predictors its standard form and name in the 1987 first edition of Time Series: Theory and Methods, together with its use for MA estimation and recursive likelihood evaluation. Their textbooks made it a standard tool, beside the Durbin-Levinson recursion and the Kalman filter.
References
- Peter J. Brockwell and Richard A. Davis, Time Series: Theory and Methods, second edition, Springer, 1991, Section 5.2 (the innovations algorithm, pp. 169 to 174), Section 5.3 (recursive prediction of an ARMA process, p. 175), Section 8.3 (preliminary MA estimates by the innovations algorithm, p. 245) and Section 8.6 (recursive calculation of the Gaussian likelihood, p. 254)
- Peter J. Brockwell and Richard A. Davis, Introduction to Time Series and Forecasting, third edition, Springer, 2016, Section 2.5.4 (the innovations algorithm, p. 62), Section 5.1.3 (MA estimation, p. 132) and Section 5.2 (maximum likelihood, p. 139)
- Craig F. Ansley, An algorithm for the exact likelihood of a mixed autoregressive-moving average process, Biometrika 66(1), 1979, pp. 59 to 65 (the Cholesky factor of the banded covariance of the transformed process)
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 1XEA6P Edit this page History Report an error Markdown