Skip to main content

Regularization: Ridge and Lasso Regression

What is regularization?​

Regularization (also called shrinkage or penalised regression) stops a model overfitting by adding a penalty on the size of its coefficients to the error it minimises. Ridge regression penalises the squared coefficients (L2) and shrinks them all; lasso regression penalises their absolute values (L1) and sets some exactly to zero. A tuning value, λ, sets its strength.

Three charts in a dark navy theme: noisy training points with a dashed true curve and an orange fitted polynomial that follows it smoothly, a coefficient path chart with fifteen coloured lines shrinking towards zero as lambda increases on a log-scale axis with a dashed marker at the chosen lambda, and training, cross-validation and test error curves against lambda with the cross-validation curve dipping to a minimum

A degree-15 polynomial fitted to 20 noisy points with ridge regression, its coefficient paths and its error curves (sample data). Try the interactive version.

Key takeaways
  • A model that fits its training data too closely learns the noise as well as the pattern, and predicts new data badly.
  • Ridge (L2) shrinks every coefficient smoothly; lasso (L1) shrinks them and drops some to exactly zero; elastic net mixes the two.
  • λ moves the model along the bias–variance trade-off: larger values mean a simpler, more stable model that fits the training data less closely.
  • Choose λ by cross-validation on the training data, and standardise the features first so the penalty treats them equally.

Overfitting vs underfitting​

Polynomial regression fits a curve y=β0+β1x+β2x2+⋯+βdxdy = \beta_0 + \beta_1 x + \beta_2 x^2 + \dots + \beta_d x^d by least squares. It is still linear regression, because the model is linear in the coefficients; the powers of x are just extra features. The degree d sets how flexible the curve can be, which makes it the clearest way to see two opposite failures:

  • Underfitting: the model is too simple for the pattern. Its error is high on the training data and on new data.
  • Overfitting: the model is flexible enough to bend through the random noise in the training points. Its training error is very low, but it predicts new data badly, because the noise it learned won't repeat.

Three panels with the same 20 noisy points around a dashed wavy true curve. Left, a straight line (degree 1) misses the wave: underfitting, training RMSE 0.74, test RMSE 0.56. Middle, a degree 6 polynomial follows the wave: a good fit, training RMSE 0.20, test RMSE 0.30. Right, a degree 15 polynomial passes close to every point but swings off the chart at both ends: overfitting, training RMSE 0.08, test RMSE 5.56

The table uses the same 20 points, drawn from a smooth curve with random noise of standard deviation 0.25, and 200 new points from the same curve as a test set. RMSE (root mean squared error) is the typical size of a prediction error, so a perfect model would score about 0.25 on new data: the noise itself.

DegreeTraining RMSETest RMSEDiagnosis
10.740.56Underfitting: a straight line through a wave
30.410.38Still too stiff
60.200.30Close to the noise floor
100.170.30Training error still falling, test error flat
150.085.56Overfitting: wild swings between and beyond the points

Training error can only fall as the degree rises, because each higher-degree model contains the lower ones. That makes it useless for choosing the degree. The test error falls and then climbs, and its minimum is the model to keep.

The unpenalised degree-15 coefficients show the cause. On standardised features the largest is about 10,800, and there are large coefficients of both signs, which cancel each other at the training points and swing apart between them. Regularization works by keeping coefficients like these small.

The bias–variance trade-off​

The expected squared error of a model on a new point splits into three parts:

E[(y−f^(x))2]=σ2⏟noise+(E[f^(x)]−f(x))2⏟bias2+E[(f^(x)−E[f^(x)])2]⏟variance\mathbb{E}\big[(y - \hat f(x))^2\big] = \underbrace{\sigma^2}_{\text{noise}} + \underbrace{\big(\mathbb{E}[\hat f(x)] - f(x)\big)^2}_{\text{bias}^2} + \underbrace{\mathbb{E}\big[(\hat f(x) - \mathbb{E}[\hat f(x)])^2\big]}_{\text{variance}}
  • Bias is how far the average model, over many possible training sets, is from the truth. A straight line fitted to a wave is biased however much data you give it.
  • Variance is how much the model changes from one training set to another. A degree-15 polynomial fitted to a fresh sample of 20 points looks completely different each time.
  • The noise, σ2\sigma^2, is the floor no model can beat.

Flexible models have low bias and high variance; simple ones the reverse. Underfitting is the high-bias end and overfitting the high-variance end. Regularization gives a dial between them that doesn't change the model's form: keep all 15 powers of x, and let λ decide how far the coefficients may grow. Hoerl and Kennard proved that some λ greater than zero always gives ridge coefficients a lower mean squared error than least squares: the variance removed outweighs the bias added.

How regularization works: the penalty and λ​

Least squares picks the coefficients that minimise the residual sum of squares, RSS =∑i(yi−y^i)2= \sum_i (y_i - \hat y_i)^2. A regularized model minimises the RSS plus a penalty that grows with the coefficients:

minimiseRSS(β)+λ⋅penalty(β)\text{minimise} \quad \text{RSS}(\beta) + \lambda \cdot \text{penalty}(\beta)

The penalty strength λ (alpha in some libraries) is a hyperparameter: you set it, the data doesn't. At λ = 0 you get ordinary least squares. As λ grows, large coefficients cost more, so the fit settles for smaller ones and a smoother curve, at the price of a slightly higher training error. The intercept β0\beta_0 is left out of the penalty, so shrinking the slopes never drags the whole curve towards zero.

What is ridge regression (L2)?​

Ridge regression penalises the sum of the squared coefficients, the squared L2 norm:

