Phase 04 / Math & optimization
Regularization and honest validation
Revision v0.18.1 · Updated since your last visit. Review the changes; your progress is saved.
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.
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements-cpu.txtpy -3 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements-cpu.txtAfter activation, run the complete worked example from that same folder:
python phases/04-optimization/10-regularization-and-validation/code/main.py.\.venv\Scripts\python.exe phases/04-optimization/10-regularization-and-validation/code/main.pyFor 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.
Download this lesson’s notebook. Open it with a Python kernel using the course environment. Run cells from the top after restarting the kernel; experiments depend on earlier definitions.
For local Jupyter, first install the course requirements using the Local Python steps, then use your environment’s Python to start Jupyter:
python -m pip install jupyterlab
python -m jupyter lab.\.venv\Scripts\python.exe -m pip install jupyterlab
.\.venv\Scripts\python.exe -m jupyter labSelect the downloaded optimization-10.ipynb file in JupyterLab. The notebook contains reference solutions; make your prediction and attempt each practice task before opening them. Restart the kernel before changing logical device setup.
The worked reference for this lesson is CPU-validated. Some references explicitly configure logical CPU devices; setting JAX_PLATFORMS does not adapt them to a TPU. Follow the execution matrix and reviewed multi-host example before attempting a target run.
For accelerator preparation, study TPU setup, observed runtime receipts, checkpointed jobs and precision and retained traces. Current receipts cover bounded v5e1 launch, resume, and precision checks; four single-device Pallas cases; and a four-device v5e collective fixture. Each receipt is limited to its recorded source, environment, cases, and hardware. It does not qualify all lessons or TPU configurations. Cloud provisioning is optional for CPU learning.
Check: The regularized slope is ; 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.
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 be the training sample count and the penalty strength. We use mean squared error plus , without a factor of one half. Differentiating gives . 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, and , so and . Setting the stated derivative to zero with n=2 gives , hence . The mean and penalty conventions are explicit; changing either changes the numerical meaning of the same lambda.
Work through shrinkage by hand
Train a slope without a bias on inputs and targets . The data loss is , so the ridge solution is . At , it fits the training slope . At , it gives slope . Our deliberately constructed validation targets follow slope , 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 . 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 , use a diagonal penalty mask with entries . 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.
Training error and validation error select different penalties
Predict before looking: Does the smallest training error imply the best validation result?
Read the figure
The horizontal axis varies the ridge penalty . 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 , training error is zero and validation error is . At , training error rises to , but validation error falls to zero. Increasing the penalty to makes both errors . The validation curve therefore has a minimum between the extremes.
Connect it to the computation
The fitted weight is . The training targets favor slope , while the validation targets in this constructed example favor slope . 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 . 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
Open full-size figureDownload data and provenance
The notebook contains the data experiment, plotting code, and recorded figure output. Rerun it to test your changes.
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.
# 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 diagonalk, 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.
# 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 .
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 asparams.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.
# 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 , validation loss is , and the penalized objective is . 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.
# 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.pyAbout 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
# 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 ; 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.
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.
Sweep the penalty
# 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 ; training error prefers .
Regularization deliberately trades training fit against a preference for smaller weights.
Duplicate the training set
# 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.
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 and penalty , 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.
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 NotImplementedErrorReveal the 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 using inputs and a bias. Compare penalizing only the slope with penalizing both parameters at .
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- Fit constant targets using inputs and a bias. Compare penalizing only the slope with penalizing both parameters at .
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 .
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 NotImplementedErrorShow a hint
Use a diagonal mask .
Reveal reference solution and reasoning
# 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 and validation input is . 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 and validation input is . 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.
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 NotImplementedErrorShow a hint
Fit the mean on training data; do not refit it on validation data.
Reveal reference solution and reasoning
# 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.
Diagnose the result
If increasing 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.
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
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.
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.