Core Foundation · Local CPULaptop CPULesson 9 of 12 in Phase 04

Phase 04 / Math & optimization

Regularization and honest validation

Revision v0.18.1 ·

Lesson · about 75 minutes · CPU practice

Derive a ridge solution, distinguish data loss from penalized loss, and select a penalty using held-out data.

Phase study guide: preparation, milestones and project evidence

Before you start

Before this: Probability, likelihood, and stable losses
Hardware: CPU

Setup help: Python, notebook, or Cloud TPU VM

Use the tested CPU packages (the recorded environment uses Python 3.14.3). Other Python versions require separate checks. Hardware receipts apply only to their recorded source, environment, hardware, and cases; they do not qualify every lesson or TPU configuration. See the TPU performance and hardware evidence guide. The optional Cloud TPU specialization explains target-specific execution boundaries. Logical CPU devices practice partitioning; they do not simulate TPU performance.

Download the repository ZIP or use your existing checkout. Extract it and open a terminal in the folder containing requirements-cpu.txt. The beginner ZIP is separate; these lessons use the full repository folder.

macOS / Linux terminal · repository folder
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements-cpu.txt

PowerShell · repository folder
py -3 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements-cpu.txt

After activation, run the complete worked example from that same folder:

macOS / Linux terminal · activated environment
python phases/04-optimization/10-regularization-and-validation/code/main.py

PowerShell command · repository folder
.\.venv\Scripts\python.exe phases/04-optimization/10-regularization-and-validation/code/main.py

For an incremental build, create main.py in your own practice folder, append each build block in order, and run python main.py with this environment active. Keep that file separate from the downloaded reference solution.

Check: The regularized slope is 22; data loss and penalized objective are reported separately.

Revisit the guided CPU setup · Open 19: TPU Setup. Package instructions are CPU instructions; Windows and accelerator environments need their own validation.

Stage 1 of 5 · Understand the MechanismCore mental model, equations & visual walkthrough

What you will be able to do

  • Derive a ridge solution, distinguish data loss from penalized loss, and select a penalty using held-out data.
  • State the exact objective
  • Work through shrinkage by hand
  • Keep fitting, choosing and reporting separate
  • Choose which parameters to penalize

The problem

A model can fit the training data closely and still make poor predictions on new data. Can we trade a little training fit for a simpler model? We will make that tradeoff visible with a dataset small enough to solve by hand, while keeping the validation data separate from fitting.

The idea

Regularization changes which solutions training prefers. Validation helps choose settings using data that did not fit the model, and a final test estimates performance after those choices are fixed. Keeping these jobs separate makes the reported result interpretable.

Give each split one job

Imagine trying several penalty strengths. For each setting, fit weights on the training split, then score the frozen result on validation. Pick a setting using those validation results. Repeatedly using test performance to make that choice quietly turns the test into another validation set.

Preprocessing belongs inside the same boundary: fit means, scales and feature selection using training data only. Applying a transformation to validation is allowed; allowing validation to choose the transformation's fitted statistics changes the experiment.

The regularization plot may show training error improving while validation error worsens. That gap motivates model selection, but one small fixture does not prove a universal best penalty. Preserve split identities and the selection rule so another person can reconstruct the decision.

State the exact objective

Let nn be the training sample count and λ≥0\lambda\ge0 the penalty strength. We use mean squared error plus λ∥w∥22\lambda\|w\|_2^2, without a factor of one half. Differentiating gives 2XT(Xw−y)/n+2λw2X^\mathsf{T}(Xw-y)/n+2\lambda w. Setting it to zero gives the linear system below. Other conventions change the numerical meaning of the same penalty value, so copy the objective along with a reported hyperparameter.

For this fixture, X=(−1,1)X=(-1,1) and y=(−3,3)=3Xy=(-3,3)=3X, so XTX=2X^\mathsf{T}X=2 and XTy=6X^\mathsf{T}y=6. Setting the stated derivative to zero with n=2 gives 2(w−3)+2λw=02(w-3)+2\lambda w=0, hence w=3/(1+λ)w=3/(1+\lambda). The mean and penalty conventions are explicit; changing either changes the numerical meaning of the same lambda.

Lλ(w)=1n∥Xw−y∥22+λ∥w∥22,(XTX+nλI)w=XTyL_\lambda(w)=\frac1n\|Xw-y\|_2^2+\lambda\|w\|_2^2,\qquad (X^\mathsf{T}X+n\lambda I)w=X^\mathsf{T}y