β^ridge=arg⁡min⁡β  ∑i=1n(yi−β0−∑j=1pxijβj)2+λ∑j=1pβj2\hat\beta^{\text{ridge}} = \arg\min_\beta \; \sum_{i=1}^{n} \Big(y_i - \beta_0 - \sum_{j=1}^{p} x_{ij}\beta_j\Big)^2 + \lambda \sum_{j=1}^{p} \beta_j^2

It has a closed-form solution. With the features centred, β^ridge=(X⊤X+λI)−1X⊤y\hat\beta^{\text{ridge}} = (X^\top X + \lambda I)^{-1} X^\top y. When features are highly correlated, as x13x^{13}, x14x^{14} and x15x^{15} are, X⊤XX^\top X is close to singular, and least squares produces the huge, unstable coefficients seen above. Adding λ to its diagonal makes the matrix well conditioned, so the solution stays stable.

Hoerl and Kennard introduced ridge regression in 1970 for exactly this problem, correlated predictors. The same idea appears in numerical analysis as Tikhonov regularization and in neural networks as weight decay.

Ridge shrinks every coefficient but almost never to exactly zero, so all the features stay in the model. In the example, ridge at λ = 0.25 keeps all 15 powers but cuts the largest coefficient from about 10,800 to 1.6. The training RMSE rises from 0.08 to 0.33 and the test RMSE falls from 5.56 to 0.30.

What is lasso regression (L1)?​

Lasso regression (least absolute shrinkage and selection operator) penalises the sum of the absolute values, the L1 norm:

β^lasso=arg⁡min⁡β  ∑i=1n(yi−β0−∑j=1pxijβj)2+λ∑j=1p∣βj∣\hat\beta^{\text{lasso}} = \arg\min_\beta \; \sum_{i=1}^{n} \Big(y_i - \beta_0 - \sum_{j=1}^{p} x_{ij}\beta_j\Big)^2 + \lambda \sum_{j=1}^{p} |\beta_j|

Tibshirani introduced it in 1996. Replacing the squares with absolute values means the lasso sets some coefficients exactly to zero, so it fits the model and selects features in one step. At the λ chosen by cross-validation in the example (0.16), the lasso keeps 7 of the 15 powers of x and reaches a test RMSE of 0.29.

There is no closed form, because ∣βj∣|\beta_j| has a corner at zero. The usual solver, used by glmnet, is coordinate descent: fix all coefficients but one, solve for that one exactly, and cycle until nothing changes. Each one-coefficient step is a soft-threshold: work out the least squares value for that coefficient given the others, move it towards zero by λ/2 divided by that feature's sum of squares, and set it to zero if it would cross. Coordinate descent slows down badly on nearly collinear features such as high powers of x, so the live demo runs it for a while and then finishes with an exact active-set step (feature-sign search) that checks the lasso's optimality conditions.

Worked example: ridge and lasso on three coefficients​

The difference is easiest to see when the features are orthonormal (uncorrelated, each with ∑ixij2=1\sum_i x_{ij}^2 = 1). Then each coefficient can be solved on its own from its least squares value β^j\hat\beta_j:

  • ridge: β^j/(1+λ)\hat\beta_j / (1 + \lambda), the same proportional shrink for every coefficient;
  • lasso: sign(β^j) max⁡(∣β^j∣−λ/2, 0)\text{sign}(\hat\beta_j)\,\max(|\hat\beta_j| - \lambda/2,\ 0), the same fixed step towards zero, stopping at zero.

With λ = 1:

CoefficientLeast squaresRidgeLasso
β1\beta_13.01.52.5
β2\beta_21.00.50.5
β3\beta_30.40.20

Ridge halves everything, so big coefficients lose the most in absolute terms. The lasso takes 0.5 off each, which leaves the big coefficient almost untouched and removes the small one entirely. With the penalty written as RSS + λ times the norm, as here, the lasso step is λ/2. Texts that put ½ in front of the RSS write it as λ.

Why lasso sets coefficients to zero: the geometry​

Each penalised fit can be rewritten as least squares with a budget: minimise the RSS while keeping the penalty below some limit t. Larger λ means a smaller t. The diagram shows the case of two coefficients.

Two panels in the plane of two coefficients, beta 1 across and beta 2 up. In both, brown ellipses of equal residual sum of squares surround the least squares estimate at about (1.8, 0.7). Left, the lasso budget is a red diamond with corners on the axes; the ellipse that first touches it does so at the corner (1, 0), so beta 2 is exactly zero. Right, the ridge budget is a blue circle; the ellipse first touches it at (0.83, 0.56), where both coefficients are smaller but neither is zero

  • The ellipses are contours of equal RSS around the least squares estimate. Moving outwards, the error grows.
  • The shaded shape holds every pair of coefficients the budget allows: a diamond for the L1 norm, a circle for the L2 norm.
  • The penalised solution is the point where the smallest ellipse first touches the shape.
  • The diamond has corners on the axes, and an ellipse coming from most directions hits a corner first. At a corner, one coefficient is exactly zero. In more dimensions the L1 shape has many corners and edges, so several coefficients can be zero at once.
  • The circle has no corners, so the touching point almost never lies on an axis. Ridge pulls both coefficients in, but keeps both.

Elastic net: combining L1 and L2​

The elastic net (Zou and Hastie, 2005) uses both penalties: RSS + λ1∑j∣βj∣+λ2∑jβj2+\ \lambda_1 \sum_j |\beta_j| + \lambda_2 \sum_j \beta_j^2, often written as one λ and a mixing weight α between 0 (ridge) and 1 (lasso). It keeps the lasso's zeros, but where the lasso picks one feature from a group of strongly correlated ones more or less at random, the elastic net tends to keep or drop the group together. It also avoids a lasso limit: with more features than observations, the lasso can select at most n of them.

How to read a coefficient path plot​

