Skip to content
AI360XpertBeta
Playgrounds

Supervised Learning

Ridge & Lasso Regularisation

A coefficient penalty changes the fitted curve; its benefit on new observations must be measured.

Guided steps 1 / 5

Stage 1 of 5: 1. Eight powers, sixteen points

One fitted polynomial, common observations

ridge at lambda 0.0031622776601683794. Training MSE 0.23922968359365607. Current fit: 0 exact zeros; 8 coefficients above 0.000001. Solver direct solve; KKT residual 1.8370721610594387e-15.

Axes rescale to include the current 81 sampled predictions and all observations. Lines join exact samples; behaviour between samples is not certified. Dashed reference is the known noiseless generator.

Training #0: prediction 1.2519270446194664; observed 1.229581353101535; residual -0.02234569151793142; squared 0.0004993299294145522.

Signed coefficients in training-SD units

Log strength -2.5, lambda 0.0031622776601683794. Current fit: 0 exact zeros; 8 coefficients above 0.000001. Inspected power 1: standardised 2.4498844467912293, raw 2.6572727732261323.

Axes rescale with the current coefficients. * = present in the generator; hatch = absent. This is not a feature-recovery certificate. Neutral diamond marks inspection.

Top inset: move the fitting penalty on its own log10(λ) axis. Lower chart: coefficients by polynomial power. Zero has no logarithmic handle; use the separate zero-penalty control.

  • Training observation
  • Validation observation
  • Known generating function
  • Fitted polynomial
  • Generator uses this power (*)
  • Generator omits this power
  • Selected vertical residual
Adjust parameters

Logarithmic track; the displayed value is lambda. Zero penalty is a separate control.

Selected x^1: standardised 2.4498844467912293; raw 2.6572727732261323 target units per x^1 unit.

Training MSE0.2392Training MSE: 0.2392
Active coefficients8Active coefficients: 8

Current fit: 0 exact zeros; 8 coefficients above 0.000001.

normal equations: direct solve; sweeps 0; maximum KKT residual 1.8370721610594387e-15. No numerical divergence is claimed.

What changes when a coefficient costs more?

The model fits eight standardised powers of x. Move strength and watch the fitted curve and coefficients together. Asterisks identify the two powers used by the known generator, not a promise of feature recovery.

  1. Training-only scaling
  2. Penalised fit
  3. Predictions
  4. Exploratory validation
Penalised fit

A fit balancing training loss with a cost on its coefficients.

Check this stage

Check your understanding

A coefficient penalty changes the fitted polynomial. Move its strength, compare ridge and lasso on identical observations, and inspect the training cost alongside exploratory validation error.

Change the fit, then judge it

Move Penalty strength or drag the neutral diamond along its logarithmic axis. Both refit the eight polynomial features x,x2,…,x8x, x^2, \ldots, x^8 on the same sixteen training observations. The known generator is 2x−1.5x32x-1.5x^3 plus Gaussian target noise with standard deviation 0.6. Asterisks identify its two nonzero powers; they do not promise that fitting recovers them. Inputs are evenly spaced, not randomly sampled.

Training circles and validation diamonds have separate noise draws. The forty validation labels never enter fitting or solver decisions. Repeatedly choosing a setting using their score makes it exploratory validation. There is no untouched final test in this lab. A training–validation gap alone does not prove overfitting or measure mathematical variance.

Which objective is fitted?

For standardised features ziz_i, slopes ww, unpenalised intercept bb and n=16n=16:

J(w,b)=12n∑i(yi−b−zi⊤w)2+P(w).J(w,b)=\frac{1}{2n}\sum_i(y_i-b-z_i^\top w)^2+P(w).

Ridge uses P(w)=λ∑jwj2P(w)=\lambda\sum_jw_j^2; lasso uses P(w)=λ∑j∣wj∣P(w)=\lambda\sum_j|w_j|. No elastic-net mixture is fitted. The drawer separates half the unpenalised training MSE, L1 contribution, L2 contribution and total objective. Training and validation MSE omit the penalty. Compare objectives only under their stated settings; changing lambda changes the objective itself.

The same numeric lambda does not impose equal budgets under L1 and L2. In the scikit-learn summed-square ridge convention its alpha would equal 2nλ2n\lambda; the library lasso alpha matches this lab's lambda. A constrained norm radius is not the same number as penalised lambda, even when corresponding optima exist.

Select a training observation. Its amber dashed segment is the vertical residual, observed target minus fitted prediction. The native table retains every prediction, signed residual and squared residual. The plots rescale to the current sampled fit; 81 predictions are joined by straight segments. They do not certify extrema between sampled inputs. The coefficient diamond selects inspection; it does not set a weight.

Why scale and leave the intercept alone?

Training feature means and population standard deviations define zj=(xj−μj)/sjz_j=(x^j-\mu_j)/s_j. Validation uses that same transformation. Each standardised coefficient is in target units per training SD of its feature, holding the other features fixed. The norm is meaningful in this chosen basis; it is not a universal complexity score across arbitrary scales. Standardising does not remove correlation.

The raw slope is aj=wj/sja_j=w_j/s_j and raw intercept is braw=b−∑jwjμj/sjb_{\mathrm{raw}}=b-\sum_jw_j\mu_j/s_j. Both representations predict the same values. Centred training features leave b=yˉb=\bar y, which is never penalised here. Constant columns centre to zero and carry no fitted effect. Rank deficiency can leave non-unique slopes even when predictions are well defined.