Work through shrinkage by hand

Train a slope without a bias on inputs (−1,1)(-1,1) and targets (−3,3)(-3,3). The data loss is (w−3)2(w-3)^2, so the ridge solution is w=3/(1+λ)w=3/(1+\lambda). At λ=0\lambda=0, it fits the training slope 33. At λ=1/2\lambda=1/2, it gives slope 22. Our deliberately constructed validation targets follow slope 22, making the tradeoff easy to inspect. Real validation curves are noisier and do not guarantee that positive regularization helps.

Keep fitting, choosing and reporting separate

Fit weights on training examples for each candidate λ\lambda. Choose using validation prediction loss, not the training objective with its penalty. Validation targets must never enter the fit or preprocessing statistics. After many choices, validation itself can be overfit; a final untouched test set estimates the selected procedure. This tiny exercise has a training and validation split only, so its result is a demonstration, not a final generalization estimate.

Choose which parameters to penalize

A bias can represent the overall target level, so many models exclude it from weight regularization. For an augmented parameter vector (w,b)(w,b), use a diagonal penalty mask with entries (1,0)(1,0). Scaling a feature also changes the size of its coefficient, and therefore the penalty. Standardize using training statistics when that matches your modeling choice, then reuse those statistics unchanged for validation and inference. Ridge adds curvature in penalized directions; it cannot repair leaked data or a wrong target.

Read the figure

The horizontal axis varies the ridge penalty λ\lambda. For each penalty, the model is fitted again. The vertical axis shows mean squared prediction error on training and validation data; it does not include the penalty term.

At λ=0\lambda=0, training error is zero and validation error is 44. At λ=0.5\lambda=0.5, training error rises to 11, but validation error falls to zero. Increasing the penalty to 22 makes both errors 44. The validation curve therefore has a minimum between the extremes.

Connect it to the computation

The fitted weight is w=3/(1+λ)w=3/(1+\lambda). The training targets favor slope 33, while the validation targets in this constructed example favor slope 22. Moderate shrinkage moves the model toward the validation relationship; too much shrinkage moves it past that relationship and toward underfitting.

Select the penalty using the validation minimum, not the intersection of the curves or the smallest training error. Here that choice is 0.50.5. A zero validation error is a property of this tiny synthetic example, not a promise that regularization removes all error on real data.

Before selecting a penalty, predict how fitted slope 3/(1+lambda) compares with validation slope 2; validation error is smallest when these match.

Figure data and execution details

Recorded environment: JAX 0.9.2 · 1 CPU device

The notebook contains the data experiment, plotting code, and recorded figure output. Rerun it to test your changes.

Stage 2 of 5 · Build & Run the ReferenceStep-by-step code construction & verified execution output

Your build: Create a separate main.py in your practice folder. Append each block in order and run python main.py in the lesson environment. The downloaded script is the complete reference, so keep it separate from your attempt.

1 Create separate training and validation examples

Create main.py. Keep validation arrays separate from the solver inputs.

main.py · append build step 1
# Step 1 — Create separate training and validation examples: The helper solves the explicitly stated mean-loss convention.
import jax
import jax.numpy as jnp
X = jnp.array([[-1.0], [1.0]])
y = jnp.array([-3.0, 3.0])
Xv = jnp.array([[-2.0], [2.0]])
yv = jnp.array([-4.0, 4.0])

def ridge(X, y, lam):
    return jnp.linalg.solve(X.T @ X + X.shape[0] * lam * jnp.eye(X.shape[1]), X.T @ y)

def mse(w, X, y):
    return jnp.mean((X @ w - y) ** 2)

The helper solves the explicitly stated mean-loss convention. We use a small well-conditioned system here; this is not a general replacement for robust least-squares algorithms.

Explain the APIs in this step
  • jnp.array(values, dtype=...): Constructs a JAX array from Python/NumPy values.
  • jnp.eye(N, M=None, k=0, dtype=...): Creates a square or rectangular identity array: ones lie on diagonal k, and other entries are zero.
  • jnp.mean(x, axis=..., keepdims=...): Averages JAX array values along the selected axis.

2 Verify the penalized optimum

Append the hand solution and its gradient check.

main.py · append build step 2
# Step 2 — Verify the penalized optimum: The data gradient and penalty gradient cancel at w=2.
lam = 0.5
w = ridge(X, y, lam)
objective = lambda w: mse(w, X, y) + lam * jnp.dot(w, w)
assert jnp.allclose(w, jnp.array([2.0]), atol=1e-06)
assert jnp.allclose(jax.grad(objective)(w), jnp.zeros(1), atol=1e-06)