A coefficient path plot shows every coefficient against λ, usually on a log scale. In the live demo it is the bottom-left chart.

  • The x-axis is λ on a logarithmic axis, because the interesting changes happen over several powers of ten. Some tools reverse it, or plot against the L1 norm of the coefficients instead.
  • At the right, with a very large λ, every coefficient is at or near zero: the model predicts the mean.
  • Moving left, coefficients grow. For ridge they all grow together, smoothly. For the lasso they enter one at a time: in the example, only the xx term is non-zero at λ = 10, and x3x^3 and x4x^4 have joined it by λ = 1.
  • At the far left, the paths approach the least squares values, which for an overfitted model are large and of both signs.
  • A vertical line marks the λ chosen by cross-validation. Read across it to see which features the chosen model uses and how much each one counts.
  • Lasso paths can cross zero or leave the model again as λ falls. A feature that enters early and stays is a strong, stable predictor; one that flickers in and out is not.

How to choose λ with cross-validation​

λ can't be chosen on the training error, which is always lowest at λ = 0, or on the test set, which then stops being an honest test. Cross-validation estimates the error on new data from the training data alone. In k-fold cross-validation:

  1. Split the training data into k folds, often 5 or 10.
  2. For each λ on a grid, spaced evenly on a log scale: fit the model k times, each time leaving one fold out, and measure the error on the fold left out.
  3. Average the k errors for each λ, and plot the average against λ. This is the validation curve.
  4. Pick the λ at the minimum of the curve, refit on all the training data, and check the result once on the test set.

The validation curve is U-shaped for the same reason as the test error against degree. On the right of the U, large λ, the model underfits: high bias. On the left, small λ, it overfits: high variance. For the 20-point example fitted with ridge at degree 15, the 5-fold CV error is lowest at λ = 0.25, about 0.40, where the test error is 0.30. At λ = 100 both are around 0.75 to 0.85 (underfitting), and unpenalised, the cross-validation error runs into the thousands.

Hastie, Tibshirani and Friedman suggest a one-standard-error rule: rather than the λ at the minimum, take the largest λ whose error is within one standard error of it. The curve is noisy near its minimum, and the rule picks the simplest model that the data can't tell apart from the best one.

A validation curve can also be drawn against the degree, or any other complexity setting. A learning curve plots the error against the size of the training set: if the training and validation errors meet at a high level, more data won't help and the model needs more flexibility; if a wide gap remains, more data or more regularization will.

Standardise the features first​

The penalty adds up the coefficients' sizes, but a coefficient's size depends on its feature's units. A feature in millimetres needs a coefficient 1,000 times smaller than the same feature in metres, so it is penalised far less. Without scaling, the penalty depends on arbitrary choices of units.

  • Standardise each feature to mean 0 and standard deviation 1 before fitting. In the polynomial example every power of x is standardised, so xx and x15x^{15} compete on equal terms.
  • Compute the means and standard deviations on the training data only, and inside each cross-validation fold on that fold's training part. Scaling on the whole dataset leaks information from the held-out points.
  • Centre y, or fit an unpenalised intercept, so the penalty never pulls the average prediction towards zero.
  • To report coefficients in the original units, divide each standardised coefficient by its feature's standard deviation.

Ridge vs lasso vs elastic net​

Use ridge when many features each matter a little, lasso when you want a small model with only a few features, and elastic net when correlated features should be kept or dropped together.

MethodPenaltySets coefficients to zero?Correlated featuresSolutionBest when
Least squaresNoneNoUnstable, large offsetting coefficientsClosed formFew features, plenty of data, no collinearity
Ridge (L2)λ∑jβj2\lambda \sum_j \beta_j^2No, shrinks allShares the weight across the groupClosed formMany features that each matter a little; collinearity
Lasso (L1)λ∑j∣βj∣\lambda \sum_j \lvert\beta_j\rvertYesPicks one, more or less at randomIterative (coordinate descent, LARS)A few features matter, and you want a small, explainable model
Elastic netBothYesKeeps or drops the group togetherIterativeMany correlated features and you want selection
Fewer features or lower degreeHard limitDrops them by handUp to youClosed formYou know which features matter

For neural networks the same ideas appear as weight decay (equivalent to an L2 penalty under plain gradient descent, but not with adaptive optimisers such as Adam), early stopping (halting training when the validation error starts to rise) and dropout.

Common regularization mistakes​

Most regularization mistakes come from how λ is chosen and reported, or from reading too much into the features the lasso keeps.

  • Standardising 0/1 features without thinking. Scaling a dummy variable for a rare category makes its coefficient cheaper or dearer to use, depending on the choice. Decide on purpose, and use the same rule for every dummy.
  • Quoting the best cross-validation error as the expected error. λ was chosen because that error was lowest, so it is optimistic. Report the error on a held-out test set, or use nested cross-validation, with λ tuned inside each outer fold.
  • Searching too narrow a grid. If the minimum of the validation curve sits at the end of the λ grid, the best value may be beyond it. Extend the grid until the curve turns up on both sides.
  • Reading p-values after lasso selection. Standard errors and p-values from refitting the selected features by least squares ignore the selection step, so they look more certain than they are.
  • Copying λ between tools. Libraries scale the loss differently. scikit-learn's lasso divides the RSS by 2n, so its alpha is not the λ in a textbook formula; glmnet uses a similar scaling. Tune λ again in each tool.
  • Treating the lasso's choice of features as the truth. With correlated features, a small change in the data can swap which one is kept. Check stability across folds or bootstrap samples before telling anyone that feature A matters and B doesn't.
  • Reading a smooth fit as a good one far from the data. Even a regularized polynomial can swing outside the range of the training x values. Don't extrapolate.
  • Skipping the residuals. A low cross-validation error doesn't show a curve the model missed or noise that grows with x. Check a residual plot of the chosen model.

