Week-07 · ML-2026
From likelihood and losses
to latent-variable inference
Alexei Kornaev,
Dr. Sc., Prof.
Innopolis University
Researcher at the RC for AI,
National RC for Oncology n.a. N.N. Blokhin

Recap: finish the scalar RNN backward pass.
Explain familiar losses, compare inference approaches, and read a VAE. Tutorial: test the argument with rainfall and images.
| Symbols | Meaning |
|---|---|
| ; ; | Model weights; RNN preactivation, state, activation; loss derivative |
| ; ; | Event probability; stated mass/density model; expectation |
| ; | Observed data; per-observation loss and summed loss |
| ; | Observation-noise variance; weight-prior variance |
| ; | VAE latent coordinates, encoder weights, approximate posterior; ELBO |
Identify the variable, what is observed, and which distribution supplies the average.
Natural logs and nats; reductions are stated explicitly. Specialized symbols and tensor shapes are defined beside first use. VAE paper translate to here.
One input coordinate. One state coordinate. Three shared weights.
Trace a prediction forward, then follow its loss backward.
Week 06 textbook: the scalar recurrent model. Same model and notation; new illustrative numbers below.
Repeated cell: shared .
Initial state: fixed .
Final readout: .
Trainable weights: .
The state travels through time; the readout makes the prediction.
Both biases are fixed at zero. This example has one target and one final loss.
Fixed ; shared ; any differentiable activation .
Cell 0
Cell 1
Cell 2
Save every and : the backward pass uses this same path.
Each cell receives its own and the previous state. Biases are fixed at zero; only the final state has a readout and loss.
— loss sensitivity to . Start at the prediction: .
Cell 0 ·
Cell 1 ·
Cell 2 ·
Through a weight: multiply by that weight.
Through an activation: multiply by its local slope.
Keep weights fixed throughout the backward pass. Here denote the same sensitivities previously written . The initial state is fixed, not trained.
What new factors appear when the recurrent path gets longer?
One recurrent weight and one activation slope per extra transition.
Chain rule for this final-loss scalar model. Color follows the same cells as the forward/backward diagrams; labels also identify each factor.
The first contribution is zero. Does still affect ?
Yes: its path through remains; , which need not be zero.
Multiply along a path. Add across uses of the same parameter.
The indirect effects through earlier states are already included in . Do not count them again in the shared-weight sum.
Vanishing: distant states barely influence the final state, weakening the learning signal.
Exploding: amplified sensitivities can produce very large gradients and unstable updates.
Plot: identity activation, so each factor is . Vertical axis is logarithmic. State sensitivity is not the total shared-weight gradient. Pascanu, Mikolov & Bengio (2013).
| Activation | Local derivative | Consequence on a path |
|---|---|---|
| Identity | Every factor is | |
| Saturation suppresses factors | ||
| ReLU | for ; for | An inactive unit blocks that path |
ReLU is not differentiable at zero; implementations choose a convention there.
A different activation does not guarantee long-range learning.
Gradient clipping limits a large update signal. It cannot recover a signal that has vanished along a path.
Now choose , , target .
Illustrative inputs ; fixed .
| 0 | 0.5 | 0.462 |
| 1 | 0.62 | 0.551 |
| 2 | 0.191 | 0.188 |
, . What is ?
Values rounded for display; checked at full precision against autograd and finite differences. The half-squared-error loss uses the course symbol throughout this recap.
Start with a joint table. Derive the rules. Extend them to continuous values.
Then ask what a distribution’s mean and spread tell us.
Reading route: Bishop, PRML, §1.2, then §§2.1–2.3. All examples and figures below are original course calculations.
One observation: a day with two binary values.
: rain, = dry, = rain.
: signal, = absent, = present.
Outcome: one pair, such as .
Event: all outcomes with rain.
Random variable: assigns 0 or 1 to each outcome.
A probability assigns weight to an event.
Synthetic teaching example. Real data need a rain threshold and signal definition. , ; disjoint events add. Bishop, PRML, §1.2.
100 synthetic outcomes. Here (rows) and (columns).
| Row total | |||
|---|---|---|---|
| 54 | 6 | 60 | |
| 16 | 24 | 40 | |
| Column total | 70 | 30 | 100 |
Cell count:
Column total:
Row total:
Grand total:
Highlighted joint event:
Joint means that both conditions hold in the same observation.
: empirical proportions. Uniform sampling from this finite table gives these probabilities exactly. Population probabilities require a sampling model. Original editable table inspired by Bishop, PRML §1.2.
Keep the highlighted event and . Change the reference group.
| Row total | |||
|---|---|---|---|
| 54 | 6 | 60 | |
| 16 | 24 | 40 | |
| Column total | 70 | 30 | 100 |
Joint: both conditions, among all .
Marginal: any row, in column .
Conditional: row , among column .
: retain the signal column, then normalize.
For iid trials, as , empirical proportions converge to population probabilities (with positive conditioning probability). The probability rules themselves are exact identities. Bishop, PRML §1.2.
Write for . The same rules hold beyond this table.
| Row total | |||
|---|---|---|---|
| 54 | 6 | 60 | |
| 16 | 24 | 40 | |
| Column total | 70 | 30 | 100 |
Sum rule: gather every row in column .
Product rule: split the cell’s fraction.
Sum out a variable. Factor the joint by conditioning on a variable.
The count identity is exact for finite-table sampling, with . General probability identities: Bishop, PRML §1.2. Extra calculations and questions.
The same joint event has two factorizations. Hold fixed.
| Row total | |||
|---|---|---|---|
| 54 | 6 | 60 | |
| 16 | 24 | 40 | |
| Column total | 70 | 30 | 100 |
Divide by and apply the sum rule to the evidence.
Require . The sum covers all disjoint, exhaustive categories. Joint symmetry exchanges variable order; conditional probabilities answer different questions. Bishop, PRML §1.2.
Steve is reserved, helpful, orderly, and attentive to detail.
Which seems more likely: Steve is a librarian, or Steve is a farmer?
Imagine sampling him uniformly from a population containing only these two occupations. Commit to an intuition before seeing the counts.
What information is missing? The occupation proportions and how often the description occurs within each occupation.
Adapted from 3Blue1Brown’s original Steve problem. Open the original page for its visual explanation, or continue with the local worked example.
Teaching population: 10 librarians (40% shy), 200 farmers (10% shy).
Use Shy as the simplified evidence category; Not shy is its complement.
| Occupation | Shy | Not shy | Total |
|---|---|---|---|
| Librarian | 4 | 6 | 10 |
| Farmer | 20 | 180 | 200 |
| Total | 24 | 186 | 210 |
Find , , , and .
, ;
, .
Librarian probability rises from to ; farmer probability is still .
Assumed counts, not measured occupation/personality statistics. 3Blue1Brown · Probability practice.
is a binary observation; is its probability of success.
means “ has a Bernoulli distribution,” .
Does changing change the possible outcomes or their weights?
It changes their weights. At or , one outcome has all the mass.
The symbol means “distributed as.” A single observation is still 0 or 1. Bishop, PRML §2.1.
Expectation: probability-weighted average.
Variance: average squared deviation.
For Bernoulli: , .
Do equal means imply equal variances?
No: these plots have the same centre and different spread.
: random variable; : a possible value. Standard deviation has the original units; variance has squared units. Bishop, PRML, Section 1.2.2.
A normal (Gaussian) distribution is a bell-shaped density.
: mean m; standard deviation m; variance .
is the density of at a possible value .
Continuous weighted average: ; is the quantity averaged.
Density at 0 m is about 1.99 per metre. What is ?
. An interval has probability: .
Density height has units 1/metre; probability is area. Gaussian density formula and location/scale · Bishop, PRML §§1.2.1, 2.3.
: mass of (discrete), or density at (continuous).
Joint: describe together. Marginal: retain by summing/integrating out .
| Rule | Discrete | Continuous |
|---|---|---|
|
Normalize |
||
| Eliminate | ||
| Factor joint | ||
| Bayes |
The denominator totals every possible explanation of the observed .
Condition where the marginal mass/density is positive. For densities, this defines conditioning even when a point has probability zero. General rules and practice. Bishop, PRML §§1.2–1.2.2.
Choose a distribution for observations.
Hold the observations fixed. Fit its parameters.
The negative log likelihood gives a loss.
Observed pairs ; fit parameters .
iid: independent, identically distributed pairs.
Joint dataset likelihood
Supervised: hold inputs fixed
Assume conditional independence:
Maximum likelihood estimation (MLE): maximize the conditional likelihood.
Loss recipe: support → model + assumptions → constrained outputs → NLL → sum/mean
Choose the observation model before choosing the loss.
. Natural-log loss is measured in nats. Mean NLL is ; omit only parameter-independent terms. selects maximizing/minimizing parameters. Bishop, PRML, Section 1.2.5.
Synthetic ordered sequence : 3 rain, 7 dry.
Assume independent, identically distributed (iid) Bernoulli observations with constant rain probability .
Each rain contributes ; each dry day contributes . Independence lets us multiply.
Fix the observations; vary . The peak at is the MLE.
Likelihood scores the fixed data, not posterior uncertainty over . Bishop, PRML, Section 1.2.3 and §2.1.
Real-valued target → Gaussian model → mean output → negative log
Fixed common : the last two terms are constant in . Mean NLL , where .
MSE follows from a Gaussian model with fixed common observation variance.
Unequal fixed variances give weighted squared error. The RNN’s uses unit variance, omitting a constant. This noise assumption is not implied by the CLT. Bishop, PRML §1.2.5.
Real-valued target → Gaussian model → mean and log-variance outputs
Derive this expression. Why must the term remain? Open the worked answer.
Increasing variance reduces the residual term; the log-variance term penalizes that inflation. Both outputs are fitted.
gives positive variance . Heteroscedastic means input-dependent noise. With an exactly zero residual, unrestricted variance can collapse; constraints may be needed. Bishop, PRML §1.2.5.
Binary target → Bernoulli → logit →
Both outcomes contribute through the same Bernoulli formula.
For the rain sequence: . Compute on logits for stability: PyTorch BCEWithLogitsLoss. Bishop, PRML §2.1.
One class among → categorical → logits →
One-hot target , ; class probabilities .
Observed class: cat. Predicted probabilities: cat 0.7, dog 0.2, bird 0.1.
Which probabilities enter the loss?
Only the observed class: nats.
Multiple simultaneous binary labels instead need a Bernoulli model for each label.
The one-hot product describes one categorical draw; it does not assume independent classes. Use logits: PyTorch CrossEntropyLoss. Bishop, PRML §2.2.
| Observation model | Network output | Negative log likelihood |
|---|---|---|
| Gaussian, fixed common variance | Mean | Scaled squared error + constant |
| Gaussian, learned variance | Mean and log variance | Weighted residual + log-scale term |
| Bernoulli | One logit; sigmoid probability | BCE |
| Categorical | logits; softmax probabilities | Multiclass CE |
Choose a model: temperature, rain/no rain, one handwritten digit class.
Temperature: Gaussian as an explicit assumption.
Rain/no rain: Bernoulli. One digit class: categorical.
A Gaussian assumption needs justification for the data. Sum or mean per-observation NLL consistently; regularization scaling matters later. Bishop, PRML §§1.2.5, 2.1–2.2.
A prior describes uncertainty before these observations.
A posterior incorporates the observations.
Prediction carries the remaining uncertainty forward.
Unknown mass kg.
Hypothetical report kg; observation model .
Multiply likelihood by prior, then normalize: here approximately.
Hypothetical teaching values; exact posterior variance is 128000 kg². now denotes unknown model parameters; evidence integrates over them. The same rule updates a mass or network weights. Bishop, PRML §§1.2.3, 2.3.6.