The data gradient and penalty gradient cancel at w=2w=2.

Explain the APIs in this step
  • jnp.allclose(actual, expected, rtol=..., atol=...): Returns a JAX boolean scalar indicating whether corresponding values are within the requested tolerance.
  • jnp.array(values, dtype=...): Constructs a JAX array from Python/NumPy values.
  • jax.grad(loss_fn)(params, ...): Transforms a scalar-output function into one returning the gradient PyTree with the same structure as params.
  • jnp.zeros(shape, dtype=...): Creates a JAX array of the requested shape filled with zeros.

3 Separate the quantities you report

Append the three losses and run python main.py.

main.py · append build step 3
# Step 3 — Separate the quantities you report
train = mse(w, X, y)
validation = mse(w, Xv, yv)
penalized = objective(w)
assert jnp.allclose(jnp.array([train, validation, penalized]), jnp.array([1.0, 0.0, 3.0]))
print('train / validation / objective:', train, validation, penalized)

Training prediction loss is 11, validation loss is 00, and the penalized objective is 33. They answer different questions.

Explain the APIs in this step
  • jnp.allclose(actual, expected, rtol=..., atol=...): Returns a JAX boolean scalar indicating whether corresponding values are within the requested tolerance.
  • jnp.array(values, dtype=...): Constructs a JAX array from Python/NumPy values.
View the cumulative build in main.py

These blocks append in order to your separate practice file.

main.py · cumulative Python build
# Step 1 — Create separate training and validation examples: The helper solves the explicitly stated mean-loss convention.
import jax
import jax.numpy as jnp
X = jnp.array([[-1.0], [1.0]])
y = jnp.array([-3.0, 3.0])
Xv = jnp.array([[-2.0], [2.0]])
yv = jnp.array([-4.0, 4.0])

def ridge(X, y, lam):
    return jnp.linalg.solve(X.T @ X + X.shape[0] * lam * jnp.eye(X.shape[1]), X.T @ y)

def mse(w, X, y):
    return jnp.mean((X @ w - y) ** 2)

# Step 2 — Verify the penalized optimum: The data gradient and penalty gradient cancel at w=2.
lam = 0.5
w = ridge(X, y, lam)
objective = lambda w: mse(w, X, y) + lam * jnp.dot(w, w)
assert jnp.allclose(w, jnp.array([2.0]), atol=1e-06)
assert jnp.allclose(jax.grad(objective)(w), jnp.zeros(1), atol=1e-06)

# Step 3 — Separate the quantities you report
train = mse(w, X, y)
validation = mse(w, Xv, yv)
penalized = objective(w)
assert jnp.allclose(jnp.array([train, validation, penalized]), jnp.array([1.0, 0.0, 3.0]))
print('train / validation / objective:', train, validation, penalized)

Run the example

python3 phases/04-optimization/10-regularization-and-validation/code/main.py
About this command

This shortcut uses an activated macOS/Linux course environment in the repository folder. For Windows, use the explicit interpreter command in “Setup help” above. The script includes worked examples and reference solutions.

Inspect the complete assembled example
main.py · complete Python example
# Step 1 — Create separate training and validation examples: The helper solves the explicitly stated mean-loss convention.
import jax
import jax.numpy as jnp
X = jnp.array([[-1.0], [1.0]])
y = jnp.array([-3.0, 3.0])
Xv = jnp.array([[-2.0], [2.0]])
yv = jnp.array([-4.0, 4.0])

def ridge(X, y, lam):
    return jnp.linalg.solve(X.T @ X + X.shape[0] * lam * jnp.eye(X.shape[1]), X.T @ y)

def mse(w, X, y):
    return jnp.mean((X @ w - y) ** 2)

# Step 2 — Verify the penalized optimum: The data gradient and penalty gradient cancel at w=2.
lam = 0.5
w = ridge(X, y, lam)
objective = lambda w: mse(w, X, y) + lam * jnp.dot(w, w)
assert jnp.allclose(w, jnp.array([2.0]), atol=1e-06)
assert jnp.allclose(jax.grad(objective)(w), jnp.zeros(1), atol=1e-06)