How to plot ridge and lasso regression in JavaScript, React or Angular​

The demo refits 366 models in the browser each time you change the degree or the noise (61 values of λ, each fitted once on all the data and five times for cross-validation), then redraws the fitted curve, the coefficient paths and the error curves together. The ridge, lasso and cross-validation maths is plain JavaScript.

Choose a Method: no penalty, ridge or lasso. Degree sets the polynomial degree, from 1 to 15. Drag the λ slider, or the dashed line on the coefficient path chart, to change the penalty on a log scale from 0.0001 to 100. Noise sets the noise in the data. Best λ (5-fold CV) jumps to the λ with the lowest cross-validation error, Error vs switches the error chart between λ and degree, and Resample data draws a fresh set of points. The readout above the charts gives the training, cross-validation and test RMSE and the number of non-zero coefficients. Hover any chart for values; the wheel zooms, a drag pans and a double-click restores the full view.

Here is the code for this chart. The fitting is plain JavaScript; SciChart.js draws the training points as a scatter series, the fitted curve, coefficient paths and error curves as line series, and λ on a logarithmic axis.

// Polynomial regression with ridge and lasso penalties: the fit, coefficient paths and error curves, charted with SciChart.js
const {
SciChartSurface,
NumericAxis,
LogarithmicAxis,
NumberRange,
EAxisAlignment,
FastLineRenderableSeries,
XyScatterRenderableSeries,
EllipsePointMarker,
XyDataSeries,
VerticalLineAnnotation,
LegendModifier,
ELegendPlacement,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"

// --- Regression maths (plain JavaScript, no library needed) ---

// Polynomial features x, x², ..., x^degree for each x
function polyFeatures(xs, degree) {
return xs.map((x) => {
const row = [];
let power = 1;
for (let k = 1; k <= degree; k++) {
power *= x;
row.push(power);
}
return row;
});
}

// Standardise each feature to mean 0 and standard deviation 1, using the training rows only,
// so the penalty treats x and x¹⁵ equally. Returns a function that applies the same scaling to any rows.
function standardiser(rows) {
const n = rows.length;
const d = rows[0].length;
const mean = new Array(d).fill(0);
const sd = new Array(d).fill(0);
for (const row of rows) for (let j = 0; j < d; j++) mean[j] += row[j] / n;
for (const row of rows) for (let j = 0; j < d; j++) sd[j] += (row[j] - mean[j]) ** 2 / n;
for (let j = 0; j < d; j++) sd[j] = Math.sqrt(sd[j]) || 1;
return (newRows) => newRows.map((row) => row.map((v, j) => (v - mean[j]) / sd[j]));
}

// Least squares by Householder QR: the b that minimises ||A b - t||². QR is used rather than the normal
// equations because high powers of x are nearly collinear and XᵀX is badly conditioned.
function leastSquares(A, t) {
const m = A.length;
const n = A[0].length;
const R = A.map((row) => row.slice());
const q = t.slice();
for (let k = 0; k < n; k++) {
let norm = 0;
for (let i = k; i < m; i++) norm += R[i][k] ** 2;
norm = Math.sqrt(norm);
if (norm === 0) continue;
const v = new Array(m).fill(0);
for (let i = k; i < m; i++) v[i] = R[i][k];
v[k] -= R[k][k] > 0 ? -norm : norm;
let vv = 0;
for (let i = k; i < m; i++) vv += v[i] ** 2;
if (vv === 0) continue;
const reflect = (get, set) => {
let s = 0;
for (let i = k; i < m; i++) s += v[i] * get(i);
s = (2 * s) / vv;
for (let i = k; i < m; i++) set(i, get(i) - s * v[i]);
};
for (let j = k; j < n; j++) reflect((i) => R[i][j], (i, value) => (R[i][j] = value));
reflect((i) => q[i], (i, value) => (q[i] = value));
}
const b = new Array(n).fill(0);
for (let k = n - 1; k >= 0; k--) {
let s = q[k];
for (let j = k + 1; j < n; j++) s -= R[k][j] * b[j];
b[k] = Math.abs(R[k][k]) > 1e-300 ? s / R[k][k] : 0;
}
return b;
}

// Ridge: minimise RSS + λ Σ b². The closed form is b = (XᵀX + λI)⁻¹ Xᵀy; solving least squares on X with
// √λ·I stacked underneath (and zeros under y) gives the same b, more accurately. λ = 0 is plain least squares.
function ridge(X, y, lambda) {
const d = X[0].length;
const A = X.map((row) => row.slice());
const t = y.slice();
for (let j = 0; j < d; j++) {
const row = new Array(d).fill(0);
row[j] = Math.sqrt(lambda);
A.push(row);
t.push(0);
}
return leastSquares(A, t);
}

// Lasso: minimise RSS + λ Σ |b|. Written with G = XᵀX and c = Xᵀy, RSS = yᵀy − 2cᵀb + bᵀGb.
// Step 1, cyclic coordinate descent: solve for one coefficient at a time with the others fixed. Each step has
// an exact answer, ρ soft-thresholded by λ/2, and that threshold is what sets coefficients exactly to zero.
// Step 2, an exact finish: high powers of x are nearly collinear, which makes coordinate descent crawl, so once
// it is close, an active-set solve (feature-sign search) finds the exact optimum. `start` warm-starts step 1.
function lasso(X, y, lambda, start = null, sweeps = 200) {
const n = X.length;
const d = X[0].length;
const G = [];
const c = [];
for (let j = 0; j < d; j++) {
G.push([]);
c.push(0);
for (let i = 0; i < n; i++) c[j] += X[i][j] * y[i];
for (let k = 0; k < d; k++) {
let s = 0;
for (let i = 0; i < n; i++) s += X[i][j] * X[i][k];
G[j].push(s);
}
}
const half = lambda / 2;
const gradient = (b, j) => c[j] - G[j].reduce((s, v, k) => s + v * b[k], 0); // xⱼ · residual
const objective = (b) => b.reduce((s, bj, j) => s + bj * (G[j].reduce((t, v, k) => t + v * b[k], 0) - 2 * c[j]) + lambda * Math.abs(bj), 0);

// Step 1: coordinate descent
const b = start ? start.slice() : new Array(d).fill(0);
for (let sweep = 0; sweep < sweeps; sweep++) {
let maxChange = 0;
for (let j = 0; j < d; j++) {
const rho = gradient(b, j) + G[j][j] * b[j]; // xⱼ · (residual with feature j left out)
const next = (Math.sign(rho) * Math.max(Math.abs(rho) - half, 0)) / G[j][j];
maxChange = Math.max(maxChange, Math.abs(next - b[j]));
b[j] = next;
}
if (maxChange < 1e-12) break;
}

// Step 2: feature-sign search. With the signs of the non-zero coefficients fixed, the optimum solves
// Gₐₐ bₐ = cₐ − (λ/2)·sign(bₐ). Move towards it, stopping where the objective is lowest (at the target or
// where a coefficient crosses zero), then add any zero coefficient with |xⱼ · residual| > λ/2.
const tolerance = 1e-9 * Math.max(1, half);
for (let iteration = 0; iteration < 100; iteration++) {
const active = b.map((_, j) => j).filter((j) => b[j] !== 0);
const optimalOnActive = active.every((j) => Math.abs(gradient(b, j) - half * Math.sign(b[j])) < tolerance);
if (!optimalOnActive) {
const target = leastSquares(
active.map((j) => active.map((k) => G[j][k])),
active.map((j) => c[j] - half * Math.sign(b[j]))
);
const candidates = [1]; // fractions of the way to the target where a coefficient reaches zero
active.forEach((j, a) => {
if (Math.sign(target[a]) !== Math.sign(b[j])) candidates.push(b[j] / (b[j] - target[a]));
});
let best = null;
let bestValue = Infinity;
for (const t of candidates) {
const trial = b.slice();
active.forEach((j, a) => (trial[j] = b[j] + t * (target[a] - b[j])));
active.forEach((j) => Math.abs(trial[j]) < 1e-14 && (trial[j] = 0));
if (t !== 1) active.forEach((j, a) => Math.abs(b[j] / (b[j] - target[a]) - t) < 1e-12 && (trial[j] = 0));
const value = objective(trial);
if (value < bestValue) {
bestValue = value;
best = trial;
}
}
best.forEach((v, j) => (b[j] = v));
continue;
}
// All non-zero coefficients are optimal: add the zero one that most breaks |xⱼ · residual| ≤ λ/2
let entering = -1;
let largest = half + tolerance;
for (let j = 0; j < d; j++) {
const g = Math.abs(gradient(b, j));
if (b[j] === 0 && g > largest) {
entering = j;
largest = g;
}
}
if (entering < 0) break; // every optimality (KKT) condition holds: this is the lasso solution
b[entering] = Math.sign(gradient(b, entering)) * 1e-12; // enters with the sign that lowers the objective
}
return b;
}

// Fit one model: standardise the features, centre y (the intercept is never penalised), then solve.
// Returns the standardised coefficients and a predict(xs) function.
function fitModel(xs, ys, degree, method, lambda, start = null) {
const scale = standardiser(polyFeatures(xs, degree));
const X = scale(polyFeatures(xs, degree));
const intercept = ys.reduce((s, v) => s + v, 0) / ys.length;
const yc = ys.map((v) => v - intercept);
const coefficients = method === "lasso" ? lasso(X, yc, lambda, start) : ridge(X, yc, method === "none" ? 0 : lambda);
const predict = (newXs) => scale(polyFeatures(newXs, degree)).map((row) => intercept + row.reduce((s, v, j) => s + v * coefficients[j], 0));
return { coefficients, predict };
}

const rmse = (predicted, actual) => Math.sqrt(predicted.reduce((s, p, i) => s + (p - actual[i]) ** 2, 0) / actual.length);

// k-fold cross-validation: fit on k-1 folds, score on the held-out fold, average the squared errors.
// Folds take every k-th point of the x-sorted data, so each fold spans the whole x range.
function crossValidate(xs, ys, degree, method, lambda, k = 5, starts = null) {
let squaredError = 0;
const fits = [];
for (let fold = 0; fold < k; fold++) {
const trainIdx = xs.map((_, i) => i).filter((i) => i % k !== fold);
const testIdx = xs.map((_, i) => i).filter((i) => i % k === fold);
const model = fitModel(trainIdx.map((i) => xs[i]), trainIdx.map((i) => ys[i]), degree, method, lambda, starts?.[fold]);
const predicted = model.predict(testIdx.map((i) => xs[i]));
testIdx.forEach((i, n) => (squaredError += (predicted[n] - ys[i]) ** 2));
fits.push(model.coefficients);
}
return { rmse: Math.sqrt(squaredError / xs.length), fits };
}

// The λ grid for the coefficient paths and the error curve: 10⁻⁴ to 10², 10 steps per decade
const LAMBDAS = Array.from({ length: 61 }, (_, i) => 10 ** (2 - i / 10)); // largest first, for warm starts

// Fit every λ on the grid: coefficients, training, cross-validation and test RMSE.
// Lasso fits warm-start from the previous λ, so each lasso fit starts close to its answer.
function lambdaSweep(data, degree, method) {
let start;
let foldStarts;
const rows = LAMBDAS.map((lambda) => {
const model = fitModel(data.trainX, data.trainY, degree, method, lambda, start);
const cv = crossValidate(data.trainX, data.trainY, degree, method, lambda, 5, foldStarts);
start = model.coefficients;
foldStarts = cv.fits;
return {
lambda,
coefficients: model.coefficients,
train: rmse(model.predict(data.trainX), data.trainY),
cv: cv.rmse,
test: rmse(model.predict(data.testX), data.testY)
};
});
return rows.reverse(); // smallest λ first, for the charts
}

// Training, cross-validation and test RMSE for each degree at a fixed λ
function degreeSweep(data, method, lambda) {
return Array.from({ length: MAX_DEGREE }, (_, i) => {
const model = fitModel(data.trainX, data.trainY, i + 1, method, lambda);
return {
degree: i + 1,
train: rmse(model.predict(data.trainX), data.trainY),
cv: crossValidate(data.trainX, data.trainY, i + 1, method, lambda).rmse,
test: rmse(model.predict(data.testX), data.testY)
};
});
}

// --- The charts ---
const theme = new SciChartJsNavyTheme();
const COLOUR_DATA = "#50C7E0";
const COLOUR_TRUE = "#C8D3E8";
const COLOUR_FIT = "#F48420";
const COLOUR_TRAIN = "#50C7E0";
const COLOUR_CV = "#3BD16F";
const COLOUR_TEST = "#E36FD4";
const zoom = () => [new MouseWheelZoomModifier(), new ZoomPanModifier(), new ZoomExtentsModifier()];
const formatLambda = (v) => (v >= 0.01 && v < 1000 ? String(Number(v.toPrecision(2))) : v.toExponential(0));
const lambdaAxis = (wasmContext) => {
const axis = new LogarithmicAxis(wasmContext, { axisTitle: "λ (log scale)", logBase: 10, visibleRange: new NumberRange(1e-4, 100) });
axis.labelProvider.formatLabel = (v) => formatLambda(v);
axis.labelProvider.formatCursorLabel = (v) => formatLambda(v);
return axis;
};
const line = (wasmContext, name, stroke, extra = {}) =>
new FastLineRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { dataSeriesName: name }),
stroke,
strokeThickness: 2.5,
...extra
});
const setXy = (series, x, y) => {
series.dataSeries.clear();
series.dataSeries.appendRange(x, y);
};
const marker = () =>
new VerticalLineAnnotation({ x1: 0.1, stroke: "#FFFFFF", strokeThickness: 2, strokeDashArray: [6, 4], isEditable: true });

