Scientific Machine Learning:
Sparse Regression for Equation Discovery

Physical laws are short. Kepler's third law has one exponent, Hooke's law one constant, Newton's second law three symbols. When an engineer tries to recover a law from measurements, the difficulty is rarely that no formula fits the data; it is that too many do. A long enough expansion passes through every point. The question is how to find, among all the terms that could appear, the few that actually do.


This notebook treats that question as a regression problem with a twist. The unknown is a vector of coefficients, one for every candidate term in a library of functions, and the answer is the vector with the fewest nonzero entries that still explains the data. The methods are those of sparse regression: the $L_1$ penalty, which turns coefficients to zero where the $L_2$ penalty only makes them small; the sequential thresholded least squares algorithm, which is a few lines long and is the engine of the next notebook; and the tools for deciding how many terms to keep. Nothing here involves a differential equation yet. The same machinery, applied to time derivatives, becomes the method called SINDy in Sparse Identification of Nonlinear Dynamics, and the notebook ends where that one begins.


Learning Objectives

After studying this notebook, you should be able to

  • state the equation-discovery problem as a linear regression over a library of candidate functions, and explain why the solution is expected to be sparse;
  • build a library, fit it by least squares, and explain why least squares assigns a nonzero coefficient to every column;
  • explain the difference between the $L_2$ and $L_1$ penalties geometrically, and why only the $L_1$ penalty sets coefficients exactly to zero;
  • solve the LASSO with CVXPY, implement the sequential thresholded least squares algorithm, and compare the two on the same data;
  • choose the sparsity threshold from the data by sweeping it and reading the long flat step;
  • recognize the three ways in which sparse regression fails, a missing term, nearly collinear candidates and excessive noise, and know what each looks like in the output; and
  • recover an algebraic law from measurements, as a power law in logarithms and as a correction series.

Setup

NumPy, Matplotlib and CVXPY are all that is needed.

In [ ]:
import numpy as np
import matplotlib.pyplot as plt
import cvxpy as cvx




1. Why Few Terms

1.1. Laws Are Short

In 1619 Kepler, after years with Tycho Brahe's tables, wrote down that the square of a planet's period is proportional to the cube of its distance from the Sun. The statement has one adjustable number, the exponent, and the data of eight planets fix it to three decimal places. The semi-major axes and periods are listed below in astronomical units and years, so that Earth is $(1, 1)$.

In [ ]:
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
a = np.array([0.387, 0.723, 1.000, 1.524, 5.203, 9.537, 19.19, 30.07])     # semi-major axis (AU)
T = np.array([0.241, 0.615, 1.000, 1.881, 11.86, 29.46, 84.01, 164.8])     # orbital period (years)
In [ ]:
plt.figure(figsize=(6, 4))
plt.plot(a, T, 'ko')

plt.xlabel('Semi-major axis a (AU)')
plt.ylabel('Period T (years)')
plt.title('Planetary Data: Period vs Distance (Linear Scale)')
plt.grid(True)
plt.show()
No description has been provided for this image
In [ ]:
plt.figure(figsize = (6, 4))
plt.loglog(a, T, 'ko')
for i in range(8):
    plt.text(a[i]*1.15, T[i], planets[i])
plt.xlabel('semi-major axis a (AU)')
plt.ylabel('period T (years)')
plt.grid(True)
plt.show()
No description has been provided for this image

On logarithmic axes the eight planets lie on a straight line, and a straight line in logarithms is a power law: $\log T = p\log a + c$ means $T = e^{c}a^{p}$. Fitting the line is one least-squares problem with two unknowns.

In [ ]:
# log T = p log a + c  is a straight line: fit p and c by least squares

A = np.hstack([np.log(a).reshape(-1, 1), np.ones((8, 1))])
y = np.log(T)

coef = np.linalg.inv(A.T @ A) @ A.T @ y

print('exponent p = %.4f,  constant c = %.4f' % (coef[0], np.exp(coef[1])))
exponent p = 1.4997,  constant c = 1.0003

The exponent is $1.4997$, the constant is $1.0003$, and Kepler's law $T^2 \propto a^3$, which is $p = 3/2$, is recovered from eight numbers with no theory of gravitation in sight. Two things made this possible. The law has very few terms, and the terms it has, $\log a$ and a constant, were the right ones to try. Every discovery method in this notebook and the next two is an attempt to make the second condition less demanding: to offer a long list of possible terms and let the data pick out the short one.


1.2. Discovery as Regression

Suppose a quantity $y$ is measured at $m$ values of an input $x$, and $y$ is believed to be a combination of a few functions of $x$, without knowing which. The approach is to write down more candidates than can possibly be needed, say $b_1(x), \ldots, b_d(x)$, and to look for coefficients $\theta_1, \ldots, \theta_d$ such that


$$ y \approx \theta_1 b_1(x) + \theta_2 b_2(x) + \cdots + \theta_d b_d(x) . $$


This is the linear basis function model of Machine Learning, and the candidates are its basis functions; the set of candidates is called the library. Evaluating every candidate at every data point gives the $m \times d$ design matrix $\Phi$, whose $j$th column is $b_j$ at the $m$ points, and the prediction is


$$ \hat{y} = \Phi\,\theta , \qquad \Phi = \begin{bmatrix} | & | & & | \\ b_1(x) & b_2(x) & \cdots & b_d(x) \\ | & | & & | \end{bmatrix} , \qquad \theta = \begin{bmatrix} \theta_1 \\ \vdots \\ \theta_d \end{bmatrix} . $$


The least-squares fit $\min_\theta \lVert\Phi\theta - y\rVert_2^2$ and its solution $\theta^* = (\Phi^T\Phi)^{-1}\Phi^T y$ are those of Machine Learning, with one difference in what is asked of them. There the coefficients were a means to a prediction; here they are the answer. A law with two terms is a vector $\theta$ with two nonzero entries and $d - 2$ zeros, and the problem is to find such a vector, not merely a vector that predicts $y$ well. A vector with few nonzero entries is called sparse, and the search for it is sparse regression.


The expectation that the answer is sparse is a physical prior, of the same kind as the physical priors of Embedding Physical Knowledge: it is not learned from the data but imposed on the solution, because experience says that laws are short. Without it the problem is not well posed, since with enough candidates many different $\theta$ fit the same data equally well. With it, the problem is to find the shortest explanation, and the notebook now follows what happens when that is attempted with the ordinary tools first.




2. Least Squares with a Library

2.1. Building a Library

The running example is a quantity generated by the law $y = 1.5x - 0.8x^3$, measured at $100$ random points in $[-3, 3]$ with Gaussian noise of standard deviation $0.2$. The law is known here so that every method can be judged against it; in use it would not be.

In [ ]:
np.random.seed(0)

m = 100
x = np.sort(np.random.uniform(-3, 3, m))
y = 1.5*x - 0.8*x**3 + 0.2*np.random.randn(m)

xp = np.linspace(-4, 4, 300)                        # for plotting, extends beyond the data
yp = 1.5*xp - 0.8*xp**3

plt.figure(figsize = (6, 4))
plt.plot(xp, yp, 'k', alpha = 0.3, linewidth = 4, label = 'True law')
plt.plot(x, y, 'bo', markersize = 2, label = 'Data')
plt.xlabel('x')
plt.ylabel('y')
plt.xlim([-4, 4])
plt.ylim([-40, 40])
plt.legend()
plt.grid(True)
plt.show()
No description has been provided for this image

The library is chosen without knowledge of the law: the constant, the powers of $x$ up to the fifth, and the two trigonometric functions $\sin 2x$ and $\cos 2x$, eight candidates in all,


