Lesson 2.5 — Probability & Statistical Learning
Random Variables · from random events to distributions
A robot can report an event (“the alarm sounded”) or a measurement (“the joint moved this far”). The form of the observation determines what the model must predict.
- Event. A probability mass assigns a share of runs to each possible outcome. For a binary alarm, the probabilities of sounding and staying silent add to one.
- Measurement. A probability density describes how tightly readings cluster. To find the chance that a reading falls within a sensor's tolerance band, take the area under the density over that band. A narrow peak can be tall because its total area still equals one.
The alarm example below uses probability to interpret evidence. The dynamics example later works in the other direction: given a state and a command, predict a distribution for the next measurement.
Compare repeated samples with their generating distribution
01 · PMF / PDF Sampling Player
Joint / Marginal / Conditional · Bayes Rule
A detector catches nine out of ten faults. An operator hears an alarm. To estimate the chance of a fault, first decide which runs belong in the comparison.
Let mean a fault occurred and mean the alarm sounded. Imagine 1,000 runs with a 5% fault rate, a 90% detection rate and a 10% false-alarm rate. These rates give the following expected counts.
| What happened | Alarm | Silent |
|---|---|---|
| 50 runs with a fault | 45 detected | 5 missed |
| 950 healthy runs | 95 false alarms | 855 silent |

Each mark represents five runs. The same nine teal circles appear in both rows.
- To evaluate the detector, inspect only the confirmed faults. This group contains the teal circles and the gray square. Of the 50 faulty runs, 45 sounded the alarm: .
- To interpret the alarm, start with the operator's alarm log. The missed faults never entered that log, but the false alarms did. Of the 140 alarms, 45 came from faulty runs: .
The alarm raises the fault probability from 5% before hearing it to about 32% afterward. Most alarms still come from healthy runs because those runs are so common. Bayes' rule expresses the same count with proportions:
Change how common faults are while keeping the detector fixed
Raise the prior from 5% to 10%. In 1,000 runs, the detector now raises 90 true alarms and 90 false alarms. Half the alarms indicate faults even though both detector rates stayed the same.
02 · Bayesian Fault Diagnosis
Expectation, Variance & Covariance
Under squared error, for any given x, the optimal deterministic predictor is the
conditional mean: E[(Y − a)² | x] = Var(Y | x) + (E[Y | x] − a)². Irreducible
conditional variance does not mean training failed.
03 · Conditional Moments & Covariance
Bernoulli / Categorical / Gaussian
These distributions are modeling assumptions rather than properties automatically guaranteed by a neural network.
04 · Distribution Parameter Explorer
Maximum Likelihood Estimation · infer parameters from data
The alarm example assumed a known detector. Now suppose its detection rate is unknown. Engineers collect 50 independently sampled, confirmed faults under the same conditions. The detector sounds on 45 and misses 5. Keep that record fixed and compare candidate values of .
For the observed sequence, the likelihood is . A small makes the 45 detections surprising. A value close to one makes the five misses surprising. The maximum occurs at . This estimates sensitivity. Estimating the chance of a fault after an alarm also requires information about healthy runs and fault prevalence.
The same idea works for continuous measurements. Give each observed reading the density assigned to it by a candidate model. For independent observations, the product of these densities is the likelihood. Taking the negative logarithm turns the product into a loss you can add across observations.
Compare candidate means against one fixed set of Gaussian readings
05 · Likelihood Surface Explorer
Gaussian NLL · from MSE to uncertainty
Suppose two dynamics models predict the same next-state mean for the same command. One predicts a tight cluster of readings and the other allows more spread. Their point predictions have identical squared error on every reading. To judge their uncertainty estimates, read the height of each density at the observation.