// 1. The fit: training points, the true curve and the fitted polynomial
const fit = await SciChartSurface.create(ui.fitDiv, { theme });
fit.sciChartSurface.xAxes.add(new NumericAxis(fit.wasmContext, { axisTitle: "x", visibleRange: new NumberRange(-1.05, 1.05) }));
fit.sciChartSurface.yAxes.add(
new NumericAxis(fit.wasmContext, { axisTitle: "y", axisAlignment: EAxisAlignment.Left, visibleRange: new NumberRange(-2.6, 2.6) })
);
const points = new XyScatterRenderableSeries(fit.wasmContext, {
dataSeries: new XyDataSeries(fit.wasmContext, { dataSeriesName: `Training data (${TRAIN_SIZE} points)` }),
pointMarker: new EllipsePointMarker(fit.wasmContext, { width: 9, height: 9, fill: COLOUR_DATA, stroke: "#FFFFFF", strokeThickness: 1 })
});
const truth = line(fit.wasmContext, "True curve", COLOUR_TRUE, { strokeThickness: 1.5, strokeDashArray: [6, 4] });
const fitted = line(fit.wasmContext, "Fitted curve", COLOUR_FIT, { strokeThickness: 3 });
fit.sciChartSurface.renderableSeries.add(truth, fitted, points);
const fitLegend = new LegendModifier({ showCheckboxes: false, placement: ELegendPlacement.TopLeft });
fit.sciChartSurface.chartModifiers.add(
fitLegend,
new CursorModifier({ showTooltip: true }),
...zoom()
);