$$ \begin{aligned} b_1(x) &= 1, \quad b_2(x) = x, \quad b_3(x) = x^2, \quad b_4(x) = x^3, \\ b_5(x) &= x^4, \quad b_6(x) = x^5, \quad b_7(x) = \sin 2x, \quad b_8(x) = \cos 2x . \end{aligned} $$


The true law uses two of them, $b_2$ and $b_4$. Evaluating the eight candidates at the $100$ data points gives the design matrix


$$ \Phi = \begin{bmatrix} | & | & & | \\ b_1(x) & b_2(x) & \cdots & b_8(x) \\ | & | & & | \end{bmatrix} \in \mathbb{R}^{100 \times 8} , $$


one row per observation and one column per candidate, exactly the matrix of Machine Learning with a longer list of basis functions. The function library builds $\Phi$ from a vector of inputs, and names labels its columns for printing.

In [ ]:
def library(x):
    x = x.reshape(-1, 1)
    return np.hstack([x**0, x, x**2, x**3, x**4, x**5, np.sin(2*x), np.cos(2*x)])

names = ['1', 'x', 'x^2', 'x^3', 'x^4', 'x^5', 'sin 2x', 'cos 2x']

Phi = library(x)
print(Phi.shape)
(100, 8)

A printing helper

Coefficients below $10^{-10}$ in magnitude are printed as a dash, so that a sparse vector can be read at a glance.

In [ ]:
def print_coef(theta, names):
    for name, t in zip(names, theta):
        if abs(t) > 1e-10:
            print('%8s : %9.3f' % (name, t))
        else:
            print('%8s :     -' % name)

2.2. Least Squares Uses Every Column

Ordinary least squares picks the $\theta$ that minimizes $\lVert\Phi\theta - y\rVert_2^2$. With more data points than columns $\Phi^T\Phi$ is invertible, and the normal equation $\theta^* = (\Phi^T\Phi)^{-1}\Phi^T y$ of Machine Learning gives the minimizer directly.

In [ ]:
theta_ls = np.linalg.inv(Phi.T @ Phi) @ Phi.T @ y

print_coef(theta_ls, names)
print('training error : %.3f' % np.mean((Phi @ theta_ls - y)**2))
       1 :     0.014
       x :     1.481
     x^2 :     0.037
     x^3 :    -0.807
     x^4 :    -0.005
     x^5 :     0.001
  sin 2x :    -0.030
  cos 2x :     0.018
training error : 0.037

The two true terms come out close to their values, $x$ at $1.48$ against $1.5$ and $x^3$ at $-0.81$ against $-0.8$, and that is the good news. The bad news is the other six: every one of them has a nonzero coefficient, between $0.001$ for $x^5$ and $0.037$ for $x^2$. Written out, the fit is


$$ \hat{y} = 0.014 + 1.481\,x + 0.037\,x^2 - 0.807\,x^3 - 0.005\,x^4 + 0.001\,x^5 - 0.030\,\sin 2x + 0.018\,\cos 2x , $$


against the law $y = 1.5x - 0.8x^3$. Least squares has no reason to set anything to zero. It is asked for the best fit, and a coefficient of $0.037$ on $x^2$ fits the noise a little better than a coefficient of zero, so $0.037$ it is. The result is an eight-term formula, and nothing in it says which six terms are noise.

In [ ]:
plt.figure(figsize = (6, 4))
plt.plot(xp, yp, 'k', alpha = 0.3, linewidth = 4, label = 'True law')
plt.plot(x, y, 'bo', markersize = 2, label = 'Data')
plt.plot(xp, library(xp) @ theta_ls, 'r--', label = 'Least squares, 8 terms')
plt.xlabel('x')
plt.ylabel('y')
plt.xlim([-4, 4])
plt.ylim([-40, 40])
plt.legend()
plt.grid(True)
plt.show()
No description has been provided for this image

Inside the data range the eight-term fit is indistinguishable from the law. Outside it, beyond $x = \pm 3$, the two begin to separate, because the spurious terms, small as they are, grow at their own rates once nothing holds them. This is the usual price of a model with too many terms, and it is the reason the question "which terms?" cannot be answered by the fit alone.


2.3. Why: Noise and Correlated Columns

Two things conspire to put nonzero weight on the wrong columns.


(1) Noise

The data differ from the law by random amounts, and any column that happens to correlate with those amounts is given a coefficient to absorb them. Least squares asks only for the smallest residual, and a small nonzero coefficient always achieves that a little better than zero.


(2) Correlated columns

The columns of a library are rarely independent. On $[-3, 3]$ the functions $x$ and $x^3$ have the same sign everywhere and rise together; $x^3$ and $x^5$ even more so. When two columns are nearly proportional, the data cannot tell how to divide a contribution between them, and the least-squares answer divides it in whatever way the noise suggests. The singular values of $\Phi$ measure how close the columns come to dependence.

In [ ]:
s = np.linalg.svd(Phi, compute_uv = False)
print('singular values of Phi : largest %.2e, smallest %.2e' % (s[0], s[-1]))
print('condition number       : %.2e' % (s[0]/s[-1]))

C = np.corrcoef(Phi[:, 1:].T)                      # correlation between columns (constant column left out)
print('correlation between x and x^3     : %.3f' % C[0, 2])
print('correlation between x^3 and x^5   : %.3f' % C[2, 4])
print('correlation between x and sin 2x  : %.3f' % C[0, 5])
print('correlation between x^2 and cos 2x: %.3f' % C[1, 6])
singular values of Phi : largest 7.62e+02, smallest 8.51e-01
condition number       : 8.95e+02
correlation between x and x^3     : 0.921
correlation between x^3 and x^5   : 0.977
correlation between x and sin 2x  : -0.385
correlation between x^2 and cos 2x: 0.130

The condition number is about $900$: the library has directions in coefficient space along which the data constrain the solution $900$ times more weakly than along others. The correlations say where those directions are. The powers $x$ and $x^3$ are correlated at $0.92$ and $x^3$ and $x^5$ at $0.98$, so the three odd powers are nearly interchangeable on this interval, and a small change in the data can move weight from one to another. The trigonometric columns are far less correlated with the powers, which is why their spurious coefficients in the least-squares fit were the smaller ones. Correlated candidates are a permanent feature of libraries built from powers and simple functions, and every method below has to cope with them.




3. Regularization: $L_2$ and $L_1$

3.1. Ridge Regression Shrinks

Regularization, MAP Estimation, and Loss Weighting introduced regularization as a second term in the objective that measures the size of the coefficients, and showed that the ridge penalty $\lambda\lVert\theta\rVert_2^2$ corresponds to a Gaussian prior on $\theta$. The ridge objective and its closed-form minimizer are those of Machine Learning,


$$ J_2(\theta) = \lVert\Phi\theta - y\rVert_2^2 + \lambda\lVert\theta\rVert_2^2 , \qquad \theta_{\mathrm{ridge}} = (\Phi^T\Phi + \lambda I)^{-1}\Phi^T y . $$


The question for discovery is whether making coefficients small can make them zero. Following every coefficient as $\lambda$ runs from $10^{-4}$ to $10^{3}$ answers it.

In [ ]:
def ridge(Phi, y, lam):
    d = Phi.shape[1]
    return np.linalg.inv(Phi.T @ Phi + lam*np.eye(d)) @ Phi.T @ y

lam_list = np.logspace(-4, 3, 50)
path = np.zeros((50, 8))
for i in range(50):
    path[i, :] = ridge(Phi, y, lam_list[i])

plt.figure(figsize = (6, 4))
for k in range(8):
    plt.semilogx(lam_list, path[:, k], label = names[k])