Why can lasso produce exact zeros?

With every other coordinate fixed, cyclic coordinate descent computes a partial residual correlation ρj\rho_j and updates:

wj←S(ρj,λ)n−1∑izij2,S(ρ,λ)=sign⁡(ρ)max⁡(∣ρ∣−λ,0).w_j \leftarrow \frac{S(\rho_j,\lambda)}{n^{-1}\sum_i z_{ij}^2}, \qquad S(\rho,\lambda)=\operatorname{sign}(\rho)\max(|\rho|-\lambda,0).

A zero column stays zero. At a nonzero optimum the residual correlation equals λsign⁡(wj)\lambda\operatorname{sign}(w_j); at zero its magnitude can lie anywhere up to lambda. The displayed KKT residual measures departures from those conditions.

For a hand example, take z=[−1,1]z=[-1,1], y=[0,4]y=[0,4], intercept 2 and lambda 0.5. Ridge gives slope 1, predictions 1 and 3, MSE 1 and objective 0.5+0.5=10.5+0.5=1. Lasso gives slope 1.5, predictions 0.5 and 3.5, MSE 0.25 and objective 0.125+0.75=0.8750.125+0.75=0.875. These objectives use different penalties.

Positive ridge solves the normal equations numerically. Positive lasso starts at zero, visits coordinates in fixed order, and stops at maximum KKT residual 10−810^{-8} or 5,000 sweeps. A budget-limited result is labelled approximate, not converged. The separate Zero penalty control uses numerical minimum-norm least squares with a relative eigenvalue cutoff of 10−1210^{-12}; zero has no finite logarithmic position. No solve uses validation labels to decide when to stop.

Ridge does not generally select variables, but symmetry can give exact zero slopes. Nor must each ridge coefficient shrink monotonically with lambda. With duplicate features, lasso can have many equally good weight allocations; it need not choose exactly one. Sparse coefficients and low validation error do not establish causality or recovery of the generator.

Break the signal, then recover

In the final stage, Load excessive L1 preset raises the lasso penalty until every slope is exactly zero. The training mean survives. The threshold is the largest absolute training feature–centred-target correlation divided by n. This is a valid constant optimum, not divergence. Subsequent edits recompute its current diagnosis. Back to working restores the complete preceding experiment, including stage, penalty, inspection, guided/free mode and prediction.

On the fixed fixture, the positive grid has lasso validation MSE about 0.663 near lambda 0.045, versus ridge's grid minimum about 0.728. These measurements do not establish a universal winner or explain the difference solely by variable selection. The challenge asks for validation MSE below 0.700 with at least three coefficients above 10−610^{-6}; exact zeros and numerically active counts are distinct readouts. There is no noise-removal or data-changing shortcut.

Stages retain settings but earlier stages explicitly use ridge. Inspection does not change fitting or invalidate a prediction; mathematical edits and stage/mode changes do. Reset retains the stage, restores controls/inspection, clears guesses/recovery and returns to guided mode. Share reproduces guided display stage, settings and inspection on these fixed observations, excluding guesses, mode identity, progress and recovery. No resampling, playback or optimiser history is implied.

Sources and limits

The linear-model guide, Lasso reference and glmnet tutorial give objective and solver conventions. Lasso uniqueness explains correlated and duplicate features; common pitfalls explains training-only preprocessing. This small synthetic experiment measures neither population generalisation, distribution shift nor final-test performance.

Stage recap

  1. 1. Eight powers, sixteen points

    The model fits eight standardised powers of x. Move strength and watch the fitted curve and coefficients together. Asterisks identify the two powers used by the known generator, not a promise of feature recovery.

  2. 2. Judge it on unseen points

    The forty diamonds use independently generated target noise. Their labels never enter fitting. Exploring this score makes it validation, not a final test. A gap alone is not a bias–variance decomposition.

  3. 3. Ridge shrinks the norm (L2)

    Ridge minimises half the training MSE plus lambda times the squared standardised coefficient norm. The norm can shrink without each individual coefficient moving monotonically. Some ridge coefficients can be exactly zero by symmetry.

  4. 4. Lasso can switch coefficients off (L1)

    Lasso can create exact zeros through soft-thresholding. Compare the alternative penalty at the same numeric lambda on identical observations. Equal lambda does not mean equal penalty budgets or equal complexity.

  5. 5. Push it too far

    At sufficient lasso strength zero satisfies every slope subgradient condition. The intercept remains the training mean. This is a valid constant model; inspect its error rather than calling it divergence.

Reference

Objective
J = SSE/(2n) + L1 + L2. Ridge: L2 = lambda sum(w²). Lasso: L1 = lambda sum(|w|). No elastic-net mixture here.
Intercept
b = training mean(y) for centred training columns. It is not penalised.
Scaling
z_j = (x^j − training mean_j) / training SD_j. Raw slope = w_j/SD_j; raw intercept = b − sum(w_j mean_j/SD_j).
Lasso update
w_j = S(rho_j, lambda) / mean(z_j²), where S(rho,lambda) = sign(rho) max(|rho|−lambda,0).
Evaluation
Training and exploratory validation MSE omit the penalty. No untouched final test is computed.

Break it on purpose

Load excessive L1 strength: every slope coefficient becomes exactly zero and the model predicts the training mean. This is a valid constant fit, not numerical divergence. Reduce the penalty and compare exploratory validation MSE.