// 2. Coefficient paths: one line per standardised coefficient against λ, with the current λ marked
const paths = await SciChartSurface.create(ui.pathDiv, { theme });
paths.sciChartSurface.xAxes.add(lambdaAxis(paths.wasmContext));
const pathYAxis = new NumericAxis(paths.wasmContext, { axisTitle: "Coefficient", axisAlignment: EAxisAlignment.Left });
paths.sciChartSurface.yAxes.add(pathYAxis);
// One colour per power of x, from x in red round the colour wheel to x¹⁵ in magenta
const PATH_COLOURS = ["#EC5151", "#EC8751", "#ECC051", "#E1EC51", "#A8EC51", "#72EC51", "#51EC68", "#51EC9E",
"#51ECD4", "#51CAEC", "#5194EC", "#515BEC", "#7D51EC", "#B551EC", "#EC51EC"];
const pathSeries = Array.from({ length: MAX_DEGREE }, (_, j) =>
line(paths.wasmContext, j === 0 ? "x" : `x^${j + 1}`, PATH_COLOURS[j], { strokeThickness: 2 })
);
paths.sciChartSurface.renderableSeries.add(...pathSeries);
const pathMarker = marker();
paths.sciChartSurface.annotations.add(pathMarker);
paths.sciChartSurface.chartModifiers.add(...zoom());