plt.xlabel(r'$\lambda$')
plt.ylabel('coefficient')
plt.legend(ncol = 2, fontsize = 8)
plt.grid(True)
plt.show()

print('ridge, lambda = 1')
print_coef(ridge(Phi, y, 1.0), names)
No description has been provided for this image
ridge, lambda = 1
       1 :    -0.017
       x :     0.815
     x^2 :     0.077
     x^3 :    -0.501
     x^4 :    -0.010
     x^5 :    -0.026
  sin 2x :     0.383
  cos 2x :     0.051

At small $\lambda$ the penalty hardly matters and the coefficients are those of least squares. As $\lambda$ grows, every coefficient moves towards zero, but none of them ever gets there. At $\lambda = 1$ the coefficient of $x$ has fallen from $1.48$ to $0.81$ and that of $x^3$ from $-0.81$ to $-0.50$. Meanwhile the coefficient of $\sin 2x$, a term the law does not contain, has risen to $0.38$. The reason is the form of the penalty: $\lambda\lVert\theta\rVert_2^2$ charges a large coefficient far more than a small one, since the cost grows with the square. Two large coefficients on $x$ and $x^3$ are therefore expensive, and the penalty finds it cheaper to describe the same odd-shaped curve with several medium coefficients spread over $x$, $x^3$ and $\sin 2x$, which are correlated and can stand in for one another. Ridge regression spreads weight across correlated columns instead of concentrating it on the right ones, which is the opposite of what discovery needs, and at no value of $\lambda$ does any coefficient become exactly zero. The $L_2$ penalty shrinks; it does not select.


3.2. The Geometry of the Two Norms

The reason is geometric, and it is easiest to see with two coefficients. Minimizing the data error subject to a bound on the size of $\theta$,


$$ \begin{aligned} \min_{\theta} \quad & \lVert\Phi\theta - y\rVert_2^2 \\ \text{subject to} \quad & \lVert\theta\rVert \le t , \end{aligned} $$


is the same problem as the penalized one, with $t$ and $\lambda$ in one-to-one correspondence. Picture the $(\theta_1, \theta_2)$ plane. Every point in it is a candidate pair of coefficients, and the data error $\lVert\Phi\theta - y\rVert_2^2$ assigns a number to every point. The error is smallest at the least-squares solution and grows as $\theta$ moves away from it, and the points of equal error form ellipses around that solution, like the contour lines of a bowl-shaped valley. The constraint $\lVert\theta\rVert \le t$ allows only the points inside a ball of radius $t$ about the origin, and the constrained solution is the point of that ball with the smallest error, which is where the smallest ellipse first touches the ball. For the $L_2$ norm the ball is a disc; for the $L_1$ norm, $\lvert\theta_1\rvert + \lvert\theta_2\rvert \le t$, it is a diamond with its corners on the axes.


The example has two correlated columns $b_1$ and $b_2$ and a law that uses only the first, $y = 1.0\,b_1 + 0\,b_2 + \text{noise}$, so that the least-squares solution lands near $(1, 0)$ but not on the axis. The constrained solutions are found by searching the boundary of each ball for the smallest error.

In [ ]:
# two correlated columns, so that the least-squares contours are tilted ellipses
np.random.seed(1)
b1 = np.random.randn(50)
b2 = 0.8*b1 + 0.6*np.random.randn(50)
Phi2 = np.hstack([b1.reshape(-1, 1), b2.reshape(-1, 1)])
y2 = 1.0*b1 + 0.0*b2 + 0.5*np.random.randn(50)

theta_ls = np.linalg.inv(Phi2.T @ Phi2) @ Phi2.T @ y2

g1, g2 = np.meshgrid(np.linspace(-0.5, 1.6, 300), np.linspace(-1.0, 1.1, 300))
J = np.zeros_like(g1)
for i in range(300):
    for j in range(300):
        J[i, j] = np.sum((Phi2 @ np.array([g1[i, j], g2[i, j]]) - y2)**2)

t = 0.7                                             # size of the constraint region
angle = np.linspace(0, 2*np.pi, 400)

# L2 ball: the point on the circle with the smallest J
circle = np.vstack([t*np.cos(angle), t*np.sin(angle)])
J_circle = np.sum((Phi2 @ circle - y2.reshape(-1, 1))**2, axis = 0)
theta_l2 = circle[:, np.argmin(J_circle)]

# L1 ball: the point on the diamond with the smallest J
u = np.linspace(-t, t, 400)
diamond = np.hstack([np.vstack([u, t - np.abs(u)]), np.vstack([u, -(t - np.abs(u))])])
J_diamond = np.sum((Phi2 @ diamond - y2.reshape(-1, 1))**2, axis = 0)
theta_l1 = diamond[:, np.argmin(J_diamond)]

plt.figure(figsize = (9, 4))
plt.subplot(1, 2, 1)
plt.contour(g1, g2, J, levels = 20, colors = 'gray', linewidths = 0.8)
plt.plot(circle[0, :], circle[1, :], 'b', linewidth = 2)
plt.plot(theta_ls[0], theta_ls[1], 'ko', label = 'least squares')
plt.plot(theta_l2[0], theta_l2[1], 'bs', markersize = 8, label = r'$L_2$ constrained')
plt.axhline(0, color = 'k', linewidth = 0.5)
plt.axvline(0, color = 'k', linewidth = 0.5)
plt.title(r'$L_2$ ball: $\theta_1^2 + \theta_2^2 \leq t^2$')
plt.xlabel(r'$\theta_1$')
plt.ylabel(r'$\theta_2$')
plt.axis('equal')
plt.legend()

plt.subplot(1, 2, 2)
plt.contour(g1, g2, J, levels = 20, colors = 'gray', linewidths = 0.8)
plt.plot(diamond[0, :200], diamond[1, :200], 'r', linewidth = 2)
plt.plot(diamond[0, 200:], diamond[1, 200:], 'r', linewidth = 2)
plt.plot(theta_ls[0], theta_ls[1], 'ko', label = 'least squares')
plt.plot(theta_l1[0], theta_l1[1], 'rs', markersize = 8, label = r'$L_1$ constrained')
plt.axhline(0, color = 'k', linewidth = 0.5)
plt.axvline(0, color = 'k', linewidth = 0.5)
plt.title(r'$L_1$ ball: $|\theta_1| + |\theta_2| \leq t$')
plt.xlabel(r'$\theta_1$')
plt.axis('equal')
plt.legend()
plt.show()

print('least squares   : theta = (%.3f, %.3f)' % (theta_ls[0], theta_ls[1]))
print('L2 constrained  : theta = (%.3f, %.3f)' % (theta_l2[0], theta_l2[1]))
print('L1 constrained  : theta = (%.3f, %.3f)' % (theta_l1[0], theta_l1[1]))
No description has been provided for this image
least squares   : theta = (1.033, -0.023)
L2 constrained  : theta = (0.655, 0.248)
L1 constrained  : theta = (0.700, 0.000)

The two pictures differ in one thing only, the shape of the constraint set, and that one thing decides whether a coefficient is zero. The ellipses meet the disc at a point of tangency on its smooth boundary, which has no reason to lie on an axis: the $L_2$ solution is $(0.655, 0.248)$, both coefficients nonzero, the second one spurious. The ellipses meet the diamond at its corner, because a corner sticks out further towards the ellipse centre than the flat sides beside it do: the $L_1$ solution is $(0.700, 0.000)$, the second coefficient exactly zero. In higher dimensions the $L_1$ ball has corners on every axis and edges on every coordinate plane, and a level set that touches it will usually do so on one of these, which is a point with many zero coordinates. The $L_2$ ball has no corners anywhere.