: unknown mass.
: tail, leg, trunk clues.
Start: .
Tail:
Leg:
Trunk:
Normalize each curve to area one. This posterior becomes the next prior.
means “proportional to”: normalization is omitted. Instructor-supplied conceptual illustration, not computed posteriors. Bishop, PRML, Section 1.2.3.
| Result | Operation | What do we keep? |
|---|---|---|
| MLE — maximum likelihood estimation | Maximize | One parameter setting at the likelihood peak |
| MAP — maximum a posteriori estimation | Maximize | One parameter setting at the posterior-density peak (mode) |
| Full posterior | Normalize | Entire distribution: spread and possible multiple modes |
Does a MAP neural network retain uncertainty over its weights?
It keeps one setting. The full posterior retains how uncertainty is distributed.
An estimate locates a peak; a distribution also describes the remaining spread.
Compare approaches · Rainfall example. Bishop, PRML, Section 1.2.3 (one subsection).
Task: fit the data while expressing a preference for weights near zero.
Assume independent ; fixed is the prior standard deviation.
Sum over independent weights: , where .
Narrower prior (left) → steeper quadratic penalty (right).
: weight-prior scale; : observation-noise scale. The next slide combines this penalty with NLL through MAP. Bishop, PRML, Section 1.2.6.
Extend the loss recipe: observation NLL + negative log prior → MAP
| Written objective | Coefficient giving this MAP fit |
|---|---|
| Mean NLL | |
| MSE |
The L2 coefficient depends on the loss scale and reduction.
Drop evidence, which is constant in . MSE row assumes fixed common Gaussian variance , with no factor ½ in MSE. MAP is point estimation; decoupled optimizer weight decay is not generally this objective. Bishop, PRML §1.2.6.
One fitted parameter setting
Evaluate one model at the new input.
Posterior predictive
Average predictions over parameter uncertainty.
Does a stronger L2 penalty guarantee better validation predictions?
No. It changes the tradeoff with data fit; validation performance depends on the model and data.
L2 supplies a MAP objective; it does not perform posterior averaging.
denote a future input and target. Rainfall prediction. Bishop, PRML §§1.2.3, 2.1.1.
| Question | Frequentist approach | Bayesian approach |
|---|---|---|
| Unknown parameters | Fixed but unknown | Uncertainty represented by prior/posterior |
| Use of evidence | Sampling model; MLE is one example | Likelihood × prior, then normalize |
| Report uncertainty | Repeated-sampling properties of procedures | Posterior and posterior predictive distributions |
| Prediction here | Evaluate a fitted model | Average over posterior; MAP retains one mode |
| Modern AI connection | Neural regression/classification; next-token NLL | Bayesian neural networks; approximate latent inference in VAEs |
Both quantify uncertainty. NLL is shared machinery.
VAE here: approximate posterior over codes; fitted network weights. Bishop, PRML, Section 1.2.3 · Kingma & Welling, §§2–3. Return to estimates.
Score the same outcomes with two distributions.
KL measures the average extra log loss relative to a reference.
Bishop, PRML, §§1.6–1.6.1. Natural logarithms and nats throughout this lecture.
Dry/rain reference frequencies: .
Candidate predictions: . Average outcomes using .
For outcome , score with : ; reference score: .
Extra log loss: .
The first argument supplies the averaging weights.
: dry or rain. Nats: units of log loss using natural logs. Here is empirical, not a known population law. Bishop, PRML, Section 1.6.1.
| Expression | Average under | Value |
|---|---|---|
| 0.583 nats | ||
| 0.534 nats | ||
| 0 |
KL is nonnegative; individual summands can be negative.
If but , the forward KL is infinite.
For densities: .
KL is a divergence, not a distance metric.
Zero means agreement almost everywhere; appropriate support and finite terms are assumed. KL is asymmetric and need not satisfy the triangle inequality. Bishop, PRML §1.6.1.
A latent code is a small vector of hidden coordinates.
First specify how this code can generate an observation.
Then ask which codes could explain an observed image.
Approximate that inverse problem with a trainable distribution.
Kingma & Welling, Auto-Encoding Variational Bayes, §§2.1–2.2. Generative and inference routes are developed before the full architecture.
AE: encoder returns a point.
Reconstruction alone does not specify a prior for generating new codes.
VAE: encoder returns Gaussian parameters.
The generative model also specifies and .
The VAE learns an approximate distribution of plausible codes for each image.
: image; : latent coordinate vector; : decoder weights; : encoder weights. Paper become course ; course remains an activation. Kingma & Welling, §§2–3.
Generate: , then .
Infer: given , find plausible using .
The encoder approximates inference; the prior and decoder define generation.
Network weights are point estimates here. Per-image latent uncertainty is not a Bayesian posterior over those weights. Kingma & Welling, §2.1.
Prior ; pixels are independent given the code.
| Code | |||
|---|---|---|---|
| 0.8 | 0.2 | ||
| 0.3 | 0.7 |
Same Bayes rule as Steve: replace occupations with candidate codes.
Exact discrete teaching model, not a continuous VAE or a trained encoder. All four images normalize under each code. Check exact ELBO arithmetic.
For continuous codes, use a spherical standard-normal prior:
independent , written .
Covariance averages the product of two variables’ deviations from their means.
is the identity covariance: unit variance in each coordinate and zero covariance between them.
At one code
The decoder can evaluate .
Across all codes
Many codes can explain one image. A nonlinear decoder can make this integral impractical.
Evidence averages over all possible codes, not just one decoder evaluation.
Spherical means equal spread in every direction. is a dummy integration variable. Continuous variables alone do not imply intractability; model structure matters. Kingma & Welling, §2.1; Bishop, PRML §10.1.
Given , the encoder predicts centre and spreads .
Under , the two coordinates are independent:
Different coordinate spreads → an axis-aligned ellipse; equal spreads → a circle.
: coordinate variances on the diagonal; zeros elsewhere.
Encoder outputs and ; . Covariance practice. Kingma & Welling, §3.
We need a training objective even when the exact latent posterior is hard to compute.
is the encoder’s approximation; averages over its possible codes.
Bayes and the definition of KL give a usable expression:
Log evidence :
how well the generative model explains after averaging over the prior.
Posterior gap:
how far the encoder’s is from the exact posterior.
The gap cannot be negative: .
Matching the exact posterior makes the bound exact. Line-by-line derivation and return link. Kingma & Welling, §2.2.
Hold the decoder and prior fixed. What changes when approaches the posterior?
The posterior gap shrinks and ELBO rises; evidence stays fixed.
Joint training also changes the generative model and its evidence.
The expected ELBO is bounded. One Monte Carlo estimate need not lie below log evidence. Exact numbers. Kingma & Welling, §2.2.
Use the product rule :
If equals the exact posterior, must its KL to the prior be zero?
No. The posterior usually differs from the prior.
Posterior-gap KL: explains the bound. Prior KL: is subtracted inside ELBO.
Minimize reconstruction NLL prior KL.
These are different KL comparisons. We estimate reconstruction by sampling and compute the Gaussian prior KL analytically. Kingma & Welling, §2.2.
Problem: how can reconstruction gradients pass through a random draw to the encoder?
Draw noise independently of the encoder, then transform it:
Same noise: shifts samples; changes spread.
Fix during backpropagation: is differentiable in both outputs.
Reconstruction gradient → sampled code → mean and spread → encoder weights.
: coordinatewise multiplication. Sample fresh noise on later forward passes. Kingma & Welling, §2.4.
Thresholded MNIST: ; decoder logits give .
Sum pixels and latent coordinates per image, then average images.
Standard VAE uses coefficient 1 on prior KL; changes the objective.
Pixels conditionally independent given ; compute BCE on logits. Latent dimension is 2 in this pilot. Gaussian KL derivation · Implementation and pilot settings. Kingma & Welling, Appendices B/C.
Mean code: the encoder’s two-coordinate centre .
(pixel probabilities).
Top: original grayscale source. Middle: binary model input.
Bottom: each pixel’s predicted probability of being on, given the mean code.
A latent code is a coordinate vector; a probability image is the decoder’s mean output.
For a Bernoulli pixel, mean = probability of 1. Decode for this deterministic display. Existing MNIST pilot: ; validation images; test set unused.
Reading task: where does the encoder place each validation image?
One dot: one image’s mean code .
Axes: two learned latent coordinates.
Color: known digit label, used only for display.
Four ellipses: selected encoder distributions; semiaxes are one standard deviation.
Find an overlapping region. Class separation was not a training objective.
2,000 validation images, baseline . Ellipses show model spread, not calibrated confidence. Original MNIST pilot.
Each column uses the same code: top = probabilities; bottom = sampled binary pixels.
Generation starts from a prior draw; reconstruction starts from an observed image.
No input image or encoder is needed for generation. : unit coordinate variances, zero covariance. Baseline , predeclared gallery; original pilot.
| Question | Model-based answer |
|---|---|
| Why this loss? | Observation distribution → negative log likelihood |
| How does evidence change uncertainty? | Prior × likelihood → posterior → prediction |
| How can hidden causes explain an image? | Generative model → approximate latent posterior → ELBO → trainable encoder/decoder |
Write the distribution, identify what is observed, and trace what is inferred or optimized.
Rainfall inference estimates a shared event probability.
This VAE infers a per-image code and optimizes shared network weights.
Compare frequentist and Bayesian approaches.