// 3. Error curves: training, 5-fold cross-validation and test RMSE against λ or against the degree
const errors = await SciChartSurface.create(ui.errorDiv, { theme });
const errorYAxis = new NumericAxis(errors.wasmContext, { axisTitle: "RMSE", axisAlignment: EAxisAlignment.Left, labelPrecision: 2 });
errors.sciChartSurface.yAxes.add(errorYAxis);
const trainLine = line(errors.wasmContext, "Training", COLOUR_TRAIN);
const cvLine = line(errors.wasmContext, "5-fold CV", COLOUR_CV);
const testLine = line(errors.wasmContext, `Test (${TEST_SIZE} new points)`, COLOUR_TEST);
errors.sciChartSurface.renderableSeries.add(trainLine, cvLine, testLine);
const errorMarker = marker();
errors.sciChartSurface.annotations.add(errorMarker);
errors.sciChartSurface.chartModifiers.add(
new LegendModifier({ showCheckboxes: false, placement: ELegendPlacement.TopRight }),
new CursorModifier({ showTooltip: true, showAxisLabels: false }),
...zoom()
);
let errorAxisMode = "";
function setErrorXAxis(mode) {
if (mode === errorAxisMode) return;
errorAxisMode = mode;
errors.sciChartSurface.xAxes.clear();
errors.sciChartSurface.xAxes.add(
mode === "lambda"
? lambdaAxis(errors.wasmContext)
: new NumericAxis(errors.wasmContext, { axisTitle: "Polynomial degree", visibleRange: new NumberRange(0.5, MAX_DEGREE + 0.5), labelPrecision: 0 })
);
}

// --- The controls ---
let seed = 1970;
let data;
let sweep; // the λ sweep for the current data, degree and method
const curveX = Array.from({ length: 301 }, (_, i) => -1 + i / 150);

const state = () => ({
method: ui.methodSelect.value,
degree: Number(ui.degreeInput.value),
lambda: 10 ** Number(ui.lambdaInput.value),
noise: Number(ui.noiseInput.value)
});
// The paths and the λ curve need a penalty: with "no penalty" selected they show ridge for comparison
const pathMethod = (method) => (method === "lasso" ? "lasso" : "ridge");

// New data: runs on noise changes and "Resample data"
function onDataChanged() {
const { noise } = state();
ui.noiseOutput.textContent = `σ = ${noise.toFixed(2)}`;
data = makeData(seed, noise);
setXy(points, data.trainX, data.trainY);
setXy(truth, curveX, curveX.map(trueCurve));
onModelChanged();
}

// New degree or method: recompute the λ sweep (coefficient paths and error curves)
function onModelChanged() {
const { method, degree } = state();
ui.degreeOutput.textContent = String(degree);
ui.lambdaInput.disabled = method === "none";
sweep = lambdaSweep(data, degree, pathMethod(method));
const lambdas = sweep.map((row) => row.lambda);
let maxAbs = 0;
pathSeries.forEach((series, j) => {
series.isVisible = j < degree;
if (j >= degree) return;
const values = sweep.map((row) => row.coefficients[j]);
setXy(series, lambdas, values);
// Scale the y-axis to λ ≥ 0.01: below that, high-degree coefficients head towards the unpenalised ones,
// which run into the thousands (zoom out or double-click to see them)
sweep.forEach((row, i) => row.lambda >= 0.01 && (maxAbs = Math.max(maxAbs, Math.abs(values[i]))));
});
pathYAxis.axisTitle = method === "none" ? "Ridge coefficient" : "Coefficient";
pathYAxis.visibleRange = new NumberRange(-1.1 * maxAbs, 1.1 * maxAbs);
onErrorChartChanged();
}

// Error chart: against λ (from the sweep) or against degree (refit at the current λ)
function onErrorChartChanged() {
const { method, lambda } = state();
const mode = ui.errorAxisSelect.value;
setErrorXAxis(mode);
const rows = mode === "lambda" ? sweep : degreeSweep(data, method, lambda);
const x = rows.map((row) => (mode === "lambda" ? row.lambda : row.degree));
setXy(trainLine, x, rows.map((row) => row.train));
setXy(cvLine, x, rows.map((row) => row.cv));
setXy(testLine, x, rows.map((row) => row.test));
const best = Math.min(...rows.map((row) => row.cv));
errorYAxis.visibleRange = new NumberRange(0, Math.max(1, 3 * best)); // clip the runaway overfit errors
updateFit();
}

// Refit the one model at the current settings, move the markers and update the readout
function updateFit() {
const { method, degree, lambda, noise } = state();
ui.lambdaOutput.textContent = method === "none" ? "0 (off)" : formatLambda(lambda);
const model = fitModel(data.trainX, data.trainY, degree, method, lambda);
setXy(fitted, curveX, model.predict(curveX));
const name = { none: "least squares", ridge: "ridge", lasso: "lasso" }[method];
fitted.dataSeries.dataSeriesName = `Fitted curve (${name}, degree ${degree}${method === "none" ? "" : `, λ = ${formatLambda(lambda)}`})`;
fitLegend.sciChartLegend?.setRenderableSeriesArray([truth, fitted, points]); // redraw the legend with the new name
pathMarker.isHidden = method === "none";
pathMarker.x1 = lambda;
const byDegree = ui.errorAxisSelect.value === "degree";
errorMarker.isHidden = method === "none" && !byDegree;
errorMarker.isEditable = !byDegree; // drag to change λ; the degree has its own slider
errorMarker.x1 = byDegree ? degree : lambda;
const nonZero = model.coefficients.filter((b) => Math.abs(b) > 1e-12).length;
const cv = crossValidate(data.trainX, data.trainY, degree, method, lambda).rmse;
ui.readout.textContent =
`Training RMSE ${rmse(model.predict(data.trainX), data.trainY).toFixed(3)} · ` +
`5-fold CV RMSE ${cv.toFixed(3)} · Test RMSE ${rmse(model.predict(data.testX), data.testY).toFixed(3)} · ` +
`Non-zero coefficients ${nonZero} of ${degree} · Noise σ = ${noise.toFixed(2)}`;
}