3.3. LASSO with CVXPY

With many columns the LASSO objective


$$ J_1(\theta) = \lVert\Phi\theta - y\rVert_2^2 + \lambda\lVert\theta\rVert_1 , \qquad \lVert\theta\rVert_1 = \sum_j\lvert\theta_j\rvert , $$


has no closed form, because the $L_1$ norm is not differentiable wherever a coefficient is zero, which is exactly the place the solution wants to be. It is, however, convex, and Machine Learning solved it with CVXPY: the objective is written down as cvx.sum_squares(Phi @ theta - y) + lam*cvx.norm(theta, 1) and the solver takes care of the kinks. The same two lines serve here.


One detail matters in practice. The penalty charges every coefficient the same $\lambda$, but a coefficient on $x^5$, whose column has values up to $243$, means something very different from a coefficient on $\sin 2x$, whose column stays within $\pm 1$. The function therefore scales every column to unit root-mean-square before solving and maps the coefficients back afterwards, so that $\lambda$ has the same meaning for every column.

In [ ]:
def lasso(Phi, y, lam):
    col_scale = np.sqrt(np.mean(Phi**2, axis = 0))   # root-mean-square of every column
    Phi = Phi/col_scale                               # scaled columns, so that lambda means the same for each

    theta = cvx.Variable(Phi.shape[1])
    obj = cvx.Minimize(cvx.sum_squares(Phi @ theta - y) + lam*cvx.norm(theta, 1))
    cvx.Problem(obj).solve()

    return theta.value/col_scale                      # back to the original columns

theta_lasso = lasso(Phi, y, lam = 10.0)
print('lasso, lambda = 10')
print_coef(theta_lasso, names)
print('training error : %.3f' % np.mean((Phi @ theta_lasso - y)**2))
lasso, lambda = 10
       1 :     -
       x :     -
     x^2 :     -
     x^3 :    -0.136
     x^4 :     -
     x^5 :    -0.056
  sin 2x :     0.877
  cos 2x :     -
training error : 0.072

At $\lambda = 10$ the LASSO keeps three columns and sets five exactly to zero, which the ridge penalty never did. But the three it keeps are $x^3$, $x^5$ and $\sin 2x$, not $x$ and $x^3$, and the coefficient on $x^3$ is $-0.14$ rather than $-0.8$. The training error, $0.072$, is twice that of least squares. The LASSO has found a sparse model, and it is the wrong one. The path of the coefficients as $\lambda$ varies shows what has happened.

In [ ]:
lam_list = np.logspace(-1, 3, 40)
path = np.zeros((40, 8))
for i in range(40):
    path[i, :] = lasso(Phi, y, lam_list[i])

plt.figure(figsize = (6, 4))
for k in range(8):
    plt.semilogx(lam_list, path[:, k], label = names[k])
plt.xlabel(r'$\lambda$')
plt.ylabel('coefficient')
plt.legend(ncol = 2, fontsize = 8)
plt.grid(True)
plt.show()

n_terms = np.sum(np.abs(path) > 1e-10, axis = 1)
for i in range(0, 40, 4):
    terms = ', '.join([names[k] for k in range(8) if abs(path[i, k]) > 1e-10])
    print('lambda = %8.3f | %d terms : %s' % (lam_list[i], n_terms[i], terms))
No description has been provided for this image
lambda =    0.100 | 7 terms : 1, x, x^2, x^3, x^4, x^5, sin 2x
lambda =    0.257 | 8 terms : 1, x, x^2, x^3, x^4, x^5, sin 2x, cos 2x
lambda =    0.661 | 6 terms : 1, x, x^3, x^5, sin 2x, cos 2x
lambda =    1.701 | 6 terms : 1, x^2, x^3, x^5, sin 2x, cos 2x
lambda =    4.375 | 5 terms : 1, x^3, x^5, sin 2x, cos 2x
lambda =   11.253 | 3 terms : x^3, x^5, sin 2x
lambda =   28.943 | 3 terms : x^3, x^5, sin 2x
lambda =   74.438 | 3 terms : x^3, x^5, sin 2x
lambda =  191.448 | 3 terms : x^3, x^5, sin 2x
lambda =  492.388 | 2 terms : x^3, x^5

At the smallest $\lambda$ seven of the eight terms are present. As $\lambda$ increases, the first columns to go are $x^4$ and $x^2$, then $\cos 2x$ and the constant; so far so good. But between $\lambda = 1$ and $\lambda = 2$ the coefficient of $x$ collapses to zero while that of $\sin 2x$ rises to $0.9$, and from there up to $\lambda \approx 200$ the selected set is $\{x^3, x^5, \sin 2x\}$. At $\lambda = 10$ the fit is


$$ \hat{y} = -0.136\,x^3 - 0.056\,x^5 + 0.877\,\sin 2x , $$


against the law $y = 1.5x - 0.8x^3$. The LASSO has traded the true term $x$ for the pair $x^5$ and $\sin 2x$. The reason is the penalty itself. The penalty is charged on the scaled columns, so each coefficient counts with its column's root-mean-square, $1.74$ for $x$, $10.45$ for $x^3$, $75.42$ for $x^5$ and $0.75$ for $\sin 2x$. The true law and the LASSO's alternative then cost


$$ \lVert\theta\rVert_1 = 1.5\times1.74 + 0.8\times10.45 \approx 11.0 , \qquad \lVert\theta\rVert_1 = 0.136\times10.45 + 0.056\times75.42 + 0.877\times0.75 \approx 6.3 , $$


and the alternative fits the data almost as well, because $x^5$ has such a large column norm that a tiny coefficient on it goes a long way. The $L_1$ penalty prefers the cheaper representation, and with correlated columns the cheaper representation need not be the true one. The penalty that produces the zeros also distorts the choice of which coefficients are zero.




4. Sequential Thresholded Least Squares

4.1. The Algorithm

There is a cruder way to obtain zeros, and for discovery it works better. Fit by least squares; set every coefficient smaller than a threshold to zero; refit the surviving columns by least squares; repeat until the set of survivors stops changing. This is sequential thresholded least squares (STLS), and the whole algorithm is a loop of a few lines,


$$ \begin{aligned} &\theta \leftarrow (\Phi^T\Phi)^{-1}\Phi^T y \\ &\text{repeat:} \quad \theta_j \leftarrow 0 \ \text{ if } \lvert\theta_j\rvert < \tau , \qquad \theta_{\mathrm{big}} \leftarrow (\Phi_{\mathrm{big}}^T\Phi_{\mathrm{big}})^{-1}\Phi_{\mathrm{big}}^T y , \end{aligned} $$


where $\Phi_{\mathrm{big}}$ holds the columns whose coefficients survived. The threshold $\tau$ plays the role of $\lambda$: it is the smallest coefficient the model is allowed to contain. There is no penalty term and no shrinkage; the surviving coefficients are plain least-squares coefficients on the surviving columns. Since every coefficient is compared with the same $\tau$, the columns must be on comparable scales; where they are not, they are scaled to unit root-mean-square as in the LASSO and the coefficients are mapped back afterwards. The library here is built on $O(1)$ inputs and needs no scaling.

In [ ]:
def stls(Phi, y, threshold, n_iter = 10):
    theta = np.linalg.inv(Phi.T @ Phi) @ Phi.T @ y
    for it in range(n_iter):
        small = np.abs(theta) < threshold                   # coefficients to drop
        big = ~small                                        # columns to keep
        theta[small] = 0
        Phi_big = Phi[:, big]
        theta[big] = np.linalg.inv(Phi_big.T @ Phi_big) @ Phi_big.T @ y    # refit the survivors
    return theta

