Phase 11 / Probabilistic modeling
Build a Bayesian regression
Revision v0.18.1 · Updated since your last visit. Review the changes; your progress is saved.
Lesson · about 110 minutes · CPU practice
State the prior, likelihood and observation-noise assumptions Derive posterior precision and check a closed-form special case
Phase study guide: preparation, milestones and project evidence
Before you start
Before this: Distributions and sampling
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/11-probability/02-build-a-bayesian-regression/code/main.py.\.venv\Scripts\python.exe phases/11-probability/02-build-a-bayesian-regression/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 probability-02.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 posterior mean is approximately . Latent variances at inputs are approximately ; observation variances are each larger by .
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
- State the prior, likelihood and observation-noise assumptions
- Derive posterior precision and check a closed-form special case
- Compute latent and observation predictive variances separately
- Demonstrate prior strength and extrapolation effects
The problem
You have three noisy measurements and want to predict at a new input. A fitted line gives one answer, but how uncertain should that answer be? We will write a prior, combine it with a likelihood, solve the posterior exactly, and separate uncertainty about the line from noise in a new observation. This exact answer will become our reference when we build an approximate sampler.
The idea
Bayesian regression represents uncertainty about parameters and propagates it to predictions. A latent-function prediction and a future noisy observation are different random quantities, so their intervals generally have different widths.
Separate uncertainty about the function from observation noise
For features , posterior parameter covariance gives latent predictive variance . If independent observation noise has variance , a new observation has variance . Name each term before combining them.
Moving away from well-observed feature combinations can increase parameter-related uncertainty. It does not require the assumed observation-noise variance to change. Plot the posterior mean with separately labeled latent and observation bands to make this distinction visible.
The saved spread curves show how uncertainty varies with the input. They are conditional on the model, prior and noise assumptions. Check held-out behavior and model adequacy instead of reading any narrow posterior band as a guarantee.
State what is random
The features are fixed inputs. We treat the intercept and slope as uncertain, and condition on the observed targets. The prior scale expresses uncertainty about each weight before seeing these targets; it is not the sensor noise. The noise scale describes repeated readings around the same latent line. We deliberately assume it known. Learning that scale would remove this exact two-parameter shortcut unless we used a richer conjugate model.
Combine information through precision
Precision is inverse covariance: larger precision means less uncertainty. The prior contributes ; the observations contribute . The linear term is . Completing the square gives a linear system for the posterior mean. This resembles ridge regression because the posterior mode and mean coincide for this Gaussian model. That equivalence does not turn every regularized optimizer into a complete uncertainty model.
Check the special case by hand
The inputs are , so their sum is zero and . The targets give . Adding prior precision gives diagonal entries and . Therefore and . These rational numbers provide an independent oracle; comparing two calls to the same posterior function would not.
Two uncertainty bands answer two questions
At a design row , the uncertain latent line value has variance . A new target adds independent observation variance . At input zero the latent variance is , whereas the observation variance is . At input two, the slope contribution increases latent variance to about . A nominal Gaussian interval is conditional on this model and known noise scale; it is not proof that future real observations achieve nominal coverage.
Use a tiny exact model as an inference test
The next lesson compares approximate samples with this kind of known answer. This is a useful engineering habit: test an inference mechanism on a model you can solve before trusting it on one you cannot. Our design is synthetic and unusually well conditioned. Retain the prior, noise assumption and extrapolation range with your result; a narrow posterior can be confidently wrong when the likelihood is wrong.
Prediction uncertainty grows away from the observed center
Predict before looking: Will an observation interval be wider or narrower than an interval for the latent line?
Read the figure
The horizontal axis is input value, and the vertical axis is predictive standard deviation in target units. The lower curve is uncertainty in the latent line; the upper curve adds the assumed unit observation-noise variance before taking the square root. At input zero, the executed model gives standard deviations about and . At input two, they are about 1.444 and 1.757 because slope uncertainty grows away from the centered training inputs.
Connect it to the computation
The curves come from the exact Gaussian posterior for fixed inputs , prior scale 2 and known noise scale 1. Variances add before taking the square root; observation noise is not added as a standard deviation. If we changed the assumed noise scale, only the upper predictive variance would receive that additional noise term directly, while refitting would also change the posterior covariance. These are conditional model quantities, not empirical coverage.
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 Construct a small linear model
Create a fresh main.py. The first feature is an intercept. Targets contain three deliberately simple synthetic observations; the known noise scale is an assumption.
# Step 1 — 1. Construct a small linear model: The design has three rows and two columns.
import numpy as np
import jax
import jax.numpy as jnp
X = jnp.array([[1.,-1.],[1.,0.],[1.,1.]])
y = jnp.array([-1.,1.,3.])
sigma, prior_scale = 1., 2.The design has three rows and two columns. The weight vector contains intercept then slope.
Explain the APIs in this step
jnp.array(values, dtype=...): Constructs a JAX array from Python/NumPy values.
2 Solve the posterior system
Append the conjugate update. Use a linear solve rather than writing an explicit matrix inverse for the mean.
# Step 2 — 2. Solve the posterior system
def posterior(X,y,sigma,prior_scale):
precision = jnp.eye(X.shape[1])/prior_scale**2 + X.T@X/sigma**2
mean = jnp.linalg.solve(precision,X.T@y/sigma**2)
covariance = jnp.linalg.solve(precision,jnp.eye(X.shape[1]))
return mean,covariance
mean,cov = posterior(X,y,sigma,prior_scale)
assert jnp.allclose(mean,jnp.array([12/13,16/9]),atol=1e-6)
assert jnp.allclose(cov,jnp.diag(jnp.array([4/13,4/9])),atol=1e-6)The independent fractions follow because centered inputs make the precision matrix diagonal.
Explain the APIs in this step
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.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.
3 Predict both the latent mean and a new observation
Append the prediction calculation, then run python main.py. Retain the two variance components separately.
# Step 3 — 3. Predict both the latent mean and a new observation
def predictive(design,mean,cov,sigma):
center = design@mean
latent_variance = jnp.einsum('ni,ij,nj->n',design,cov,design)
return center,latent_variance,latent_variance+sigma**2
query = jnp.array([[1.,0.],[1.,2.]])
center,latent_var,observation_var = predictive(query,mean,cov,sigma)
assert jnp.allclose(latent_var,jnp.array([4/13,4/13+16/9]),atol=1e-6)
assert jnp.allclose(observation_var-latent_var,1.)
print('posterior mean:',mean,'covariance:',cov)
print('latent variance:',latent_var,'observation variance:',observation_var)The variance at the extrapolation input is larger because slope uncertainty contributes more strongly there.
Explain the APIs in this step
jnp.array(values, dtype=...): Constructs a JAX array from Python/NumPy values.jnp.allclose(actual, expected, rtol=..., atol=...): Returns a JAX boolean scalar indicating whether corresponding values are within the requested tolerance.
View the cumulative build in main.py
These blocks append in order to your separate practice file.
# Step 1 — 1. Construct a small linear model: The design has three rows and two columns.
import numpy as np
import jax
import jax.numpy as jnp
X = jnp.array([[1.,-1.],[1.,0.],[1.,1.]])
y = jnp.array([-1.,1.,3.])
sigma, prior_scale = 1., 2.
# Step 2 — 2. Solve the posterior system
def posterior(X,y,sigma,prior_scale):
precision = jnp.eye(X.shape[1])/prior_scale**2 + X.T@X/sigma**2
mean = jnp.linalg.solve(precision,X.T@y/sigma**2)
covariance = jnp.linalg.solve(precision,jnp.eye(X.shape[1]))
return mean,covariance
mean,cov = posterior(X,y,sigma,prior_scale)
assert jnp.allclose(mean,jnp.array([12/13,16/9]),atol=1e-6)
assert jnp.allclose(cov,jnp.diag(jnp.array([4/13,4/9])),atol=1e-6)
# Step 3 — 3. Predict both the latent mean and a new observation
def predictive(design,mean,cov,sigma):
center = design@mean
latent_variance = jnp.einsum('ni,ij,nj->n',design,cov,design)
return center,latent_variance,latent_variance+sigma**2
query = jnp.array([[1.,0.],[1.,2.]])
center,latent_var,observation_var = predictive(query,mean,cov,sigma)
assert jnp.allclose(latent_var,jnp.array([4/13,4/13+16/9]),atol=1e-6)
assert jnp.allclose(observation_var-latent_var,1.)
print('posterior mean:',mean,'covariance:',cov)
print('latent variance:',latent_var,'observation variance:',observation_var)Run the example
python3 phases/11-probability/02-build-a-bayesian-regression/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 — 1. Construct a small linear model: The design has three rows and two columns.
import numpy as np
import jax
import jax.numpy as jnp
X = jnp.array([[1.,-1.],[1.,0.],[1.,1.]])
y = jnp.array([-1.,1.,3.])
sigma, prior_scale = 1., 2.
# Step 2 — 2. Solve the posterior system
def posterior(X,y,sigma,prior_scale):
precision = jnp.eye(X.shape[1])/prior_scale**2 + X.T@X/sigma**2
mean = jnp.linalg.solve(precision,X.T@y/sigma**2)
covariance = jnp.linalg.solve(precision,jnp.eye(X.shape[1]))
return mean,covariance
mean,cov = posterior(X,y,sigma,prior_scale)
assert jnp.allclose(mean,jnp.array([12/13,16/9]),atol=1e-6)
assert jnp.allclose(cov,jnp.diag(jnp.array([4/13,4/9])),atol=1e-6)
# Step 3 — 3. Predict both the latent mean and a new observation
def predictive(design,mean,cov,sigma):
center = design@mean
latent_variance = jnp.einsum('ni,ij,nj->n',design,cov,design)
return center,latent_variance,latent_variance+sigma**2
query = jnp.array([[1.,0.],[1.,2.]])
center,latent_var,observation_var = predictive(query,mean,cov,sigma)
assert jnp.allclose(latent_var,jnp.array([4/13,4/13+16/9]),atol=1e-6)
assert jnp.allclose(observation_var-latent_var,1.)
print('posterior mean:',mean,'covariance:',cov)
print('latent variance:',latent_var,'observation variance:',observation_var)Expected result: The posterior mean is approximately . Latent variances at inputs are approximately ; observation variances are each larger by .
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.
posterior mean: [0.923077 1.7777778] covariance: [[0.30769232 0. ]
[0. 0.44444445]]
latent variance: [0.30769232 2.0854702 ] observation variance: [1.3076923 3.0854702]
posterior mean: [0.923077 1.7777778] covariance: [[0.30769232 0. ]
[0. 0.44444445]]
latent variance: [0.30769232 2.0854702 ] observation variance: [1.3076923 3.0854702]
[0.16 0.23529412]
PASS: probability-02
Download execution record · The notebook includes executed cells and figure outputs. Compare your run with these values; timings depend on the machine.
Repeat independent observations
# Experiment — Repeat independent observations: The calculation treats rows as independent new evidence.
repeat_mean,repeat_cov = posterior(jnp.tile(X,(2,1)),jnp.tile(y,2),sigma,prior_scale)
assert jnp.all(jnp.diag(repeat_cov)<jnp.diag(cov))
print(jnp.diag(repeat_cov))Expected: Both posterior marginal variances decrease.
The calculation treats rows as independent new evidence. Duplicating a stored file does not create new evidence in a real dataset.
Check the prior-only boundary
# Experiment — Check the prior-only boundary
empty_mean,empty_cov = posterior(jnp.empty((0,2)),jnp.empty((0,)),sigma,prior_scale)
assert jnp.allclose(empty_mean,0.)
assert jnp.allclose(empty_cov,4*jnp.eye(2))Expected: The mean is zero and covariance is .
The posterior recovers the prior when no likelihood information is present.
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.
Strengthen the prior by changing its scale from two to one half. Predict the direction of change in the weight norm and check it. Explain why a tighter posterior need not mean a better model.
Show a writing guide and starter scaffold
How to write this exercise code
Learner-only inputs, outputs, checks and hints
Inputs
- A design matrix with an explicit intercept column, outcomes, known noise scale, and two prior scales.
Outputs
- Posterior mean and covariance for both prior choices.
Invariants to check
- The covariance is symmetric positive definite.
- The stronger zero-centered prior cannot increase the posterior mean norm in this fixed fixture.
Hints
- Build posterior precision from prior and likelihood precision.
- Solve linear systems instead of explicitly inverting a matrix.
- Interpret the changed posterior separately from predictive model quality.
def compare_prior_strength(X, y, noise_scale, prior_scales):
"""Return posterior moments under two prior scales."""
# TODO: solve both Gaussian precision systems and compare their means.
raise NotImplementedErrorReveal the reference solution
# Exercise solution: Strengthen the prior by changing its scale from two to one half.
strong_mean,strong_cov = posterior(X,y,sigma,.5)
assert jnp.linalg.norm(strong_mean)<jnp.linalg.norm(mean)
assert jnp.all(jnp.diag(strong_cov)<jnp.diag(cov))Move away from centered inputs
Transfer / diagnosis
Use design rows . Compare the JAX result with a host NumPy linear solve and show the posterior covariance is not diagonal.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- The requested design rows, outcomes, known noise scale, and prior scale.
Outputs
- The JAX posterior mean/covariance, host NumPy solve results, and an off-diagonal covariance check.
Invariants to check
- The two solves use the same precision system; the shifted design yields a full posterior covariance with a nonzero off-diagonal entry.
Hints
- Construct the precision matrix in float64 on the host for an independent solve.
- Check the covariance off-diagonal directly instead of reducing it to a diagonal summary.
import numpy as np
def compare_posterior_with_host_solve(posterior, outcomes, noise_scale, prior_scale):
# TODO: Solve the requested design case with JAX and independent host NumPy arithmetic.
raise NotImplementedErrorShow a hint
The intercept and slope can compensate for each other when features are not centered.
Reveal reference solution and reasoning
# Move away from centered inputs (Transfer / diagnosis)
shift_X = jnp.array([[1.,0.],[1.,1.],[1.,2.]])
shift_m,shift_c = posterior(shift_X,y,sigma,prior_scale)
# Transfer the device result to the host for an independent NumPy comparison.
host_X=np.asarray(shift_X,dtype=np.float64)
host_P=np.eye(2)/4+host_X.T@host_X
# Transfer the device result to the host for an independent NumPy comparison.
np.testing.assert_allclose(shift_m,np.linalg.solve(host_P,host_X.T@np.asarray(y)),rtol=1e-5,atol=1e-6)
assert shift_c[0,1]<0Nonzero covariance affects prediction uncertainty; keeping only marginal variances would lose the compensating relationship.
Verify total predictive variance
Transfer / diagnosis
Draw posterior weights and independent observation noise. Compare empirical prediction variance at input zero to the analytic observation variance.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- Posterior weight mean/covariance, observation noise scale, an explicit random key, and the requested sample count.
Outputs
- Empirical prediction variance from sampled weights plus observation noise and analytic observation variance at input zero.
Invariants to check
- The sampled observation variance is compared with the analytic predictive variance, including the noise contribution.
Hints
- Draw parameter samples from the full posterior covariance.
- Use a separate subkey for observation noise and evaluate the prediction at input zero.
import jax
import jax.numpy as jnp
def compare_sampled_and_analytic_observation_variance(mean, covariance, noise_scale, key, sample_count):
# TODO: Sample posterior weights and independent observation noise, then compare variances at x=0.
raise NotImplementedErrorShow a hint
Use separate keys for weights and noise; sample with a Cholesky factor.
Reveal reference solution and reasoning
# Verify total predictive variance (Transfer / diagnosis)
# Create or split explicit PRNG key(s) (`(kw, kn)`) for reproducible randomness.
kw,kn=jax.random.split(jax.random.key(37))
# Sample deterministic random values into `weights` using an explicit PRNG key.
weights=mean+jax.random.normal(kw,(30000,2))@jnp.linalg.cholesky(cov).T
# Sample deterministic random values into `replicated` using an explicit PRNG key.
replicated=weights[:,0]+sigma*jax.random.normal(kn,(30000,))
assert abs(float(replicated.var())-float(observation_var[0]))<.07A simulation verifies that the independent noise term belongs in predictions for observed targets.
Diagnose the result
If an interval becomes implausibly narrow, print the latent and noise variance terms separately. If the slope is unexpectedly shrunk, inspect whether the prior scale was confused with prior precision. If targets have an extra column axis, reject the shape before a matrix operation silently changes the mean shape.
Carry forward
- Posterior precision combines prior information with likelihood information.
- Latent uncertainty and future observation noise are separate quantities.
- An exact small model supplies an independent reference for approximate inference.
Keep your evidence
Precision derivation, exact fractional reference, host solve and predictive variance plot. Keep the environment, observed outputs and your explanation of the figure.
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.