Skip to content

System identification

You have measured the input and the output of a machine, a process or a plant, and you want a model that predicts the output from past inputs and outputs. For a nonlinear system, a common model is a sum of simple terms: past outputs such as y(t-1), past inputs such as u(t-1), and their products and squares. Which terms belong in the model? With too few, the model misses the dynamics. With too many, it fits the noise and predicts badly. Choosing the terms is a combinatorial search: gradient methods cannot do it, because a term is either in the model or not.

Measured input u and output y of an unknown system, and candidate terms built from earlier samples, with five of them selected
The search chooses the terms of the model. For each choice, least squares gives the coefficients. The five selected terms here are those of the true model below.

This example uses data simulated from a known system, so the answer can be checked. The true model has five terms:

y(t) = 0.7 y(t-1) + u(t-1) - u(t-2) + 0.3 y(t-1) u(t-1) - 0.2 y(t-2)^2 + noise

The noise enters the system at each step. The input is random but changes slowly, as it often does when a signal is sampled fast. There are 500 samples to fit the model and 300 new ones to test it. Two candidate sets:

Candidates Terms Structures Best BIC
lags up to 2 15 2^15 = 32 768 -3001.28, exact (all structures checked in a fraction of a second)
lags up to 3 28 2^28, about 268 million -2994.40, best known

In both sets the best structure is exactly the true model. (The two values differ because the larger set leaves one sample fewer to fit.) Checking all structures of the larger set would take about 10 minutes, and each added candidate doubles that: with lags up to 4 there are 45 candidates, and it would take years. This is where a metaheuristic earns its place.

The model

The variable is one Binary vector with one bit per candidate term: 1 means the term is in the model. Selection would fix the number of terms, but that number is part of the answer, so Binary fits better.

For each choice of terms, the coefficients come from ordinary least squares (np.linalg.lstsq), so the search works only on the structure. The score is the Bayesian information criterion (BIC):

BIC = m ln(RSS / m) + k ln(m)

where RSS is the sum of squared errors of the fit, m the number of samples and k the number of terms. Lower is better. The first part rewards a good fit and the second charges for each term. With 500 samples, a new term must cut the squared error by about 1.25 percent to pay for itself, so terms that only fit the noise stay out.

import numpy as np
import ypea

# the data, generated from a seed
rng = np.random.default_rng(21)
n = 500
u = np.zeros(n + 200)  # a random input that changes slowly
for t in range(1, n + 200):
    u[t] = 0.98 * u[t - 1] + 0.1 * rng.standard_normal()
u = u[200:]
noise = 0.05 * rng.standard_normal(n)
y = np.zeros(n)
for t in range(2, n):  # the true system, unknown to the search
    y[t] = 0.7 * y[t - 1] + u[t - 1] - u[t - 2] + 0.3 * y[t - 1] * u[t - 1] - 0.2 * y[t - 2] ** 2 + noise[t]

# the candidate terms: a constant, lags 1 to 3, and all products and squares of the lags
max_lag = 3
signals = {}
for lag in range(1, max_lag + 1):
    signals[f"y(t-{lag})"] = y[max_lag - lag:n - lag]
for lag in range(1, max_lag + 1):
    signals[f"u(t-{lag})"] = u[max_lag - lag:n - lag]
names = ["1"] + list(signals)
columns = [np.ones(n - max_lag)] + list(signals.values())
keys = list(signals)
for i in range(len(keys)):
    for j in range(i, len(keys)):
        if i == j:
            names.append(f"{keys[i]}^2")
        else:
            names.append(f"{keys[i]}*{keys[j]}")
        columns.append(signals[keys[i]] * signals[keys[j]])
regressors = np.column_stack(columns)  # one column per candidate term
target = y[max_lag:]  # the outputs to explain


def bic(sol):
    terms = sol.terms == 1  # the chosen columns
    k = np.sum(terms)
    residual = target
    if k > 0:
        coefficients = np.linalg.lstsq(regressors[:, terms], target, rcond=None)[0]
        residual = target - regressors[:, terms] @ coefficients
    m = len(target)
    return m * np.log(residual @ residual / m) + k * np.log(m)


problem = ypea.Problem(
    ypea.Binary("terms", shape=len(names)),
    bic,
    name="28 candidates",
)
result = ypea.GA(max_nfe=3_000, space="native").solve(problem, seed=1)
print(result.summary())

chosen = []
for j in np.flatnonzero(result.best.solution.terms):
    chosen.append(names[j])
print("terms:", chosen)
GA on 28 candidates
  best objective value: -2994.4
  feasible: True (violation 0)
  evaluations: 3000, iterations: 29, time: 0.152 s, stopped by: max_nfe
terms: ['y(t-1)', 'u(t-1)', 'u(t-2)', 'y(t-1)*u(t-1)', 'y(t-2)^2']

Differs from Python: MATLAB draws its own random numbers and its own data from the seed, so the results differ from Python's.

% the data, generated from a seed
generator = ypea.Rng(21);
n = 500;
u = zeros(n + 200, 1);  % a random input that changes slowly
for t = 2:n + 200
    u(t) = 0.98 * u(t - 1) + 0.1 * generator.standard_normal();
end
u = u(201:end);
noise = 0.05 * generator.standard_normal(n, 1);
y = zeros(n, 1);
for t = 3:n  % the true system, unknown to the search
    y(t) = 0.7 * y(t - 1) + u(t - 1) - u(t - 2) + 0.3 * y(t - 1) * u(t - 1) - 0.2 * y(t - 2)^2 + noise(t);