The dotted line marks the observed reading. At the mean, the narrow model earns a lower negative log-likelihood because it puts more density there. At the reading on the right, the wide model earns the lower loss. Widening the curve moves density toward the tails and lowers its peak because the total area must stay one.
For observation , predicted mean and predicted variance , the loss is
If is fixed, minimizing average NLL over the mean gives the same objective as MSE up to a positive scale and an additive constant. When the model learns , both terms matter. The implementation below predicts a positive variance with a small floor and passes that variance to the loss.
Read the two loss terms for a chosen mean, spread and observation
06 · Gaussian NLL & MSE Lens
Entropy, Cross Entropy & KL Divergence
In natural logs, units are nats. By convention 0 log 0 = 0. For fixed
p, minimizing CE minimizes forward KL; for one-hot p,
H(p) = 0 and CE equals NLL. KL is non-negative and generally asymmetric, so it is
not a distance metric.
07 · Entropy / KL Contribution Mapper
Engineering Lab · Probabilistic Robot Dynamics
08 · Compare Gaussian Prediction Intervals
Evaluate Mean MSE, full NLL, 90% interval coverage, and mean interval width together. Learned
v(x, u) captures aleatoric uncertainty (conditional data noise)
under the Gaussian assumption—not epistemic parameter uncertainty or out-of-distribution safety.
Complete reproducible PyTorch code (probabilistic_dynamics.py)
import math
import torch
from torch import nn
import torch.nn.functional as F
torch.set_default_dtype(torch.float64)
torch.set_num_threads(1)
def rng(seed):
state = seed & 0xffffffff
def uniform():
nonlocal state
state = (1664525 * state + 1013904223) & 0xffffffff
return state / 4294967296
return uniform
def dataset(n, seed):
r = rng(seed)
xs, ys = [], []
for _ in range(n):
x, u = 4 * r() - 2, 2 * r() - 1
e = math.sqrt(-2 * math.log(max(r(), 1e-15))) * math.cos(2 * math.pi * r())
y = 0.65 * x + 0.5 * math.sin(2 * x) + 0.35 * u + (0.08 + 0.25 * abs(x)) * e
xs.append([x, u])
ys.append(y)
return torch.tensor(xs), torch.tensor(ys)
class Dynamics(nn.Module):
def __init__(self, seed, mode):
super().__init__()
r = rng(seed + 2000)
p = [0.6 * (r() - 0.5) for _ in range(42)]
p[40], p[41] = 0.0, -2.0
self.p = nn.Parameter(torch.tensor(p))
self.mode = mode
def forward(self, x):
p = self.p
a = torch.tanh(x @ p[:16].reshape(2, 8) + p[16:24])
out = a @ p[24:40].reshape(8, 2) + p[40:42]
mu = out[:, 0]
v = 0.01 + F.softplus(out[:, 1]) if self.mode == "learn" else torch.full_like(mu, 0.16)
return mu, v
loss_fn = nn.GaussianNLLLoss(full=True)
@torch.no_grad()
def metrics(model, data):
x, y = data
mu, v = model(x)
half = 1.6448536269514722 * v.sqrt()
return dict(
loss=loss_fn(mu, y, v).item(),
mse=((y - mu)**2).mean().item(),
cover=((y - mu).abs() <= half).double().mean().item(),
width=(2 * half).mean().item(),
)
def train(seed=3, mode="learn", lr=0.02, epochs=250):
train_data, val_data = dataset(160, seed), dataset(80, seed + 1000)
model = Dynamics(seed, mode)
opt = torch.optim.Adam(model.parameters(), lr=lr, betas=(0.9, 0.999), eps=1e-8)
history = []
for t in range(epochs + 1):
if t % 5 == 0 or t == epochs:
history.append(dict(t=t, p=model.p.detach().tolist(), tr=metrics(model, train_data), va=metrics(model, val_data)))
if t == epochs:
break
opt.zero_grad(set_to_none=True)
x, y = train_data
mu, v = model(x)
loss = loss_fn(mu, y, v)
loss.backward()
opt.step()
return model, history
if __name__ == "__main__":
for mode in ("learn", "fixed"):
model, h = train(mode=mode)
print(mode, "initial:", h[0]["va"], "final:", h[-1]["va"])
with torch.no_grad():
print("predicted sigma at x=0, 2:", model(torch.tensor([[0.0, 0.0], [2.0, 0.0]]))[1].sqrt())