theta_stls = stls(Phi, y, threshold = 0.1)
print('sequential thresholded least squares, threshold = 0.1')
print_coef(theta_stls, names)
sequential thresholded least squares, threshold = 0.1
       1 :     -
       x :     1.453
     x^2 :     -
     x^3 :    -0.796
     x^4 :     -
     x^5 :     -
  sin 2x :     -
  cos 2x :     -

With $\tau = 0.1$ the algorithm returns $\hat y= 1.45\,x - 0.80\,x^3$ and nothing else: the right two terms, with coefficients within $3\%$ and $1\%$ of the truth. Printing the surviving set after each pass shows how quickly the loop settles.

In [ ]:
theta = np.linalg.inv(Phi.T @ Phi) @ Phi.T @ y
print('iteration 0 : %d terms' % np.sum(np.abs(theta) > 1e-10))

for it in range(1, 6):
    small = np.abs(theta) < 0.1
    big = ~small
    theta[small] = 0
    Phi_big = Phi[:, big]
    theta[big] = np.linalg.inv(Phi_big.T @ Phi_big) @ Phi_big.T @ y
    print('iteration %d : %d terms  ->  %s' % (it, np.sum(big), ', '.join([names[k] for k in range(8) if big[k]])))
iteration 0 : 8 terms
iteration 1 : 2 terms  ->  x, x^3
iteration 2 : 2 terms  ->  x, x^3
iteration 3 : 2 terms  ->  x, x^3
iteration 4 : 2 terms  ->  x, x^3
iteration 5 : 2 terms  ->  x, x^3

One pass was enough. The least-squares fit had six coefficients below $0.1$ in magnitude, all of them spurious, and they were removed together; the refit on $x$ and $x^3$ produced two coefficients well above the threshold, and nothing changed after that. In harder cases, with more noise or a larger library, the first refit moves weight around and a second or third pass removes more, which is why the loop is there; but the number of passes needed is small, because every pass can only shrink the set.


4.2. LASSO and STLS Compared

The two methods are compared at the same sparsity. For the LASSO, $\lambda = 300$ is large enough to leave two terms.

In [ ]:
theta_lasso = lasso(Phi, y, lam = 300.0)            # a lambda large enough to leave two terms

print('            true     lasso      STLS')
for k in range(8):
    true_k = 1.5 if k == 1 else (-0.8 if k == 3 else 0.0)
    print('%7s : %8.3f  %8.3f  %8.3f' % (names[k], true_k, theta_lasso[k], theta_stls[k]))
print('\ntraining error : lasso %.3f | STLS %.3f' % (np.mean((Phi @ theta_lasso - y)**2), np.mean((Phi @ theta_stls - y)**2)))
            true     lasso      STLS
      1 :    0.000     0.000     0.000
      x :    1.500    -0.000     1.453
    x^2 :    0.000     0.000     0.000
    x^3 :   -0.800    -0.153    -0.796
    x^4 :    0.000     0.000     0.000
    x^5 :    0.000    -0.039     0.000
 sin 2x :    0.000     0.000     0.000
 cos 2x :    0.000    -0.000     0.000

training error : lasso 2.657 | STLS 0.039

The LASSO's two terms are $x^3$ and $x^5$, the wrong pair, with the coefficient of $x^3$ at $-0.15$ instead of $-0.8$ and a training error $70$ times larger than the STLS fit. STLS has the right pair with coefficients $1.45$ and $-0.80$. The comparison separates the two things that a sparse method has to do, select and estimate, and shows the LASSO weak at both for this library. In estimation it is biased: the penalty keeps pulling every surviving coefficient towards zero, and at the $\lambda$ needed to remove six columns the pull is a large fraction of the true values. In selection it is swayed by column norms, as Section 3.3 showed. STLS has neither problem, because its surviving coefficients are refitted without any penalty, and because its criterion for dropping a column is the column's own coefficient rather than a trade-off against the others.


This is why STLS, not the LASSO, is the standard engine of equation discovery, and the one the next notebook uses throughout. The LASSO remains the right tool when the goal is prediction rather than identification, when the columns are nearly uncorrelated, or when $d$ exceeds $m$ so that least squares has no unique solution and the refit of STLS cannot be done.

Remark (what STLS optimizes). The LASSO minimizes a convex function and its answer is unique. STLS is a heuristic for the non-convex problem of minimizing the data error plus a penalty on the number of nonzero coefficients, the so-called $L_0$ problem, whose exact solution would require trying every subset of columns. It can in principle stop at a wrong subset, and the threshold sweep of Section 4.3 is the safeguard.


4.3. Choosing the Threshold

The threshold was set to $0.1$ above because the answer was known. Without that knowledge the threshold has to be chosen from the data, and the simplest way is to sweep it and watch two quantities: how many terms survive, and how well they fit.

In [ ]:
thresholds = np.logspace(-3, 1, 60)
n_terms = np.zeros(60)
train_err = np.zeros(60)

for i in range(60):
    theta = stls(Phi, y, thresholds[i])
    n_terms[i] = np.sum(np.abs(theta) > 1e-10)
    train_err[i] = np.mean((Phi @ theta - y)**2)

plt.figure(figsize = (9, 3))
plt.subplot(1, 2, 1)
plt.semilogx(thresholds, n_terms, 'k.-')
plt.xlabel('threshold')
plt.ylabel('number of terms')
plt.grid(True)

plt.subplot(1, 2, 2)
plt.loglog(thresholds, train_err, 'k.-')
plt.xlabel('threshold')
plt.ylabel('training error')
plt.grid(True)
plt.show()
No description has been provided for this image

Both curves are staircases, because a model changes only when a term crosses the threshold. Reading from the left: below $\tau \approx 0.005$ seven terms survive, between $0.005$ and $0.02$ the count drops to five and then three, and from $\tau \approx 0.02$ to $0.7$, nearly two decades of threshold, the model is the same two-term one with training error $0.039$. At $\tau \approx 0.8$ the term $x^3$ is lost and the error jumps by a factor of $270$; above $1.5$ nothing survives. The long flat step is the signature of a correct model: it is the model the data return for any reasonable threshold, and the threshold value inside the step does not matter. The sweep is therefore the standard way to choose $\tau$, and when no flat step appears, the data do not determine a sparse model, a situation Section 5.3 returns to.




5. Pitfalls

5.1. A Term Missing from the Library

Sparse regression can only choose among the candidates it is given. If the true law contains a function that is not in the library, the method does not report failure; it returns the best sparse combination of the wrong functions, and the result can look convincing. The data below follow $y = 1.5x - 2e^{-x^2}$, and the library of Section 2.1 has no Gaussian in it.

In [ ]:
np.random.seed(2)
y2 = 1.5*x - 2*np.exp(-x**2) + 0.1*np.random.randn(m)

theta_miss = stls(Phi, y2, threshold = 0.05)        # exp(-x^2) is not in the library
print('library without exp(-x^2)')
print_coef(theta_miss, names)
print('training error : %.4f' % np.mean((Phi @ theta_miss - y2)**2))

Phi_full = np.hstack([Phi, np.exp(-x**2).reshape(-1, 1)])
theta_full = stls(Phi_full, y2, threshold = 0.05)
print('\nlibrary with exp(-x^2) added')
print_coef(theta_full, names + ['exp(-x^2)'])
print('training error : %.4f' % np.mean((Phi_full @ theta_full - y2)**2))
library without exp(-x^2)
       1 :    -1.293
       x :     1.505
     x^2 :     0.223
     x^3 :     -
     x^4 :     -
     x^5 :     -
  sin 2x :     -
  cos 2x :    -0.617
training error : 0.0134