end

% the candidate terms: a constant, lags 1 to 3, and all products and squares of the lags
max_lag = 3;
keys = strings(1, 0);
signals = zeros(n - max_lag, 0);
for lag = 1:max_lag
    keys(end + 1) = "y(t-" + lag + ")";
    signals(:, end + 1) = y(max_lag - lag + 1:n - lag);
end
for lag = 1:max_lag
    keys(end + 1) = "u(t-" + lag + ")";
    signals(:, end + 1) = u(max_lag - lag + 1:n - lag);
end
names = ["1", keys];
regressors = [ones(n - max_lag, 1), signals];  % one column per candidate term
for i = 1:numel(keys)
    for j = i:numel(keys)
        if i == j
            names(end + 1) = keys(i) + "^2";
        else
            names(end + 1) = keys(i) + "*" + keys(j);
        end
        regressors(:, end + 1) = signals(:, i) .* signals(:, j);
    end
end
target = y(max_lag + 1:end);  % the outputs to explain

problem = ypea.Problem( ...
    vars=ypea.Binary("terms", shape=numel(names)), ...
    objective=@(sol) bic(sol.terms, regressors, target), ...
    name="28 candidates");
result = ypea.GA(max_nfe=3000, space="native").solve(problem, seed=1);
disp(result.summary())

chosen = names(result.best.solution.terms == 1);
disp("terms: " + strjoin(chosen, ", "))

function value = bic(terms, regressors, target)
chosen = terms == 1;  % the chosen columns
k = sum(chosen);
residual = target;
if k > 0
    coefficients = lsqminnorm(regressors(:, chosen), target);  % least squares
    residual = target - regressors(:, chosen) * coefficients;
end
m = numel(target);
value = m * log(residual' * residual / m) + k * log(m);
end
GA on 28 candidates
  best objective value: -2936.82
  feasible: true (violation 0)
  evaluations: 3000, iterations: 29, time: 0.783 s, stopped by: max_nfe
terms: y(t-1), u(t-1), u(t-2), y(t-1)*u(t-1), y(t-2)^2

The genetic algorithm with native binary operators (space="native") finds the five true terms among 28 candidates in 3000 evaluations and a fraction of a second. Least squares then gives coefficients close to the true ones (0.687, 1.013, -1.019, 0.366 and -0.259). The full script, examples/applications/system_identification.py, also checks all 32 768 structures of the smaller set and runs two classic greedy methods.

Why not a classic greedy method?

Forward selection (and orthogonal forward regression, its fast form) adds the term that helps most, one at a time. Stepwise selection here starts from the model with every term and adds or drops the one term that helps most, until no single change helps. Both are fast and often work, but on this data they miss:

Method 15 candidates: BIC above the best 28 candidates: BIC above the best
forward selection, best model along its path 7.58 (two extra terms) 13.42 (three extra terms)
stepwise selection from the full model 0 (finds it) 35.35 (13 terms, two true ones missing)

The reason is the slow input. The terms u(t-1) and u(t-2) are almost equal (correlation 0.99), and so are many products of slow signals. A greedy method judges one term at a time against the terms it already has: forward selection keeps the extra terms it added early, and stepwise selection gets lost among near duplicates. A search over whole structures does not have this weakness. This data set was chosen to show the problem, but it is common: on the 23 stable data sets from seeds 0 to 23 (this one included), at least one of the two greedy methods found the best known structure only 12 times, while a single GA run found it 21 times.

Results

Five algorithms, each with 10 seeded runs: 1000 evaluations with 15 candidates (3 percent of the structures) and 3000 with 28. GA and SA use the native binary operators, tabu search and ILS flip one bit at a time, and PSO works in the encoded space. The gap is the BIC above the best structure (exact with 15 candidates, best known with 28).

Candidates Algorithm Runs with the best structure Mean BIC gap Worst BIC gap
15 GA 10 of 10 0.00 0.00
15 SA 10 of 10 0.00 0.00
15 Tabu search 10 of 10 0.00 0.00
15 ILS 10 of 10 0.00 0.00
15 PSO 9 of 10 0.19 1.93
28 GA 10 of 10 0.00 0.00
28 SA 0 of 10 5.56 11.10
28 Tabu search 10 of 10 0.00 0.00
28 ILS 10 of 10 0.00 0.00
28 PSO 5 of 10 6.15 19.02

GA, tabu search and ILS find the true model in every run. SA always keeps the five true terms but adds one to three extra ones with 28 candidates, and PSO sometimes trades a true term for others. Each run takes well under a second.

Free-run prediction of the model selected by GA with seed 1 on the validation data
On 300 new samples, the model of GA (blue) runs on the input alone, feeding back its own past outputs. It follows the measured output (gray) with an RMS error of 0.100. The true system with its exact coefficients does only a little better (0.085), because the rest is the noise that enters at each step.

Try it on your own data

Replace u and y with your measurements, and choose the largest lag and the kinds of terms (products, squares, cubes) from what you know about the system. Always test the model on data it was not fitted on, and in free run, as in the figure: a model can predict one step ahead well and still drift when it feeds back its own outputs. If the chosen model has too many terms, use a stronger penalty than BIC. GA, tabu search and ILS are good first choices. With hundreds of candidates, checking every structure is out of reach, and so is starting from the full model when there are more terms than samples, but the search stays the same.