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.

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.
- 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 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.
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.
| Degree | Training RMSE | Test RMSE | Diagnosis |
|---|---|---|---|
| 1 | 0.74 | 0.56 | Underfitting: a straight line through a wave |
| 3 | 0.41 | 0.38 | Still too stiff |
| 6 | 0.20 | 0.30 | Close to the noise floor |
| 10 | 0.17 | 0.30 | Training error still falling, test error flat |
| 15 | 0.08 | 5.56 | Overfitting: 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:
- 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, , 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 . A regularized model minimises the RSS plus a penalty that grows with the coefficients:
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 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:
It has a closed-form solution. With the features centred, . When features are highly correlated, as , and are, 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:
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 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 ). Then each coefficient can be solved on its own from its least squares value :
- ridge: , the same proportional shrink for every coefficient;
- lasso: , the same fixed step towards zero, stopping at zero.
With λ = 1:
| Coefficient | Least squares | Ridge | Lasso |
|---|---|---|---|
| 3.0 | 1.5 | 2.5 | |
| 1.0 | 0.5 | 0.5 | |
| 0.4 | 0.2 | 0 |
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.
- 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 , 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 term is non-zero at λ = 10, and and 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:
- Split the training data into k folds, often 5 or 10.
- 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.
- Average the k errors for each λ, and plot the average against λ. This is the validation curve.
- 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 and 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.
| Method | Penalty | Sets coefficients to zero? | Correlated features | Solution | Best when |
|---|---|---|---|---|---|
| Least squares | None | No | Unstable, large offsetting coefficients | Closed form | Few features, plenty of data, no collinearity |
| Ridge (L2) | No, shrinks all | Shares the weight across the group | Closed form | Many features that each matter a little; collinearity | |
| Lasso (L1) | Yes | Picks one, more or less at random | Iterative (coordinate descent, LARS) | A few features matter, and you want a small, explainable model | |
| Elastic net | Both | Yes | Keeps or drops the group together | Iterative | Many correlated features and you want selection |
| Fewer features or lower degree | Hard limit | Drops them by hand | Up to you | Closed form | You 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.
- JavaScript
- React
- Angular
// 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();
import { SciChartReact } from "scichart-react";
import {
SciChartSurface,
NumericAxis,
LogarithmicAxis,
FastLineRenderableSeries,
XyDataSeries,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} from "scichart";
const PATH_COLOURS = ["#EC5151", "#ECC051", "#72EC51", "#51ECD4", "#5194EC", "#B551EC", "#EC51EC"]; // one per feature
// Ridge coefficients for standardised features X and centred y: solve (XᵀX + λI) b = Xᵀy
const ridgeCoefficients = (X: number[][], y: number[], lambda: number) => {
const d = X[0].length;
const A = Array.from({ length: d }, (_, j) => [
...Array.from({ length: d }, (_, k) => X.reduce((s, row) => s + row[j] * row[k], 0) + (j === k ? lambda : 0)),
X.reduce((s, row, i) => s + row[j] * y[i], 0)
]);
for (let i = 0; i < d; i++) {
for (let r = 0; r < d; r++) {
if (r === i) continue;
const f = A[r][i] / A[i][i];
for (let c = i; c <= d; c++) A[r][c] -= f * A[i][c];
}
}
return A.map((row, j) => row[d] / row[j]);
};
// initChart builds the chart; SciChartReact creates it, sizes it and cleans it up
const initChart = async (rootElement: string | HTMLDivElement) => {
const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
theme: new SciChartJsNavyTheme()
});
sciChartSurface.xAxes.add(new LogarithmicAxis(wasmContext, { axisTitle: "λ", logBase: 10 }));
sciChartSurface.yAxes.add(new NumericAxis(wasmContext, { axisTitle: "Standardised coefficient" }));
const { X, y, featureNames } = getYourStandardisedData(); // features scaled to mean 0, sd 1; y centred
const lambdas = Array.from({ length: 61 }, (_, i) => 10 ** (-4 + i / 10)); // 0.0001 to 100
const fits = lambdas.map((lambda) => ridgeCoefficients(X, y, lambda));
featureNames.forEach((name, j) => {
sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { xValues: lambdas, yValues: fits.map((b) => b[j]), dataSeriesName: name }),
stroke: PATH_COLOURS[j % PATH_COLOURS.length],
strokeThickness: 2
})
);
});
sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true }),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
return { sciChartSurface };
};
export const RidgePathChart = () => (
<SciChartReact initChart={initChart} style={{ width: "100%", height: 450 }} />
);
import { Component } from "@angular/core";
import { ScichartAngularComponent } from "scichart-angular";
import {
SciChartSurface,
NumericAxis,
LogarithmicAxis,
FastLineRenderableSeries,
XyDataSeries,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} from "scichart";
const PATH_COLOURS = ["#EC5151", "#ECC051", "#72EC51", "#51ECD4", "#5194EC", "#B551EC", "#EC51EC"]; // one per feature
// Ridge coefficients for standardised features X and centred y: solve (XᵀX + λI) b = Xᵀy
const ridgeCoefficients = (X: number[][], y: number[], lambda: number) => {
const d = X[0].length;
const A = Array.from({ length: d }, (_, j) => [
...Array.from({ length: d }, (_, k) => X.reduce((s, row) => s + row[j] * row[k], 0) + (j === k ? lambda : 0)),
X.reduce((s, row, i) => s + row[j] * y[i], 0)
]);
for (let i = 0; i < d; i++) {
for (let r = 0; r < d; r++) {
if (r === i) continue;
const f = A[r][i] / A[i][i];
for (let c = i; c <= d; c++) A[r][c] -= f * A[i][c];
}
}
return A.map((row, j) => row[d] / row[j]);
};
@Component({
selector: "app-ridge-path-chart",
standalone: true,
imports: [ScichartAngularComponent],
template: `<scichart-angular [initChart]="initChart" style="display: block; width: 100%; height: 450px"></scichart-angular>`
})
export class RidgePathChartComponent {
// initChart builds the chart; scichart-angular creates it, sizes it and cleans it up
initChart = async (rootElement: string | HTMLDivElement) => {
const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
theme: new SciChartJsNavyTheme()
});
sciChartSurface.xAxes.add(new LogarithmicAxis(wasmContext, { axisTitle: "λ", logBase: 10 }));
sciChartSurface.yAxes.add(new NumericAxis(wasmContext, { axisTitle: "Standardised coefficient" }));
const { X, y, featureNames } = getYourStandardisedData(); // features scaled to mean 0, sd 1; y centred
const lambdas = Array.from({ length: 61 }, (_, i) => 10 ** (-4 + i / 10)); // 0.0001 to 100
const fits = lambdas.map((lambda) => ridgeCoefficients(X, y, lambda));
featureNames.forEach((name, j) => {
sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { xValues: lambdas, yValues: fits.map((b) => b[j]), dataSeriesName: name }),
stroke: PATH_COLOURS[j % PATH_COLOURS.length],
strokeThickness: 2
})
);
});
sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true }),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
return { sciChartSurface };
};
}
Key points:
- λ runs on a
LogarithmicAxiswithlogBase: 10, so the grid of λ values, spaced evenly in powers of ten, plots evenly. ItslabelProvider.formatLabelis 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
FastLineRenderableSeriesover anXyDataSeries; the training points are anXyScatterRenderableSerieswith anEllipsePointMarker. - The current λ is a
VerticalLineAnnotationwithisEditable: true; itsdragDeltaevent 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
- Hoerl, A. E. and Kennard, R. W. (1970), Ridge regression: biased estimation for nonorthogonal problems. Technometrics, 12(1), 55–67.
- Tibshirani, R. (1996), Regression shrinkage and selection via the lasso. Journal of the Royal Statistical Society, Series B, 58(1), 267–288.
- Zou, H. and Hastie, T. (2005), Regularization and variable selection via the elastic net. Journal of the Royal Statistical Society, Series B, 67(2), 301–320.
- Hastie, T., Tibshirani, R. and Friedman, J. (2009), The Elements of Statistical Learning, 2nd edition, Springer. Ridge and lasso (section 3.4), the bias–variance decomposition (7.3), cross-validation and the one-standard-error rule (7.10).
- Friedman, J., Hastie, T. and Tibshirani, R. (2010), Regularization paths for generalized linear models via coordinate descent. Journal of Statistical Software, 33(1), 1–22.
- Lee, H., Battle, A., Raina, R. and Ng, A. Y. (2007), Efficient sparse coding algorithms. Advances in Neural Information Processing Systems 19. The feature-sign search the demo uses to finish each lasso fit exactly.
- Loshchilov, I. and Hutter, F. (2019), Decoupled weight decay regularization. International Conference on Learning Representations (ICLR 2019). Why weight decay and an L2 penalty differ under Adam.
- scikit-learn, Linear models: ridge, lasso and elastic net, for how one widely used library scales the penalty.