library with exp(-x^2) added
       1 :     -
       x :     1.506
     x^2 :     -
     x^3 :     -
     x^4 :     -
     x^5 :     -
  sin 2x :     -
  cos 2x :     -
exp(-x^2) :    -2.007
training error : 0.0107

Without $e^{-x^2}$ the algorithm returns a four-term model, $-1.29 + 1.50x + 0.22x^2 - 0.62\cos 2x$, with a training error of $0.013$, which is close to the noise variance $0.01$. By the loss there is nothing wrong with it. By physics there is: the constant, the $x^2$ and the $\cos 2x$ are a committee impersonating a bump, and none of them is in the law. With the Gaussian added to the library the same threshold returns $1.51x - 2.01e^{-x^2}$, the law itself, with error $0.011$. The two fits are compared beyond the data below.

In [ ]:
Phi_p = library(xp)
Phi_p_full = np.hstack([Phi_p, np.exp(-xp**2).reshape(-1, 1)])

plt.figure(figsize = (6, 4))
plt.plot(xp, 1.5*xp - 2*np.exp(-xp**2), 'k', linewidth = 3, alpha = 0.3, label = 'True law')
plt.plot(x, y2, 'bo', markersize = 4, label = 'Data')
plt.plot(xp, Phi_p @ theta_miss, 'r--', linewidth = 1.5, label = 'Library without exp(-x^2)')
plt.plot(xp, Phi_p_full @ theta_full, 'g--', linewidth = 1.5, label = 'Library with exp(-x^2)')
plt.xlabel('x')
plt.ylabel('y')
plt.xlim([-4, 4])
plt.ylim([-8, 8])
plt.legend()
plt.grid(True)
plt.show()
No description has been provided for this image

Inside $[-3, 3]$ the two models are on top of each other and on top of the data. Outside, the four-term model turns upward at the left and downward at the right, following its $x^2$ and $\cos 2x$ terms into territory the data never covered, while the two-term model follows the law. Two lessons follow. A small residual does not certify the terms; the four-term model's residual is small because the library was rich enough to imitate the missing function, not because it contained it. And extrapolation is a test: a discovered law that is right should keep working outside the data, and one that is wrong usually does not. The remedy is the obvious one, a richer library, with the cost that more candidates means more correlation among them, which is the next pitfall.


5.2. Candidates That Look Alike

Two candidate functions that are nearly proportional on the range of the data cannot be told apart by any method, because the data contain no information about the difference between them. On a narrow range around zero, $x$, $\sin x$ and $\tanh x$ are all approximately $x$. The data below follow $y = 2\sin x$ on $[-0.5, 0.5]$ with noise of $0.01$, and the library has all three.

In [ ]:
np.random.seed(3)
x_small = np.sort(np.random.uniform(-0.5, 0.5, 60))       # a narrow range: sin x and x are nearly the same column
y3 = 2.0*np.sin(x_small) + 0.01*np.random.randn(60)

Phi3 = np.hstack([x_small.reshape(-1, 1), np.sin(x_small).reshape(-1, 1), np.tanh(x_small).reshape(-1, 1)])
C3 = np.corrcoef(Phi3.T)
print('correlation x / sin x : %.6f,  x / tanh x : %.6f' % (C3[0, 1], C3[0, 2]))

for trial in range(5):
    y3 = 2.0*np.sin(x_small) + 0.01*np.random.randn(60)
    theta3 = stls(Phi3, y3, threshold = 0.5)
    print('trial %d : x %8.3f | sin x %8.3f | tanh x %8.3f' % (trial + 1, theta3[0], theta3[1], theta3[2]))
correlation x / sin x : 0.999934,  x / tanh x : 0.999769
trial 1 : x   -1.646 | sin x    5.347 | tanh x   -1.699
trial 2 : x   10.426 | sin x  -20.607 | tanh x   12.197
trial 3 : x  -18.577 | sin x   42.406 | tanh x  -21.857
trial 4 : x   21.694 | sin x  -45.167 | tanh x   25.499
trial 5 : x   12.677 | sin x  -25.633 | tanh x   14.977

The correlations between the columns are $0.9999$ and higher. Five repetitions of the experiment with fresh noise give five different answers, with coefficients of $5$, $-20$, $42$, $-45$ and $-25$ on $\sin x$, all with the wrong terms kept and the coefficients cancelling one another to reproduce a function that is simply $2\sin x$. The threshold of $0.5$ does not help, because the spurious coefficients are not small; they are huge and opposite. This is the condition number of Section 2.3 in its extreme form. Widening the range changes everything.

In [ ]:
x_wide = np.sort(np.random.uniform(-3, 3, 60))
Phi3w = np.hstack([x_wide.reshape(-1, 1), np.sin(x_wide).reshape(-1, 1), np.tanh(x_wide).reshape(-1, 1)])
C3w = np.corrcoef(Phi3w.T)
print('correlation x / sin x : %.4f,  x / tanh x : %.4f' % (C3w[0, 1], C3w[0, 2]))

for trial in range(5):
    y3 = 2.0*np.sin(x_wide) + 0.01*np.random.randn(60)
    theta3 = stls(Phi3w, y3, threshold = 0.5)
    print('trial %d : x %8.3f | sin x %8.3f | tanh x %8.3f' % (trial + 1, theta3[0], theta3[1], theta3[2]))
correlation x / sin x : 0.7983,  x / tanh x : 0.9628
trial 1 : x    0.000 | sin x    2.001 | tanh x    0.000
trial 2 : x    0.000 | sin x    1.997 | tanh x    0.000
trial 3 : x    0.000 | sin x    2.000 | tanh x    0.000
trial 4 : x    0.000 | sin x    2.000 | tanh x    0.000
trial 5 : x    0.000 | sin x    1.999 | tanh x    0.000

On $[-3, 3]$ the correlation of $x$ with $\sin x$ falls to $0.80$, because $\sin x$ turns over where $x$ keeps going, and all five trials return $2.00\sin x$ alone. The difference is not in the method but in the data: the experiment on the wide range exercised the part of the domain where the candidates disagree. Before trusting a discovered law, it is worth asking whether the measurements covered a range on which the surviving terms could have been distinguished from the ones that were dropped, and, when two candidates are nearly collinear on the available data, admitting that the data do not decide between them rather than reporting whichever one the noise favoured.


5.3. Noise

Noise raises the spurious coefficients, and at some level they cross the threshold. The running example is repeated with noise from $0.05$ to $2.0$, against a signal whose range is about $\pm 17$.

In [ ]:
np.random.seed(4)
noise_list = [0.05, 0.2, 0.5, 1.0, 2.0]

print('noise  | recovered terms (threshold 0.1)             | x coef   | x^3 coef')
for sig in noise_list:
    y_n = 1.5*x - 0.8*x**3 + sig*np.random.randn(m)
    theta_n = stls(Phi, y_n, threshold = 0.1)
    terms = ', '.join([names[k] for k in range(8) if abs(theta_n[k]) > 1e-10])
    print('%5.2f  | %-44s | %8.3f | %8.3f' % (sig, terms, theta_n[1], theta_n[3]))
noise  | recovered terms (threshold 0.1)             | x coef   | x^3 coef
 0.05  | x, x^3                                       |    1.498 |   -0.800
 0.20  | x, x^3                                       |    1.516 |   -0.805
 0.50  | x, x^3                                       |    1.453 |   -0.787
 1.00  | x, x^3, cos 2x                               |    1.410 |   -0.808
 2.00  | x, sin 2x, cos 2x                            |   -2.543 |    0.000