# Step 3 — Separate the quantities you report
train = mse(w, X, y)
validation = mse(w, Xv, yv)
penalized = objective(w)
assert jnp.allclose(jnp.array([train, validation, penalized]), jnp.array([1.0, 0.0, 3.0]))
print('train / validation / objective:', train, validation, penalized)

Expected result: The regularized slope is 22; data loss and penalized objective are reported separately.

Recorded output and runtime details

Reference output captured from executing the complete lesson script (code/main.py) and its assertions in the course CPU environment.

2026-10-27T17:03:52.414138+00:00 · Python 3.14.3 · JAX 0.9.2 · 1 CPU device

train / validation / objective: 1.0 0.0 3.0
train / validation / objective: 1.0 0.0 3.0
penalty / train / validation: [0.  0.5 2. ] [0. 1. 4.] [4. 0. 4.]
PASS: optimization-10

Download execution record · The notebook includes executed cells and figure outputs. Compare your run with these values; timings depend on the machine.

Stage 3 of 5 · Controlled ExperimentsPredict before running & test boundary conditions

Sweep the penalty

Sweep the penalty · Python experiment
# Experiment — Sweep the penalty
candidates = jnp.array([0.0, 0.5, 2.0])
fits = jnp.stack([ridge(X, y, float(a)) for a in candidates])
training = jnp.array([mse(a, X, y) for a in fits])
validation = jnp.array([mse(a, Xv, yv) for a in fits])
assert jnp.allclose(fits[:, 0], jnp.array([3.0, 2.0, 1.0]))
assert jnp.allclose(training, jnp.array([0.0, 1.0, 4.0]))
assert jnp.allclose(validation, jnp.array([4.0, 0.0, 4.0]))
assert int(jnp.argmin(training)) != int(jnp.argmin(validation))
print('penalty / train / validation:', candidates, training, validation)

Expected: Validation selects λ=0.5\lambda=0.5; training error prefers λ=0\lambda=0.

Regularization deliberately trades training fit against a preference for smaller weights.

Duplicate the training set

Duplicate the training set · Python experiment
# Experiment — Duplicate the training set
repeat = ridge(jnp.tile(X, (2, 1)), jnp.tile(y, 2), lam)
assert jnp.allclose(repeat, w, atol=1e-06)

Expected: The weights stay fixed.

Using a mean data loss keeps the penalty tradeoff unchanged under exact dataset duplication.

Stage 4 of 5 · Hands-On Exercise & CheckpointModify the code yourself, solve transfer tasks & test your understanding
Hands-On Exercise · Modify & Verify Run in the declared lesson environment

Make it yours

Where to put your code: Modify your own main.py, or use the Make it yours cell in your downloaded notebook. Run your attempt in the declared environment and verify your prediction before opening the reference solution.

For a target slope of 44 and penalty λ=1\lambda=1, derive the fitted slope and verify its gradient.

Show a writing guide and starter scaffold

How to write this exercise code

Learner-only inputs, outputs, checks and hints

Inputs

  • Training features, targets, and a nonnegative penalty.

Outputs

  • Fitted coefficients and predictions on supplied rows.

Invariants to check

  • Only designated coefficients are penalized; preprocessing statistics come from training data alone.

Hints

  • Separate the intercept from the penalized slope.
  • Compare validation transforms using the training-only statistics.
Your attempt · complete the TODOs
import jax.numpy as jnp

def ridge_fit(features, targets, penalty):
    """Fitted coefficients and predictions on supplied rows."""
    # TODO: Fit the stated penalized objective while separating intercept penalty and training-only preprocessing.
    raise NotImplementedError
Reveal the reference solution
Reference solution
# Exercise solution
y4 = jnp.array([-4.0, 4.0])
w4 = ridge(X, y4, 1.0)
assert jnp.allclose(w4, jnp.array([2.0]))
assert jnp.allclose(jax.grad(lambda z: mse(z, X, y4) + jnp.dot(z, z))(w4), jnp.zeros(1), atol=1e-06)

Do not accidentally shrink the intercept

Transfer / diagnosis

Fit constant targets (5,5,5)(5,5,5) using inputs (−1,0,1)(-1,0,1) and a bias. Compare penalizing only the slope with penalizing both parameters at λ=1\lambda=1.

Show a writing guide and starter scaffold

How to write this practice solution

Learner-only inputs, outputs, checks and hints

Inputs

  • Fit constant targets (5,5,5)(5,5,5) using inputs (−1,0,1)(-1,0,1) and a bias. Compare penalizing only the slope with penalizing both parameters at λ=1\lambda=1.