// New λ: the error-vs-degree curves depend on λ, so they are refitted too (15 degrees × 6 fits)
function onLambdaChanged() {
if (ui.errorAxisSelect.value === "degree" && ui.methodSelect.value !== "none") onErrorChartChanged();
else updateFit();
}

// Set λ from a chart marker or the CV button, keeping the slider in step
function setLambda(lambda) {
const exponent = Math.max(-4, Math.min(2, Math.log10(lambda)));
ui.lambdaInput.value = String(Math.round(exponent * 20) / 20);
onLambdaChanged();
}

ui.methodSelect.addEventListener("change", () => {
if (ui.methodSelect.value === "none" && ui.errorAxisSelect.value === "lambda") ui.errorAxisSelect.value = "degree";
onModelChanged();
});
ui.degreeInput.addEventListener("input", onModelChanged);
ui.lambdaInput.addEventListener("input", onLambdaChanged);
ui.noiseInput.addEventListener("input", onDataChanged);
ui.errorAxisSelect.addEventListener("change", onErrorChartChanged);
ui.resampleButton.addEventListener("click", () => {
seed = (seed * 48271) % 2147483647;
onDataChanged();
});
ui.bestButton.addEventListener("click", () => {
if (ui.methodSelect.value === "none") ui.methodSelect.value = "ridge";
ui.errorAxisSelect.value = "lambda";
onModelChanged();
const best = sweep.reduce((a, b) => (b.cv < a.cv ? b : a)); // the λ with the lowest cross-validation error
setLambda(best.lambda);
});
pathMarker.dragDelta.subscribe(() => setLambda(pathMarker.x1));
errorMarker.dragDelta.subscribe(() => {
if (ui.errorAxisSelect.value === "lambda") setLambda(errorMarker.x1);
});
onDataChanged();

Key points:

  • λ runs on a LogarithmicAxis with logBase: 10, so the grid of λ values, spaced evenly in powers of ten, plots evenly. Its labelProvider.formatLabel is overridden to print 0.01, 1 or 1e-3 rather than the default format.
  • Each coefficient path, the fitted curve and each error curve is a FastLineRenderableSeries over an XyDataSeries; the training points are an XyScatterRenderableSeries with an EllipsePointMarker.
  • The current λ is a VerticalLineAnnotation with isEditable: true; its dragDelta event sets the slider and refits the model.
  • The fitted curve's legend name, set through dataSeriesName, shows the method, degree and λ, so a screenshot records the settings.

See it in the demo app: JavaScript line chart · React line chart · Angular line chart, and for the training points, JavaScript scatter chart · React scatter chart · Angular scatter chart.

Go deeper: SciChart.js line series documentation, the logarithmic axis documentation for the λ axis, the residual plot guide for checking the chosen model, and the ROC curve guide for evaluating classifiers.

Frequently asked questions​

What is the difference between ridge and lasso regression?​

Both add a penalty on the size of the coefficients to the least squares fit. Ridge regression penalises the sum of the squared coefficients (an L2 penalty), which shrinks every coefficient towards zero but keeps them all in the model. Lasso regression penalises the sum of their absolute values (an L1 penalty), which shrinks them too but sets some exactly to zero, so it also selects features. Ridge copes better with groups of correlated features; lasso gives a smaller model that is easier to explain.

What is the difference between overfitting and underfitting?​

An underfitted model is too simple to capture the pattern, so it makes large errors on the training data and on new data alike: a straight line through curved data is the classic case. An overfitted model is so flexible that it learns the noise in the training data as well as the pattern, so its training error is very low but its error on new data is much higher. Regularization, fewer features and more data all reduce overfitting.

What does lambda do in ridge and lasso regression?​

Lambda sets how strongly the penalty counts against the fit. At lambda = 0 the model is ordinary least squares. As lambda grows, the coefficients shrink towards zero, the fitted curve becomes smoother, the training error rises and the variance of the model falls. Very large values shrink everything and the model underfits. The best value is usually chosen by cross-validation, and it depends on how the penalty is scaled, so values are not comparable between libraries.

Why does lasso set coefficients to zero but ridge does not?​

The L1 penalty has a kink at zero. For a single coefficient, the lasso solution is the least squares value moved towards zero by a fixed amount, and it stops at exactly zero if the value is smaller than that amount. Ridge divides each value by a factor greater than one, which never reaches zero. Geometrically, the lasso constraint is a diamond with corners on the axes, and the error contours usually first touch it at a corner, where some coefficients are zero; the ridge constraint is a circle with no corners.

How do you choose lambda with cross-validation?​

Split the training data into k folds, often 5 or 10. For each value on a grid of lambdas, fit the model k times, each time leaving one fold out and measuring the error on it, and average the k errors. Plot the average against lambda on a log scale: this validation curve is usually U-shaped. Pick the lambda at its minimum, or the largest lambda within one standard error of the minimum for a simpler model, then refit on all the training data and check it once on a held-out test set.

How do I plot ridge and lasso coefficient paths in JavaScript?​

Standardise the features, then fit the model at each lambda on a grid spaced evenly on a log scale, from a value that shrinks every coefficient to near zero down to a very small one. Store each coefficient as a series of (lambda, value) points and draw one line per coefficient on a logarithmic x-axis. SciChart.js does this with FastLineRenderableSeries, XyDataSeries and LogarithmicAxis, in plain JavaScript, React or Angular, and a VerticalLineAnnotation marks the chosen lambda.

Sources​