Up to noise $0.5$ the two-term law is recovered with coefficients within a few percent. At noise $1.0$ a spurious $\cos 2x$ appears alongside the correct pair. At noise $2.0$, about $12\%$ of the signal range, the method returns $x$, $\sin 2x$ and $\cos 2x$ with the coefficient of $x$ at $-2.5$: the wrong model with the wrong sign on the one term it got right. The threshold was fixed at $0.1$ throughout. Sweeping it at each noise level, as in Section 4.3, and reading off the longest flat step shows how much room there is to choose it.

In [ ]:
np.random.seed(4)
print('noise  | longest flat step               | model on that step | training error')
for sig in noise_list:
    y_n = 1.5*x - 0.8*x**3 + sig*np.random.randn(m)
    thetas = [stls(Phi, y_n, t) for t in thresholds]
    models = [tuple(np.abs(theta) > 1e-10) for theta in thetas]                # surviving terms at every threshold

    length, first, last = 0, 0, 0                   # the longest run of one model, other than all terms or none
    i = 0
    for j in range(1, 61):
        if j == 60 or models[j] != models[i]:
            if any(models[i]) and not all(models[i]) and j - i > length:
                length, first, last = j - i, i, j - 1
            i = j

    terms = ', '.join([names[k] for k in range(8) if models[first][k]])
    error = np.mean((Phi @ thetas[first] - y_n)**2)
    print('%5.2f  | %.3f to %.3f (%2d of 60 steps) | %-18s | %.3f (noise variance %.3f)' % (sig, thresholds[first], thresholds[last], length, terms, error, sig**2))
noise  | longest flat step               | model on that step | training error
 0.05  | 0.010 to 0.704 (28 of 60 steps) | x, x^3             | 0.002 (noise variance 0.003)
 0.20  | 0.027 to 0.704 (22 of 60 steps) | x, x^3             | 0.034 (noise variance 0.040)
 0.50  | 0.036 to 0.377 (16 of 60 steps) | x, x^3             | 0.286 (noise variance 0.250)
 1.00  | 0.148 to 0.704 (11 of 60 steps) | x, x^3             | 0.865 (noise variance 1.000)
 2.00  | 0.322 to 1.124 ( 9 of 60 steps) | sin 2x             | 27.723 (noise variance 4.000)

The sweep is read as in Section 4.3, except that the trivial models, all eight terms at the smallest thresholds and none at the largest, are left out. At every noise level up to $1.0$ the longest flat step belongs to the two-term law, with a training error at the noise variance, as a correct model's should be. But the step shortens as the noise grows: it spans $\tau$ from $0.01$ to $0.7$ at noise $0.05$ and only from $0.15$ to $0.7$ at noise $1.0$, where the fixed threshold $0.1$ fell just outside it and admitted the spurious $\cos 2x$. A threshold read from the step recovers the law at all four levels. At noise $2.0$ the two-term law has no flat step at all. The longest step that remains is nine thresholds wide and belongs to the single term $\sin 2x$, with a training error seven times the noise variance: a model that is sparse but not accurate. There is a noise level beyond which the data do not contain the law, and no choice of threshold recovers it; what the sweep offers is a way to see that this level has been reached, since no step then gives a model that is both sparse and accurate. The next notebook meets this problem in a sharper form, because there the data have to be differentiated before they can be used, and differentiation amplifies noise.




6. Lab: The Period of a Pendulum

6.1. Measurements

The laboratory discovers a law that Galileo found by eye and Huygens by calculation: the period of a pendulum. Eighty pendulums are built with lengths $L$ between $0.2$ and $2\,\mathrm{m}$, bob masses $m$ between $0.05$ and $1\,\mathrm{kg}$, and release angles $\theta_0$ between $0.05$ and $1.2\,\mathrm{rad}$, and the period $T$ of each is timed with $1\%$ error. The measurements are simulated from the exact period, which involves the complete elliptic integral $K$,


$$ T = 4\sqrt{\frac{L}{g}}\;K\!\left(\sin^2\frac{\theta_0}{2}\right) , $$


but this formula is used only to generate the data. The discovery proceeds as if it were unknown.

In [ ]:
from scipy.special import ellipk

np.random.seed(5)
g = 9.81

n_exp = 80
L = np.random.uniform(0.2, 2.0, n_exp)                    # length (m)
m = np.random.uniform(0.05, 1.0, n_exp)                   # bob mass (kg)
theta0 = np.random.uniform(0.05, 1.2, n_exp)              # release angle (rad)

T_exact = 4*np.sqrt(L/g)*ellipk(np.sin(theta0/2)**2)      # exact period of a pendulum
T_meas = T_exact*(1 + 0.01*np.random.randn(n_exp))        # 1 % measurement noise

plt.figure(figsize = (10, 3.5))
plt.subplot(1, 3, 1)
plt.plot(L, T_meas, 'ko', markersize = 4)
plt.xlabel('L (m)')
plt.ylabel('T (s)')
plt.grid(True)
plt.subplot(1, 3, 2)
plt.plot(m, T_meas, 'ko', markersize = 4)
plt.xlabel('m (kg)')
plt.grid(True)
plt.subplot(1, 3, 3)
plt.plot(theta0, T_meas, 'ko', markersize = 4)
plt.xlabel(r'$\theta_0$ (rad)')
plt.grid(True)
plt.show()
No description has been provided for this image

Against $L$ the period rises along a clear curve. Against $m$ it is a cloud with no trend, and against $\theta_0$ a cloud with perhaps a slight upward drift. A good experimenter would already guess that $m$ does not matter, and the question is whether sparse regression reaches the same conclusion and quantifies the rest.


6.2. A Power Law by Sparse Regression

A product of powers, $T = C\,L^p m^q\theta_0^r$, becomes linear in logarithms,


$$ \log T = \log C + p\log L + q\log m + r\log\theta_0 , $$


which is a library of four columns, the constant and the three logarithms, with the exponents as coefficients. A zero exponent means the variable does not enter, so sparsity in this library is the statement "this variable is irrelevant", and the threshold is a bound on how small an exponent is taken seriously.

In [ ]:
# power law T = C L^p m^q theta0^r  ->  log T = log C + p log L + q log m + r log theta0
A = np.hstack([np.ones((n_exp, 1)), np.log(L).reshape(-1, 1), np.log(m).reshape(-1, 1), np.log(theta0).reshape(-1, 1)])
names_pow = ['log C', 'p (L)', 'q (m)', 'r (theta0)']

print('least squares')
print_coef(np.linalg.lstsq(A, np.log(T_meas), rcond = None)[0], names_pow)

theta_pow = stls(A, np.log(T_meas), threshold = 0.1)
print('\nSTLS, threshold 0.1')
print_coef(theta_pow, names_pow)
print('\nC = exp(log C) = %.4f,   2 pi / sqrt(g) = %.4f' % (np.exp(theta_pow[0]), 2*np.pi/np.sqrt(g)))
least squares
   log C :     0.747
   p (L) :     0.502
   q (m) :    -0.001
r (theta0) :     0.033

STLS, threshold 0.1
   log C :     0.727
   p (L) :     0.504
   q (m) :     -
r (theta0) :     -

C = exp(log C) = 2.0695,   2 pi / sqrt(g) = 2.0061

Least squares gives $p = 0.502$, $q = -0.0007$ and $r = 0.033$: the length enters with the square root, the mass with an exponent indistinguishable from zero, and the angle with a small positive exponent. STLS with threshold $0.1$ removes both $q$ and $r$ and refits: $T = 2.07\,L^{0.504}$. The constant is $3\%$ above $2\pi/\sqrt{g} = 2.006$, which is the value in the small-angle formula $T = 2\pi\sqrt{L/g}$. The excess is not noise. It is the amplitude effect that the power law cannot represent, because the period's dependence on $\theta_0$ is not a power: it is flat near $\theta_0 = 0$ and rises slowly, and a term $\theta_0^r$ with any $r > 0$ vanishes at zero instead. The power-law library did what it could, assigned the effect to the constant, and dropped $\theta_0$. This is Section 5.1 in a mild form, and the right response is a library built for the effect.