Outputs

  • Two fitted parameter sets with a prediction comparison.

Invariants to check

  • The intercept penalty choice is explicit and the unpenalized fit uses training rows only.

Hints

  • Use a diagonal mask diag⁡(1,0)\operatorname{diag}(1,0).
Your attempt · complete the TODOs
import jax.numpy as jnp

def practice_do_not_accidentally_shrink_the_intercept(features, targets):
    """Implement the do not accidentally shrink the intercept check."""
    # TODO: Fit the constant target data with slope-only and all-parameter penalties and compare both parameter pairs.
    raise NotImplementedError
Show a hint

Use a diagonal mask diag⁡(1,0)\operatorname{diag}(1,0).

Reveal reference solution and reasoning
Do not accidentally shrink the intercept · Python solution
# Do not accidentally shrink the intercept (Transfer / diagnosis)
x = jnp.array([-1.0, 0.0, 1.0])
A = jnp.stack([x, jnp.ones_like(x)], axis=1)
target = jnp.full((3,), 5.0)
mask = jnp.diag(jnp.array([1.0, 0.0]))
correct = jnp.linalg.solve(A.T @ A + 3 * mask, A.T @ target)
all_penalized = ridge(A, target, 1.0)
assert jnp.allclose(correct, jnp.array([0.0, 5.0]))
assert jnp.allclose(all_penalized, jnp.array([0.0, 2.5]))

The mask expresses a modeling choice: shrink feature effects while preserving the constant target level.

Catch preprocessing leakage

Transfer / diagnosis

Training inputs are (0,2)(0,2) and validation input is 100100. Compare training-only centering with centering all inputs together. Which can be reused for a truly unseen example?

Show a writing guide and starter scaffold

How to write this practice solution

Learner-only inputs, outputs, checks and hints

Inputs

  • Training inputs are (0,2)(0,2) and validation input is 100100. Compare training-only centering with centering all inputs together. Which can be reused for a truly unseen example?

Outputs

  • Both centers and the transformed unseen example under the training-only center.

Invariants to check

  • Validation data does not influence preprocessing statistics used for fitting.

Hints

  • Fit the mean on training data; do not refit it on validation data.
Your attempt · complete the TODOs
import jax.numpy as jnp

def practice_catch_preprocessing_leakage(train_features, validation_features):
    """Implement the catch preprocessing leakage check."""
    # TODO: Compute the center from training inputs alone and compare it with a center that includes the held-out value.
    raise NotImplementedError
Show a hint

Fit the mean on training data; do not refit it on validation data.

Reveal reference solution and reasoning
Catch preprocessing leakage · Python solution
# Catch preprocessing leakage (Transfer / diagnosis): Validation data must not influence fitted preprocessing.
train_x = jnp.array([0.0, 2.0])
val_x = jnp.array([100.0])
train_mean = jnp.mean(train_x)
leaked_mean = jnp.mean(jnp.concatenate([train_x, val_x]))
assert jnp.allclose(val_x - train_mean, jnp.array([99.0]))
assert not jnp.allclose(train_mean, leaked_mean)
assert jnp.allclose(jnp.mean(train_x - train_mean), 0.0)

Validation data must not influence fitted preprocessing. Reusing training statistics preserves the meaning of held-out evaluation.

Check your understanding

Which loss should select the penalty in this exercise?

Choose one answer

Diagnose the result

If increasing λ\lambda improves the penalized objective but worsens predictions, check which quantity is being compared. Inspect the mean-versus-sum convention, bias mask, feature units and where preprocessing statistics were fitted.

Stage 5 of 5 · Keep Your EvidenceRecord your verification receipt & carry takeaways forward

Carry forward

  • Regularization deliberately trades training fit against a preference for smaller weights.
  • Using a mean data loss keeps the penalty tradeoff unchanged under exact dataset duplication.

Keep your evidence

Download evidence template

Keep the ridge gradient/solve comparison, penalty sweep with separate train/validation losses, duplication check and bias-mask repair.

Save your modified code, its output, and an explanation of your prediction. Checkpoint answers and exercise evidence are tracked separately.

Saved in this browser. Export or back up your portfolio anytime in My learning.

Save work for this lesson

Reference execution: CPU validation only. This worked reference is validated on CPU. Accelerator compatibility requires a separate source review and target execution receipt. Use the execution matrix to review device selection and data ownership before adapting a separate target program. Execution matrix and target qualification.

Primary references