Diederik P. (Durk) Kingma
A learned inference network and a differentiable sampling path connect today’s probability model to neural-network training.
Kingma’s site · AEVB · Adam. Biography verified 2026-10-14. Portrait supplied by the instructor.
Rainfall
Same observations: likelihood → MLE → prior/posterior → prediction.
Explain which object describes data and which describes uncertainty about .
VAE
Identify inferred codes and fitted weights.
Explain reconstruction, latent maps, generation, and the sampling gradient path.
State the model → predict → compute → explain.
Elephant graphical abstract supplied by the instructor. RNN diagrams redraw the Week 06 model; diagrams and sensitivity plots are original course figures.
The main lecture is complete. Use the following slides for practice or selected live derivations.
Our 7 dry and 3 rain observations define :
When is fixed, which term changes as we fit ?
Only KL changes. Minimizing empirical categorical cross-entropy minimizes . One-hot CE is .
is the fixed reference term. This exact finite discrete identity does not identify a continuous empirical measure with a density. Detailed information theory is deferred to later in the course. Bishop, PRML §1.6.1.
Same tanh example: , .
| Backward order | |||
|---|---|---|---|
| −0.412 | 0.964 | −0.397 | |
| −0.318 | 0.696 | −0.221 | |
| −0.177 | 0.786 | −0.139 |
Use these sensitivities to calculate all three parameter gradients.
Calculate with full precision; displayed values are rounded. Return to checkpoint · Check with code.
import torch
w_x, w_h, w_o = [torch.tensor(v, dtype=torch.float64, requires_grad=True)
for v in [0.5, 0.8, 1.0]]
h = torch.tensor(0.0, dtype=torch.float64)
for x_t in [1.0, 0.5, -0.5]:
h = torch.tanh(w_x * x_t + w_h * h)
prediction = w_o * h
loss = 0.5 * (prediction - 0.6) ** 2
loss.backward()
print([f"{w.grad.item():.3g}" for w in (w_x, w_h, w_o)])
# [-0.0513, -0.321, -0.0776]Autograd follows the same dependencies we differentiated by hand.
Try changing one input or weight. Predict the gradient sign, then rerun.
Download the checked replay · Return to the checkpoint.
CPU only; requires PyTorch. Run python3 scalar-rnn.py. No training or dataset download.
Use the same counts to check your reasoning. Each task has a worked answer revealed by a click.
Public, ungraded lecture practice. Return to Steve · Continue with continuous probability.
| Signal absent | Signal present | Total | |
|---|---|---|---|
| Dry | 54 | 6 | 60 |
| Rain | 16 | 24 | 40 |
| Total | 70 | 30 | 100 |
Find , , , and . Which denominators change?
Conditioning changes the reference group. The joint event is the same 24 observations; the two conditionals use different totals.
Normalized teaching counts; uniform sampling from the table. Bishop, PRML §1.2. Practice menu · Return to the denominator slide.
Given the same table:
Recover . Why would an unweighted average of the two conditionals fail?
The groups contain 30 and 70 observations. Giving them equal weight would yield approximately , describing a different sampling scheme.
The groups are disjoint and exhaustive. Combine sum and product rules. Bishop, PRML §1.2. Practice menu · Return to the rules.
Are rain and signal independent in our table? Can two mutually exclusive events with positive probability be independent?
Rain and signal: , whereas . Independence fails.
Mutually exclusive events: their intersection has probability zero. If both have positive probability, their product is positive, so independence fails here too.
Independence means factorization. Mutual exclusivity means no shared outcomes.
One failed factorization disproves independence; checking one successful cell does not establish it in general. Bishop, PRML §1.2. Practice menu · Return to the rules.
A separate hypothetical sensor model
Each sensor has , ; let .
Does conditional independence imply marginal independence? Compare with .
No. Mixing groups with different signal rates induces marginal dependence in this model.
Factorization is a model assumption, not a conclusion from the first rain/signal table or a causal claim. Bishop, PRML §8.2. Practice menu · Return to Bayes.
Explore the longer calculations. Each fixed question has a worked answer revealed by a click.
Public, ungraded lecture practice. Return to the rules · Continue to likelihood.
Use the two marked values to find .
Rounded labels give 0.682; the full-precision calculation rounds to 0.683.
Same Gaussian as the core slide. where differentiable. Bishop, PRML §1.2.1. Practice menu · Return to density.
Do these curves describe a binary observation, or uncertainty over its probability ?
Uncertainty over . The common mean is for Beta(2,3) and Beta(8,12); their variances are and about .
normalizes the density. These are example models, not successive updates. Bishop, PRML §2.1.1. Practice menu · Return to Bernoulli.
The rain/signal table
Correlation divides by both standard deviations:
Does zero covariance guarantee independence?
No. Let be uniform on and .
| −1 | 0 | 1 | |
|---|---|---|---|
| 1 | 0 | 1 |
, so . Yet is determined by and is not constant.
Finite second moments assumed. Correlation requires positive variances; independence implies zero covariance, but its converse fails in general. Bishop, PRML §1.2.2. Practice menu · Return to moments.
Which parameter shifts the curve? Which parameter changes its width?
sets location; sets spread. has mean and variance . All these densities have unit area.
Gaussian support is the real line. Bishop, PRML §§1.2.4, 2.3. Practice menu · Return to density.
counts independent Bernoulli() trials, .
Use . Orange points show .
Why does the rare-event example make a poor approximation?
Normal approximation: Penn State STAT 414 §28.1. Accuracy depends on counts and the event; one trial stays binary. Gaussian regression noise requires a separate model assumption. Show worked answer · Practice menu.
Rare-event example: ; is the matching Gaussian approximation.
| Quantity | Binomial | Gaussian |
|---|---|---|
| Mean | 0.4 | 0.4 |
| Variance | 0.392 | 0.392 |
| Zero / zero bin | ||
| Outside | 0 | About 7.53% |
Only successes are expected. The count law is skewed near zero; the Gaussian spreads too much probability beyond the bins for valid counts.
Matching mean and variance does not guarantee accurate count probabilities.
Original exact calculations; no renormalization of Gaussian bin probabilities. Return to comparison · Practice menu. Approximation method: Penn State STAT 414 §28.1.
Write , with . Shading marks the variables eliminated.
Marginalize the joint over every remaining coordinate
(discrete)
(continuous)
Chain rule: factor the joint in a chosen order
Does this factorization require independence?
No. The chain rule holds without independence; that extra assumption can simplify the conditionals.
Sum/integrate over each eliminated variable’s support. Mixed models combine sums and integrals. For , the empty product is one. Bishop, PRML §§1.2, 8.2. Practice menu · Return to the rules.
Start with the scalar Gaussian negative log density:
Substitute : and .
Writing , . For fixed nonzero residual, the optimum is . Without , arbitrarily large variance drives the residual term toward zero.
The constant can be omitted; the fitted log-variance term cannot.
If , drives this unrestricted NLL down without bound. This is observation noise, not a posterior over weights. Return to the question. Bishop, PRML §1.2.5.
Beta(2,3) + 3 rain + 7 dry → Beta(5,10).
Conjugacy: the posterior remains in the prior’s distribution family. Constant , common Bernoulli model, conditionally independent observations. Real weather may violate these assumptions. Bishop, PRML §2.1.1. Practice menu.
Change only : which posterior mean moves further toward ?
The weak prior moves farther: posterior mean 0.333 versus 0.383 after 3 of 10 rain observations.
Dashed = prior; solid = posterior. Synthetic datasets: and . Fixed prior influence decreases in this model as grows. in the displayed weighted-average identity. Bishop, PRML §2.1.1. Practice menu.
Let count rain events in future observations.
Given , use ; retain the same model assumptions.
Same mean count, different spread: integrating uncertainty changes the prediction.
Beta-binomial variance ; plug-in Binomial variance . Axes represent different variables and units. A credible interval for is not a prediction interval for . Original calculation from the predictive integral; Bishop, PRML §2.1.1. Practice menu.
For , insert Bayes into the definition of KL:
Evidence does not depend on the code, so it leaves the expectation.
Rearrange: .
Appropriate support and finite expectations assumed. Return to ELBO. Kingma & Welling, §2.2.
For independent coordinates of , :
Use and :
Each coordinate’s contribution is zero at , .
This is KL to the prior, not to the model posterior. Return to image loss. Kingma & Welling, Appendix B.
For and :
| Quantity | Calculation | Nats |
|---|---|---|
| Reconstruction log likelihood | −1.03 | |
| Prior KL | 0.0823 | |
| ELBO | Reconstruction log likelihood − prior KL | −1.12 |
| Posterior gap | 0.109 |
ELBO is maximized; its negative is minimized. Keep the sign of the prior term.
Numbers rounded for display; identities checked at full precision by the figure generator. The gap is checkable because this posterior is exact. Return to the bound.
| Fixed choice | Pilot setting |
|---|---|
| Data | 12,000 training + 2,000 disjoint validation images from MNIST’s training split |
| Observation | Pixel/255 ; all ten digit classes retained |
| Optimization | 15 epochs, batch 256, Adam learning rate 0.001; 705 updates/model |
| Comparison | ; common initialization, batch order and noise streams |
| Validation | Same images and four common code draws/image; report NLL and KL separately |
These are measured outputs of one controlled, finite-budget pilot.
CPU, one initialization seed; official test set unused. Labels only select a fixed gallery and color the latent map. This is not a convergence, robustness, or Colab-runtime claim. Full settings and metrics: pilot record. Practice menu.
At , this estimates the negative ELBO.
One sampled code per image in training; exact latent KL. Separately averaging pixels and latent coordinates would change their relative weight. Gaussian sampling and reduction checks are reproducible in the pilot generator. Practice menu.
In this run, larger reduced latent KL and increased reconstruction NLL.
Same validation examples and sampled noise, separate unweighted terms. Do not compare differently weighted total losses as a common quality metric. One seed and 705 updates per model; these observations are not a universal ordering. Original pilot. Practice menu.
Open discussion: compare recognizable and ambiguous regions. Expect differences in coverage; this grid alone cannot establish generation quality.
Chosen coordinates in , not random prior samples. Every tile is a probability image. Inspect these alongside reconstruction NLL, latent KL, and actual prior draws; a grid alone does not establish generative quality. Practice menu.
Toy classes ; stipulated model probabilities, not estimates from counts.
| Class | Prior | ||
|---|---|---|---|
| 0.4 | 0.8 | 0.7 | |
| 0.6 | 0.2 | 0.3 |
Observe both features equal 1. Find . What permits the product?
Assume : scores are and . Normalize: .
Redundant features can count the same evidence twice and distort confidence. Count-based estimation needs an explicit smoothing choice for unseen combinations. Bishop, PRML §8.2. All practice · Return to Bayes.
| Method | What varies? | Prediction |
|---|---|---|
| Heteroscedastic head | Noise scale depends on input | Observation distribution at fitted weights |
| Bayesian regression | Weights have a posterior | Average over weights and observation noise |
| MC dropout | Stochastic network masks | Approximate predictive draws under assumptions |
For a specified posterior predictive model: Observation spread and uncertainty in the predicted mean can coexist.
Dropout is not automatically calibrated Bayesian inference; its interpretation depends on modeling assumptions. Gal & Ghahramani (2016). All practice · Return to prediction.
Choose a task, reveal its answer, and return to the corresponding teaching frame.
Public, ungraded practice. Return to the lecture map · Tutorials. The main teaching route ends at the references.
← Lectures Introduction to Machine Learning · Week 07