6.3. The Amplitude Correction

With the small-angle period $T_0 = 2\pi\sqrt{L/g}$ taken as known from the previous step, the remaining dependence is the ratio $T/T_0$ as a function of $\theta_0$ alone.

In [ ]:
T0 = 2*np.pi*np.sqrt(L/g)                                 # small-angle period
ratio = T_meas/T0

plt.figure(figsize = (6, 4))
plt.plot(theta0, ratio, 'ko', markersize = 4)
plt.xlabel(r'$\theta_0$ (rad)')
plt.ylabel(r'$T / T_0$')
plt.grid(True)
plt.show()
No description has been provided for this image

The ratio starts at $1$ and rises to about $1.1$ at $\theta_0 = 1.2$, with a curvature that suggests an even function of $\theta_0$, as it must be, since the pendulum does not care which way it is released. The library is the powers of $\theta_0$ up to the fourth. Their columns differ in size, so they are scaled to unit root-mean-square before thresholding, as Section 4.1 prescribed, and the threshold is $0.01$ because the whole effect is of order $0.1$.

In [ ]:
Phi_c = np.hstack([np.ones((n_exp, 1)), theta0.reshape(-1, 1), (theta0**2).reshape(-1, 1), (theta0**3).reshape(-1, 1), (theta0**4).reshape(-1, 1)])
names_c = ['1', 'th', 'th^2', 'th^3', 'th^4']

print('least squares')
print_coef(np.linalg.lstsq(Phi_c, ratio, rcond = None)[0], names_c)

col_scale = np.sqrt(np.mean(Phi_c**2, axis = 0))
theta_c = stls(Phi_c/col_scale, ratio, threshold = 0.01)/col_scale

print('\nSTLS on T/T0, threshold 0.01 (scaled library)')
print_coef(theta_c, names_c)
print('\nseries expansion : 1 + theta0^2/16 + 11 theta0^4/3072 = 1 + %.4f theta0^2 + %.4f theta0^4' % (1/16, 11/3072))
least squares
       1 :     0.993
      th :     0.025
    th^2 :     0.042
    th^3 :    -0.008
    th^4 :     0.014

STLS on T/T0, threshold 0.01 (scaled library)
       1 :     0.998
      th :     -
    th^2 :     0.068
    th^3 :     -
    th^4 :     -

series expansion : 1 + theta0^2/16 + 11 theta0^4/3072 = 1 + 0.0625 theta0^2 + 0.0036 theta0^4

Least squares uses all five powers, with coefficients of mixed sign that include odd powers the physics forbids. STLS keeps two: $T/T_0 = 0.998 + 0.068\,\theta_0^2$. The exact series is $1 + \theta_0^2/16 + 11\theta_0^4/3072 + \cdots = 1 + 0.0625\,\theta_0^2 + 0.0036\,\theta_0^4 + \cdots$, so the discovered coefficient of $\theta_0^2$ is $9\%$ above the series value, having absorbed the $\theta_0^4$ term that the data at $1\%$ noise cannot resolve on their own. The odd powers are gone, as they should be.

In [ ]:
th_fine = np.linspace(0, 1.3, 200)
Phi_fine_c = np.hstack([np.ones((200, 1)), th_fine.reshape(-1, 1), (th_fine**2).reshape(-1, 1), (th_fine**3).reshape(-1, 1), (th_fine**4).reshape(-1, 1)])
ratio_exact = 2/np.pi*ellipk(np.sin(th_fine/2)**2)

plt.figure(figsize = (6, 4))
plt.plot(th_fine, ratio_exact, 'k', linewidth = 3, alpha = 0.3, label = 'Exact')
plt.plot(theta0, ratio, 'ko', markersize = 4, label = 'Data')
plt.plot(th_fine, Phi_fine_c @ theta_c, 'r--', linewidth = 1.5, label = 'Discovered')
plt.plot(th_fine, 1 + th_fine**2/16, 'b:', linewidth = 1.5, label = r'$1 + \theta_0^2/16$')
plt.xlabel(r'$\theta_0$ (rad)')
plt.ylabel(r'$T / T_0$')
plt.xlim([0, 1.3])
plt.legend()
plt.grid(True)
plt.show()

T_model = 2*np.pi*np.sqrt(L/g)*(Phi_c @ theta_c)
print('relative error of the discovered law on the data : %.4f (noise level 0.01)' % np.sqrt(np.mean((T_model/T_exact - 1)**2)))
No description has been provided for this image
relative error of the discovered law on the data : 0.0010 (noise level 0.01)

The discovered correction follows the exact curve across the whole range of amplitudes, and improves on the pure $\theta_0^2/16$ term at large angles because its slightly larger coefficient stands in for the quartic. The full discovered law, $T = 2\pi\sqrt{L/g}\,(0.998 + 0.068\,\theta_0^2)$, reproduces the exact periods of the eighty pendulums to $0.10\%$, below the $1\%$ noise of the measurements they were discovered from.


6.4. What the Lab Showed

From eighty noisy timings and no mechanics, sparse regression found that the period of a pendulum grows as the square root of its length, does not depend on its mass, and increases with amplitude as the square of the release angle, with the coefficient of the leading correction within $10\%$ of the value that the elliptic integral gives. Each conclusion was a zero or a nonzero in a coefficient vector. The lab also showed the two moves that discovery depends on: choosing a library in which the law is sparse, logarithms for a power law and even polynomials for a symmetric correction, and reading a misfit, the $3\%$ excess in the constant, as a sign that the library was missing something rather than as noise to be ignored.




Summary

Key takeaways

  • Equation discovery with a library of candidates is linear regression in which the coefficients are the answer, and the answer is expected to be sparse: few nonzero coefficients, the rest exactly zero.
  • Least squares never returns a zero. It spreads weight over every column, more so when the columns are correlated, and a library of powers and simple functions is always correlated.
  • The $L_2$ penalty shrinks every coefficient by a factor and selects nothing; the $L_1$ penalty subtracts a constant from every coefficient and sets the small ones to zero. Geometrically, the $L_1$ ball has corners on the axes and the $L_2$ ball has none.
  • The LASSO selects, but with a bias and with a preference for cheap combinations of correlated columns that can pick the wrong terms. Sequential thresholded least squares, threshold then refit, selects by the size of each coefficient and estimates the survivors without bias; it is the engine of SINDy.
  • The threshold must be chosen from the data: a sweep over its value shows a long flat step where the model does not change, and that model is the one to report. The columns of the library must be on comparable scales for one threshold to apply to all of them.
  • Discovery fails in three recognizable ways: a missing term produces a plausible fit of wrong functions that breaks down on extrapolation; collinear candidates produce huge cancelling coefficients that change with the noise; and noise above a problem-dependent level removes the law from the data altogether.

Looking ahead. Every $y$ in this notebook was a measured quantity. In Sparse Identification of Nonlinear Dynamics the left-hand side is a time derivative, $\dot X = \Phi(X)\,\Theta$ with one coefficient vector $\theta$ per state variable, and the same sparse regression discovers the differential equation that generated a trajectory. The library, the thresholding and the diagnostics carry over unchanged. What is new is the derivative, which must be estimated from noisy measurements before anything else can be done, and the methods for doing so are where that notebook starts.