Regression and Fitting, Part 4: Least-Squares Fitting#
Linear, polynomial and non-linear regression are all least squares, and they share four choices that change the answer even when the model does not: how each observation is weighted, how errors are penalised, whether the solution is regularised, and what constraints it must satisfy. These choices are often made by default, by a library routine, and they are where a fitted curve or a calibrated parameter is most easily moved. This page sets out each choice, and shows what it does on a small example. It is the last of four pages on regression and fitting.
The general problem#
Fit parameters \(\theta\) of a model \(f(x; \theta)\) to observations \((x_i, y_i)\) by minimising
where \(\rho\) is the loss, \(w_i\) the weights, and possibly a penalty and constraints on \(\theta\). Ordinary least squares is \(\rho(r) = r^2\) and \(w_i = 1\).
Weights#
If the observations have different noise, with standard deviation \(\sigma_i\), the best linear unbiased estimate weights each by \(w_i = 1/\sigma_i^2\),
It is the same as ordinary least squares on \(X_i/\sigma_i\) and \(y_i/\sigma_i\). In a calibration, a weight of the inverse of the vega turns a price error into an error in implied volatility, which is the way that quotes are made and the way that noise is spread, and a weight of one fits the expensive options at the expense of the others (Calibration).
Robust losses#
The squared loss gives a large residual a very large influence, so a single bad quote can pull the fit. Robust losses grow more slowly for large residuals. The Huber loss is quadratic for \(|r| \le c\) and linear beyond,
and the soft-L1 and Cauchy losses, \(\rho = 2(\sqrt{1 + r^2} - 1)\) and \(\rho = \ln(1 + r^2)\), grow more slowly still. With a scale \(c\) set from the noise, they behave as least squares for the good points and limit the effect of the outliers. The price is that the problem is no longer a linear one, and a loss that grows very slowly, such as the Cauchy, is not convex and can have local minima.
Regularisation#
When the design matrix is ill-conditioned, small changes in the data produce large changes in the coefficients. Ridge or Tikhonov regularisation adds a penalty on the size of the coefficients,
in terms of the SVD \(X = U S V^\top\). Directions with a large singular value \(s_j \gg \sqrt\lambda\) are fitted as before, and those with a small one are damped instead of being amplified by \(1/s_j\). The parameter \(\lambda\) trades bias for variance, and it is chosen by cross-validation (Regression and Fitting, Part 2: Polynomial Regression). A penalty on the roughness of the fitted function, \(\lambda \int (f'')^2 dx\), is the smoothing spline of Interest Rate Curves, Part 5: Regression Fits.
Constraints#
A fitted quantity often has to satisfy a constraint: a weight that is not negative, a discount factor that falls, a volatility that is positive. Bounds can be imposed directly (bounded least squares). Non-negative least squares solves \(\min \lVert X\beta - y \rVert^2\) subject to \(\beta \ge 0\). A constraint stops a fit from using offsetting terms, and where it is active it says that the data want something that is not allowed.
Worked example#
The example takes four small problems. It fits a line with noise that grows with \(x\), with and without weights, and compares the spread of the estimates with the theory. It fits a line to data with two outliers, with four losses. It fits a degree-10 polynomial to 20 noisy points of a sine, with ridge regularisation of increasing strength. And it fits a sum of five decaying exponentials to data from two of them, with and without a non-negativity constraint.
Python code
"""Least-squares fitting: weights, robust losses, ridge regularisation and a sign constraint."""
import numpy as np
from scipy.optimize import least_squares, nnls
if __name__ == "__main__":
rng = np.random.default_rng(31)
print("1. Weights: y = 1 + 0.5 x with noise that grows with x (standard deviation 0.1 x), 20 points, 2,000 repetitions")
x = np.linspace(1, 10, 20)
a = np.column_stack([np.ones_like(x), x])
sigma = 0.1 * x
ols, wls = [], []
for _ in range(2000):
y = 1 + 0.5 * x + rng.normal(0, sigma)
ols.append(np.linalg.lstsq(a, y, rcond=None)[0])
wls.append(np.linalg.lstsq(a / sigma[:, None], y / sigma, rcond=None)[0])
ols, wls = np.array(ols), np.array(wls)
theory = np.sqrt(np.diag(np.linalg.inv((a / sigma[:, None]).T @ (a / sigma[:, None]))))
print(f" {'':<22} {'std dev of intercept':>21} {'std dev of slope':>17}")
print(f" {'Ordinary':<22} {ols[:, 0].std():21.4f} {ols[:, 1].std():17.4f}")
print(f" {'Weighted by 1/sigma':<22} {wls[:, 0].std():21.4f} {wls[:, 1].std():17.4f}")
print(f" {'Theory for weighted':<22} {theory[0]:21.4f} {theory[1]:17.4f}")
print("\n2. Outliers: 30 points on y = 1 + 0.5 x with noise 0.1, two points raised by 3")
x = np.linspace(0, 10, 30)
y = 1 + 0.5 * x + rng.normal(0, 0.1, 30)
y[[8, 20]] += 3.0
print(f" {'Loss':<26} {'intercept':>10} {'slope':>8} {'error in the fitted line at x = 10':>36}")
for loss in ("linear", "huber", "soft_l1", "cauchy"):
r = least_squares(lambda p: p[0] + p[1] * x - y, [0.0, 0.0], loss=loss, f_scale=0.2)
label = {"linear": "Squared error (ordinary)", "huber": "Huber", "soft_l1": "Soft L1", "cauchy": "Cauchy"}[loss]
print(f" {label:<26} {r.x[0]:10.4f} {r.x[1]:8.4f} {r.x[0] + 10 * r.x[1] - 6.0:36.4f}")
print(" true line: intercept 1.0000, slope 0.5000")
print("\n3. Ridge regularisation: degree-10 monomial fit to 20 noisy points of sin(2 pi x), noise 0.05")
x = np.linspace(0, 1, 20)
y = np.sin(2 * np.pi * x) + rng.normal(0, 0.05, 20)
xt = np.linspace(0, 1, 400)
a = np.vander(x, 11, increasing=True)
u, s, vt = np.linalg.svd(a, full_matrices=False)
print(f" {'lambda':>9} {'effective condition':>20} {'training RMSE':>14} {'test RMSE':>10} {'norm of coefficients':>21}")
for lam in (0.0, 1e-12, 1e-9, 1e-6, 1e-4, 1e-2):
filt = s / (s**2 + lam) if lam > 0 else 1 / s
coef = vt.T @ (filt * (u.T @ y))
train = np.sqrt(np.mean((a @ coef - y) ** 2))
test = np.sqrt(np.mean((np.vander(xt, 11, increasing=True) @ coef - np.sin(2 * np.pi * xt)) ** 2))
cond = s[0] / s[-1] if lam == 0 else np.sqrt((s[0] ** 2 + lam) / (s[-1] ** 2 + lam))
print(f" {lam:9.0e} {cond:20.2e} {train:14.4f} {test:10.4f} {np.linalg.norm(coef):21.1f}")
print("\n4. A sign constraint: fit exp(-t/tau) terms for tau = 1, 2, 3, 4, 5 to data from 0.3 exp(-t/2) + 0.7 exp(-t/4) + noise 0.002")
t = np.linspace(0, 10, 40)
y = 0.3 * np.exp(-t / 2) + 0.7 * np.exp(-t / 4) + rng.normal(0, 0.002, t.size)
a = np.exp(-t[:, None] / np.array([1.0, 2, 3, 4, 5]))
free = np.linalg.lstsq(a, y, rcond=None)[0]
nonneg = nnls(a, y)[0]
print(f" {'':<22} " + " ".join(f"{'tau ' + str(k):>8}" for k in range(1, 6)) + f" {'RMSE':>9} {'sum':>7}")
for name, w in (("Unconstrained", free), ("Non-negative", nonneg)):
print(f" {name:<22} " + " ".join(f"{v:8.3f}" for v in w) + f" {np.sqrt(np.mean((a @ w - y) ** 2)):9.5f} {w.sum():7.3f}")
The output is:
1. Weights: y = 1 + 0.5 x with noise that grows with x (standard deviation 0.1 x), 20 points, 2,000 repetitions
std dev of intercept std dev of slope
Ordinary 0.2162 0.0543
Weighted by 1/sigma 0.1017 0.0351
Theory for weighted 0.1002 0.0353
2. Outliers: 30 points on y = 1 + 0.5 x with noise 0.1, two points raised by 3
Loss intercept slope error in the fitted line at x = 10
Squared error (ordinary) 1.2173 0.4969 0.1862
Huber 1.0132 0.5012 0.0252
Soft L1 1.0183 0.5009 0.0274
Cauchy 1.0012 0.5013 0.0143
true line: intercept 1.0000, slope 0.5000
3. Ridge regularisation: degree-10 monomial fit to 20 noisy points of sin(2 pi x), noise 0.05
lambda effective condition training RMSE test RMSE norm of coefficients
0e+00 2.39e+07 0.0249 0.0275 58357.8
1e-12 5.99e+06 0.0251 0.0266 5934.7
1e-09 1.96e+05 0.0256 0.0251 138.8
1e-06 6.19e+03 0.0267 0.0248 53.1
1e-04 6.19e+02 0.0422 0.0417 22.6
1e-02 6.19e+01 0.2199 0.2019 7.3
4. A sign constraint: fit exp(-t/tau) terms for tau = 1, 2, 3, 4, 5 to data from 0.3 exp(-t/2) + 0.7 exp(-t/4) + noise 0.002
tau 1 tau 2 tau 3 tau 4 tau 5 RMSE sum
Unconstrained -0.081 0.857 -1.496 2.385 -0.668 0.00171 0.998
Non-negative 0.000 0.259 0.117 0.591 0.033 0.00185 0.999
Reading the output:
Weights cut the uncertainty by a third to a half here. With noise that grows with \(x\), ordinary least squares has a standard deviation of 0.216 for the intercept and 0.054 for the slope. Weighting by \(1/\sigma\) gives 0.102 and 0.035, which match the theory, 0.100 and 0.035. Both estimates are unbiased. The weighted one has the lower variance, and the difference is the cost of ignoring the structure of the noise.
Two bad points move an ordinary fit. The two points raised by 3 move the intercept to 1.217, for a true 1.0, and leave the line wrong by 0.186 at \(x = 10\). The Huber, soft-L1 and Cauchy losses give 1.013, 1.018 and 1.001, and errors of 0.025, 0.027 and 0.014 at \(x = 10\), 7 to 13 times smaller.
Regularisation trades a small bias for stable coefficients. Without it, the degree-10 fit has coefficients of norm 58,358, and a design matrix with an effective condition number of 2.4e7. With \(\lambda = 10^{-6}\) the norm is 53, the condition number 6.2e3, the training error rises slightly, 0.0249 to 0.0267, and the test error falls, 0.0275 to 0.0248. With \(\lambda = 10^{-2}\) the fit is too stiff, and both errors are about 0.2.
A constraint changes the answer without changing the fit. The unconstrained fit to the exponentials has weights from -1.50 to +2.39 that nearly cancel, and a fit error of 0.0017. The non-negative fit has weights between 0 and 0.59 and a fit error of 0.0019, both at the level of the noise, 0.002. The two have the same sum, 1.0, and give nearly the same curve. The data do not determine the individual weights, and the constraint chooses one answer from many.
A valuation control view#
Record the weights and the loss: they are part of the model. A calibration weighted by price and one weighted by vega give different parameters from the same quotes, and the difference is a model choice and not an error.
Look at the residuals, point by point: a single quote with a large residual is either an outlier or a sign that the model cannot fit it. A robust loss hides the outlier in the fit, so the residuals have to be reported.
Do not let a regularisation parameter be an unreported knob: a ridge or smoothing parameter changes the fitted curve, and a larger one hides instability. Report it, and the sensitivity of the valuation to it.
Check where constraints bind: a coefficient or parameter on a bound is information. A fit that needs a non-negativity or a bound to give sensible numbers is under-determined.
Compare fits, not only parameters: two different sets of parameters can give the same curve. Whether it matters depends on what is priced with them, and the test is the price of the products that are outside the fit.
Next, Numerical Methods: Optimisation and Calibration covers the optimisation that sits under all of these fits, and the calibration of a model to prices.