Frequentist and
Bayesian approaches
to ML

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

Instructor-provided elephant illustration: partial observations accompany successive beliefs about mass. The drawn distributions are conceptual, not measured data.

What will we understand and then test?

Recap: finish the scalar RNN backward pass.

  1. Probability: describe what is uncertain
  2. Likelihood: explain the loss
  3. Bayesian inference: update with evidence
  4. KL: compare distributions
  5. VAE: infer a hidden cause and generate

Explain familiar losses, compare inference approaches, and read a VAE. Tutorial: test the argument with rainfall and images.

Notation for today’s route

Symbols Meaning
θ\theta; zt,ht,ϕz_t,h_t,\phi; gv=∂L/∂vg_v=\partial L/\partial v Model weights; RNN preactivation, state, activation; loss derivative
P(A)P(A); pp; 𝔼\mathbb E Event probability; stated mass/density model; expectation
𝒟={(xi,yi)}i=1n\mathcal D=\{(x_i,y_i)\}_{i=1}^n; Li,LL_i,L Observed data; per-observation loss and summed loss
σ2\sigma^2; τ2\tau^2 Observation-noise variance; weight-prior variance
u,ψ,qψ(u∣x)u,\psi,q_\psi(u\mid x); ℰ\mathcal E 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 z,ϕz,\phi translate to u,ψu,\psi here.

Before probability: one scalar RNN

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.

Separate the cell from the prediction

Scalar input and previous hidden state enter the recurrent cell. Its new state feeds the next step and, when required, a separate linear readout.

zt=wxxt+whht−1,ht=ϕ(zt),xt,ht∈ℝ. z_t=w_xx_t+w_hh_{t-1},\qquad h_t=\phi(z_t),\qquad x_t,h_t\in\mathbb R.

Repeated cell: shared wx,whw_x,w_h.
Initial state: fixed h−1=0h_{-1}=0.

Final readout: ŷ=woh2\widehat y=w_oh_2.
Trainable weights: θ=(wx,wh,wo)\theta=(w_x,w_h,w_o).

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.

Forward: three cells, one final loss

Fixed h−1=0h_{-1}=0; shared wx,whw_x,w_h; any differentiable activation ϕ\phi.

Cell 0

z0=wxx0+whh−1z_0=w_xx_0+w_hh_{-1} h0=ϕ(z0)h_0=\phi(z_0)

Cell 1

z1=wxx1+whh0z_1=w_xx_1+w_hh_0 h1=ϕ(z1)h_1=\phi(z_1)

Cell 2

z2=wxx2+whh1z_2=w_xx_2+w_hh_1 h2=ϕ(z2)h_2=\phi(z_2)

h2→woŷ=woh2→L=12(ŷ−y)2h_2\ \xrightarrow{\ w_o\ }\ \widehat y=w_oh_2 \quad\longrightarrow\quad L=\tfrac12(\widehat y-y)^2

Save every ztz_t and hth_t: the backward pass uses this same path.

Each cell receives its own xtx_t and the previous state. Biases are fixed at zero; only the final state has a readout and loss.

Backward: follow the same path in reverse

gv:=∂L∂vg_v:=\dfrac{\partial L}{\partial v} — loss sensitivity to vv. Start at the prediction: gŷ=ŷ−yg_{\widehat y}=\widehat y-y.

Cell 0 · z0→h0z_0\to h_0

gh0=whgz1g_{h_0}=w_hg_{z_1} gz0=ϕ′(z0)gh0g_{z_0}=\phi'(z_0)g_{h_0}

Cell 1 · z1→h1z_1\to h_1

gh1=whgz2g_{h_1}=w_hg_{z_2} gz1=ϕ′(z1)gh1g_{z_1}=\phi'(z_1)g_{h_1}

Cell 2 · z2→h2z_2\to h_2

gh2=wogŷg_{h_2}=w_og_{\widehat y} gz2=ϕ′(z2)gh2g_{z_2}=\phi'(z_2)g_{h_2}

Through a weight: multiply by that weight.
Through an activation: multiply by its local slope.

Keep weights fixed throughout the backward pass. Here ght,gztg_{h_t},g_{z_t} denote the same sensitivities previously written gth,gtzg_t^h,g_t^z. The initial state is fixed, not trained.

The deepest term contains every local derivative

L→ŷ→h2→z2→h1→z1→h0→z0L\ \longrightarrow\ \widehat y\ \longrightarrow\ h_2\ \longrightarrow\ z_2\ \longrightarrow\ h_1\ \longrightarrow\ z_1\ \longrightarrow\ h_0\ \longrightarrow\ z_0

gz0=g_{z_0}= (ŷ−y)wo⏟loss and readout\underbrace{(\widehat y-y)w_o}_{\text{loss and readout}} ϕ′(z2)⏟cell 2\underbrace{\phi'(z_2)}_{\text{cell 2}} wh⏟1←2\underbrace{w_h}_{1\leftarrow2} ϕ′(z1)⏟cell 1\underbrace{\phi'(z_1)}_{\text{cell 1}} wh⏟0←1\underbrace{w_h}_{0\leftarrow1} ϕ′(z0)⏟cell 0\underbrace{\phi'(z_0)}_{\text{cell 0}}

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.

Shared parameters: add their contributions

∂L∂wo=gŷh2\frac{\partial L}{\partial w_o}=g_{\widehat y}h_2

∂L∂wx=∑t=02gztxt=gz0x0+gz1x1+gz2x2\frac{\partial L}{\partial w_x} =\sum_{t=0}^{2}g_{z_t}x_t =g_{z_0}x_0+g_{z_1}x_1+g_{z_2}x_2

∂L∂wh=∑t=02gztht−1=gz0h−1⏟=0+gz1h0+gz2h1\frac{\partial L}{\partial w_h} =\sum_{t=0}^{2}g_{z_t}h_{t-1} =\underbrace{g_{z_0}h_{-1}}_{=\,0}+g_{z_1}h_0+g_{z_2}h_1

The first whw_h contribution is zero. Does x0x_0 still affect LL?

Yes: its path through h0,h1,h2h_0,h_1,h_2 remains; ∂L/∂x0=wxgz0\partial L/\partial x_0=w_xg_{z_0}, 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 gztg_{z_t}. Do not count them again in the shared-weight sum.

Longer paths multiply more derivatives

∂hT∂hs=∏t=s+1T[whϕ′(zt)],s<T. \frac{\partial h_T}{\partial h_s} =\prod_{t=s+1}^{T}\bigl[w_h\phi'(z_t)\bigr],\qquad s<T.

Logarithmic plot of absolute state sensitivity over zero to thirty recurrent transitions for identity activation. Weight 0.7 gives exponential decay, 1 gives a constant one, and 1.2 gives exponential growth.

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 whw_h. Vertical axis is logarithmic. State sensitivity is not the total shared-weight gradient. Pascanu, Mikolov & Bengio (2013).

Changing the activation changes the backward path

Activation ϕ(z)\phi(z) Local derivative Consequence on a path
Identity zz 11 Every factor is whw_h
tanh⁡(z)\tanh(z) 1−tanh⁡2(z)1-\tanh^2(z) Saturation suppresses factors
ReLU max⁡(0,z)\max(0,z) 11 for z>0z>0; 00 for z<0z<0 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.

Check one numerical backward step

Now choose ϕ=tanh\phi=\tanh, (wx,wh,wo)=(0.5,0.8,1)(w_x,w_h,w_o)=(0.5,0.8,1), target y=0.6y=0.6.
Illustrative inputs (x0,x1,x2)=(1,0.5,−0.5)(x_0,x_1,x_2)=(1,0.5,-0.5); fixed h−1=0h_{-1}=0.

tt ztz_t ht=tanh⁡(zt)h_t=\tanh(z_t)
0 0.5 0.462
1 0.62 0.551
2 0.191 0.188

ŷ=0.188\widehat y=0.188, L=0.0847L=0.0847. What is gz2g_{z_2}?

gz2=(ŷ−y)wo(1−h22)≈(−0.412)(1)(0.964)=−0.397.g_{z_2}=(\widehat y-y)w_o(1-h_2^2) \approx(-0.412)(1)(0.964)=-0.397.

Values rounded for display; checked at full precision against autograd and finite differences. The half-squared-error loss uses the course symbol LL throughout this recap.

Part 1 · Probability describes the question

  1. Probability
  2. Likelihood
  3. Bayesian inference
  4. KL
  5. VAE

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.

Outcomes, events, and random variables

One observation: a day with two binary values.

RR: rain, 00 = dry, 11 = rain.
SS: signal, 00 = absent, 11 = present.

Ω={(0,0),(0,1),(1,0),(1,1)}.\Omega=\{(0,0),(0,1),(1,0),(1,1)\}.

Outcome: one pair, such as (1,1)(1,1).

Event: all outcomes with rain.

A={(1,0),(1,1)}={R=1}.A=\{(1,0),(1,1)\}=\{R=1\}.

Random variable: RR 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. P(A)≥0P(A)\ge0, P(Ω)=1P(\Omega)=1; disjoint events add. Bishop, PRML, §1.2.

A count table records both variables

100 synthetic outcomes. Here Y=RY=R (rows) and X=SX=S (columns).

Y∖XY\backslash X x0x_0 x1x_1 Row total
y0y_0 54n00n_{00} 6n01n_{01} 60r0r_0
y1y_1 16n10n_{10} 24n11n_{11} 40r1r_1
Column total 70c0c_0 30c1c_1 100NN

Cell count: nijn_{ij}

Column total: cj=∑inijc_j=\sum_i n_{ij}
Row total: ri=∑jnijr_i=\sum_j n_{ij}

Grand total: N=∑i,jnijN=\sum_{i,j}n_{ij}

p̂N(yi,xj)=nijN.\widehat p_N(y_i,x_j)=\frac{n_{ij}}{N}.

Highlighted joint event:

p̂N(R=1,S=1)=24100.\widehat p_N(R=1,S=1)=\frac{24}{100}.

Joint means that both conditions hold in the same observation.

p̂N\widehat p_N: 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.

Conditioning changes the denominator

Keep the highlighted event Y=y1Y=y_1 and X=x1X=x_1. Change the reference group.

Y∖XY\backslash X x0x_0 x1x_1 Row total
y0y_0 54n00n_{00} 6n01n_{01} 60r0r_0
y1y_1 16n10n_{10} 24n11n_{11} 40r1r_1
Column total 70c0c_0 30c1c_1 100NN

Joint: both conditions, among all NN.

p̂N(yi,xj)=nijN.\widehat p_N(y_i,x_j)=\frac{n_{ij}}{N}.

Marginal: any row, in column jj.

p̂N(xj)=∑inijN=cjN.\widehat p_N(x_j)=\frac{\sum_i n_{ij}}{N}=\frac{c_j}{N}.

Conditional: row ii, among column jj.

p̂N(yi∣xj)=nijcj,cj>0.\widehat p_N(y_i\mid x_j)=\frac{n_{ij}}{c_j},\qquad c_j>0.

p̂N(R=1∣S=1)=24/30=0.8\widehat p_N(R=1\mid S=1)=24/30=0.8: retain the signal column, then normalize.

For iid trials, as N→∞N\to\infty, empirical proportions converge to population probabilities (with positive conditioning probability). The probability rules themselves are exact identities. Bishop, PRML §1.2.

Sum and product rules follow from the counts

Write p(yi,xj)p(y_i,x_j) for P(Y=yi,X=xj)P(Y=y_i,X=x_j). The same rules hold beyond this table.

Y∖XY\backslash X x0x_0 x1x_1 Row total
y0y_0 54n00n_{00} 6n01n_{01} 60r0r_0
y1y_1 16n10n_{10} 24n11n_{11} 40r1r_1
Column total 70c0c_0 30c1c_1 100NN

Sum rule: gather every row in column jj.

p(xj)=∑ip(yi,xj).p(x_j)=\sum_i p(y_i,x_j).

Product rule: split the cell’s fraction.

nijN=nijcjcjN.\frac{n_{ij}}{N}=\frac{n_{ij}}{c_j}\frac{c_j}{N}.

p(yi,xj)=p(yi∣xj)p(xj).p(y_i,x_j)=p(y_i\mid x_j)p(x_j).

Sum out a variable. Factor the joint by conditioning on a variable.

The count identity is exact for finite-table sampling, with cj>0c_j>0. General probability identities: Bishop, PRML §1.2. Extra calculations and questions.

Bayes reverses the conditioning

The same joint event has two factorizations. Hold i,ji,j fixed.

Y∖XY\backslash X x0x_0 x1x_1 Row total
y0y_0 54n00n_{00} 6n01n_{01} 60r0r_0
y1y_1 16n10n_{10} 24n11n_{11} 40r1r_1
Column total 70c0c_0 30c1c_1 100NN

p(yi,xj)=p(yi∣xj)p(xj)=p(xj∣yi)p(yi).\begin{aligned} p(y_i,x_j)&=p(y_i\mid x_j)p(x_j)\\ &=p(x_j\mid y_i)p(y_i). \end{aligned}

Divide by p(xj)p(x_j) and apply the sum rule to the evidence.

p(yi∣xj)=p(xj∣yi)⏞likelihoodp(yi)⏞prior∑kp(xj∣yk)p(yk)⏟evidence p(xj).p(y_i\mid x_j)=\frac{\overbrace{p(x_j\mid y_i)}^{\text{likelihood}}\overbrace{p(y_i)}^{\text{prior}}} {\underbrace{\sum_k p(x_j\mid y_k)p(y_k)}_{\text{evidence }p(x_j)}}.

Require p(xj)>0p(x_j)>0. The sum covers all disjoint, exhaustive YY categories. Joint symmetry exchanges variable order; conditional probabilities answer different questions. Bishop, PRML §1.2.

Steve: librarian or farmer?

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.

Steve: condition on the observed evidence

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 P(Shy∣Lib)P(\mathrm{Shy}\mid\mathrm{Lib}), P(Shy∣Farm)P(\mathrm{Shy}\mid\mathrm{Farm}), P(Lib)P(\mathrm{Lib}), and P(Farm)P(\mathrm{Farm}).

P(Shy∣Lib)=0.4P(\mathrm{Shy}\mid\mathrm{Lib})=0.4, P(Shy∣Farm)=0.1P(\mathrm{Shy}\mid\mathrm{Farm})=0.1;
P(Lib)=10/210=1/21P(\mathrm{Lib})=10/210=1/21, P(Farm)=200/210=20/21P(\mathrm{Farm})=200/210=20/21.

P(Lib∣Shy)=0.4(1/21)0.4(1/21)+0.1(20/21)=424=16≈16.7%.P(\mathrm{Lib}\mid\mathrm{Shy})= \frac{0.4(1/21)}{0.4(1/21)+0.1(20/21)} =\frac{4}{24}=\frac16\approx16.7\%.

Librarian probability rises from 1/211/21 to 1/61/6; farmer probability is still 5/65/6.

Assumed counts, not measured occupation/personality statistics. 3Blue1Brown · Probability practice.

Bernoulli: a distribution over a binary observation

RR is a binary observation; rr is its probability of success.
R∼Bernoulli⁡(r)R\sim\operatorname{Bernoulli}(r) means “RR has a Bernoulli distribution,” 0≤r≤10\le r\le1.

P(R=0)=1−r,P(R=1)=r.P(R=0)=1-r,\qquad P(R=1)=r.

Three Bernoulli mass plots for r equal to 0.1, 0.5 and 0.9. Each has only outcomes zero and one. Their masses are 0.9 and 0.1, 0.5 and 0.5, and 0.1 and 0.9, respectively.

Does changing rr change the possible outcomes or their weights?

It changes their weights. At r=0r=0 or r=1r=1, one outcome has all the mass.

The symbol ∼\sim means “distributed as.” A single observation is still 0 or 1. Bishop, PRML §2.1.

Expectation and variance

Two discrete signed-error distributions on minus one, zero and one metres. Masses 0.1, 0.8, 0.1 give mean zero and variance 0.2 square metres; masses 0.4, 0.2, 0.4 give the same mean and variance 0.8 square metres.

Expectation: probability-weighted average.

μ=𝔼[X]=∑xxP(X=x).\mu=\mathbb E[X]=\sum_x xP(X=x).

Variance: average squared deviation.

Var⁡(X)=𝔼[(X−μ)2].\operatorname{Var}(X)=\mathbb E[(X-\mu)^2].

For Bernoulli: 𝔼[R]=0(1−r)+1r=r\mathbb E[R]=0(1-r)+1r=r, Var⁡(R)=r(1−r)\operatorname{Var}(R)=r(1-r).

Do equal means imply equal variances?

No: these plots have the same centre and different spread.

XX: random variable; xx: a possible value. Standard deviation SD⁡(X)=Var⁡(X)\operatorname{SD}(X)=\sqrt{\operatorname{Var}(X)} has the original units; variance has squared units. Bishop, PRML, Section 1.2.2.

Continuous probability is area under a density

A normal (Gaussian) distribution is a bell-shaped density.
X∼𝒩(μ,σ2)X\sim\mathcal N(\mu,\sigma^2): mean μ=0\mu=0 m; standard deviation σ=0.2\sigma=0.2 m; variance σ2\sigma^2.
pX(x)p_X(x) is the density of XX at a possible value xx.

P(a≤X≤b)=∫abpX(x)dx,∫pX(x)dx=1.P(a\le X\le b)=\int_a^b p_X(x)\,dx,\qquad \int p_X(x)\,dx=1.

Gaussian density for signed measurement error with mean zero and standard deviation 0.2 metres. Peak density is approximately 1.99 per metre. The shaded area between minus 0.2 and plus 0.2 metres is approximately 0.683.

Continuous weighted average: 𝔼[f(X)]=∫f(x)pX(x)dx\mathbb E[f(X)]=\int f(x)p_X(x)\,dx; f(X)f(X) is the quantity averaged.

Density at 0 m is about 1.99 per metre. What is P(X=0)P(X=0)?

P(X=0)=0P(X=0)=0. An interval has probability: P(−0.2≤X≤0.2)≈0.683P(-0.2\le X\le0.2)\approx0.683.

Density height has units 1/metre; probability is area. Gaussian density formula and location/scale · Bishop, PRML §§1.2.1, 2.3.

The same rules use sums or integrals

pX(x)p_X(x): mass of X=xX=x (discrete), or density at xx (continuous).
Joint: describe X,YX,Y together. Marginal: retain XX by summing/integrating out YY.

Rule Discrete Continuous
Normalize
p≥0p\ge0
∑xpX(x)=1\sum_x p_X(x)=1 ∫pX(x)dx=1\int p_X(x)\,dx=1
Eliminate YY pX(x)=∑ip(x,yi)p_X(x)=\sum_i p(x,y_i) pX(x)=∫p(x,y)dyp_X(x)=\int p(x,y)\,dy
Factor joint p(x,y)=p(x∣y)pY(y)p(x,y)=p(x\mid y)p_Y(y) p(x,y)=p(x∣y)pY(y)p(x,y)=p(x\mid y)p_Y(y)
Bayes p(y∣x)=p(x∣y)pY(y)∑kp(x∣yk)pY(yk)p(y\mid x)=\dfrac{p(x\mid y)p_Y(y)}{\sum_k p(x\mid y_k)p_Y(y_k)} p(y∣x)=p(x∣y)pY(y)∫p(x∣v)pY(v)dvp(y\mid x)=\dfrac{p(x\mid y)p_Y(y)}{\int p(x\mid v)p_Y(v)\,dv}

The denominator totals every possible explanation of the observed xx.

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.

Part 2 · A probability model explains the loss

  1. Probability
  2. Likelihood
  3. Bayesian inference
  4. KL
  5. VAE

Choose a distribution for observations.
Hold the observations fixed. Fit its parameters.

The negative log likelihood gives a loss.

Observed data → likelihood → loss

Observed pairs 𝒟={(xi,yi)}i=1n\mathcal D=\{(x_i,y_i)\}_{i=1}^n; fit parameters θ\theta.
iid: independent, identically distributed pairs.

Joint dataset likelihood

pθ(𝒟)=∏ipθ(xi,yi).p_\theta(\mathcal D)=\prod_i p_\theta(x_i,y_i).

Supervised: hold inputs fixed
Assume conditional independence:

pθ(y1:n∣x1:n)=∏ipθ(yi∣xi).p_\theta(y_{1:n}\mid x_{1:n})=\prod_i p_\theta(y_i\mid x_i).

Maximum likelihood estimation (MLE): maximize the conditional likelihood.

θ̂MLE=arg⁡maxθ∏ipθ(yi∣xi)=arg⁡minθ−∑iln⁡pθ(yi∣xi)⏟L(θ):negative log likelihood (NLL).\widehat\theta_{\mathrm{MLE}} =\arg\max_\theta\prod_i p_\theta(y_i\mid x_i) =\arg\min_\theta\underbrace{-\sum_i\ln p_\theta(y_i\mid x_i)}_{L(\theta):\ \text{negative log likelihood (NLL)}}.

Loss recipe: support → model + assumptions → constrained outputs → NLL → sum/mean

Choose the observation model before choosing the loss.

y1:n=(y1,…,yn)y_{1:n}=(y_1,\ldots,y_n). Natural-log loss is measured in nats. Mean NLL is L/nL/n; omit only parameter-independent terms. arg⁡max⁡/arg⁡min\arg\max/\arg\min selects maximizing/minimizing parameters. Bishop, PRML, Section 1.2.5.

Likelihood: fixed observations, variable parameters

Synthetic ordered sequence (1,0,0,1,0,0,0,1,0,0)(1,0,0,1,0,0,0,1,0,0): 3 rain, 7 dry.
Assume independent, identically distributed (iid) Bernoulli observations with constant rain probability rr.

ℓ(r;𝒟)=p(𝒟∣r)=r3⏟3 rain(1−r)7⏟7 dry. \ell(r;\mathcal D)=p(\mathcal D\mid r)=\underbrace{r^3}_{\text{3 rain}}\underbrace{(1-r)^7}_{\text{7 dry}}.

Each rain contributes rr; each dry day contributes 1−r1-r. Independence lets us multiply.

Likelihood of the fixed ordered ten-observation sequence versus candidate rain probability. It peaks at r=0.3, while r=0.8 explains the sequence poorly.

Fix the observations; vary rr. The peak at r=0.3r=0.3 is the MLE.

Likelihood scores the fixed data, not posterior uncertainty over rr. Bishop, PRML, Section 1.2.3 and §2.1.

Fixed Gaussian noise explains MSE

Real-valued target → Gaussian model → mean output → negative log

Three conditional Gaussian target densities at different fixed inputs, centered on different predicted means but with equal standard deviation. Observed targets are marked separately from the means.

yi∣xi,θ∼𝒩(μθ(xi),σ2),−ln⁡pθ(yi∣xi)=(yi−μθ(xi))22σ2+ln⁡σ+12ln⁡(2π). y_i\mid x_i,\theta\sim\mathcal N(\mu_\theta(x_i),\sigma^2),\qquad -\ln p_\theta(y_i\mid x_i)=\frac{(y_i-\mu_\theta(x_i))^2}{2\sigma^2}+\ln\sigma+\frac12\ln(2\pi).

Fixed common σ>0\sigma>0: the last two terms are constant in θ\theta. Mean NLL =MSE/(2σ2)+constant=\mathrm{MSE}/(2\sigma^2)+\text{constant}, where MSE=n−1∑i(yi−μθ(xi))2\mathrm{MSE}=n^{-1}\sum_i(y_i-\mu_\theta(x_i))^2.

MSE follows from a Gaussian model with fixed common observation variance.

Unequal fixed variances give weighted squared error. The RNN’s 12(ŷ−y)2\tfrac12(\widehat y-y)^2 uses unit variance, omitting a constant. This noise assumption is not implied by the CLT. Bishop, PRML §1.2.5.

Input-dependent Gaussian noise

Real-valued target → Gaussian model → mean and log-variance outputs

Three conditional Gaussian target densities with different predicted means and different standard deviations. Varying widths represent input-dependent observation noise, rather than uncertainty over network weights.

si=sθ(xi)=ln⁡σθ2(xi),Li=12[e−si(yi−μθ(xi))2+si]+12ln⁡(2π). s_i=s_\theta(x_i)=\ln\sigma_\theta^2(x_i),\qquad L_i=\frac12\left[e^{-s_i}(y_i-\mu_\theta(x_i))^2+s_i\right]+\frac12\ln(2\pi).

Derive this expression. Why must the sis_i term remain? Open the worked answer.

Increasing variance reduces the residual term; the log-variance term penalizes that inflation. Both outputs are fitted.

si∈ℝs_i\in\mathbb R gives positive variance esie^{s_i}. Heteroscedastic means input-dependent noise. With an exactly zero residual, unrestricted variance can collapse; constraints may be needed. Bishop, PRML §1.2.5.

Bernoulli observations explain BCE

Binary target y∈{0,1}y\in\{0,1\} → Bernoulli → logit aθ(x)a_\theta(x) → π=sigmoid⁡(aθ(x))\pi=\operatorname{sigmoid}(a_\theta(x))

pθ(y∣x)=πy(1−π)1−y⇒Li=−yln⁡π−(1−y)ln⁡(1−π). p_\theta(y\mid x)=\pi^y(1-\pi)^{1-y} \quad\Rightarrow\quad L_i=-y\ln\pi-(1-y)\ln(1-\pi).

Binary cross-entropy for each possible observed target. For y=1 it equals minus log pi; for y=0 it equals minus log(1-pi). Confidently wrong predictions have large loss.

Both outcomes contribute through the same Bernoulli formula.

For the rain sequence: L=−3ln⁡r−7ln⁡(1−r)L=-3\ln r-7\ln(1-r). Compute on logits for stability: PyTorch BCEWithLogitsLoss. Bishop, PRML §2.1.

Categorical observations explain multiclass CE

One class among CC → categorical → logits aca_c → πc=eac/∑jeaj\pi_c=e^{a_c}/\sum_j e^{a_j}

One-hot target tc∈{0,1}t_c\in\{0,1\}, ∑ctc=1\sum_c t_c=1; class probabilities ∑cπc=1\sum_c\pi_c=1.

pθ(t∣x)=∏c=1Cπctc⇒Li=−∑c=1Ctcln⁡πc=−ln⁡πobserved class. p_\theta(t\mid x)=\prod_{c=1}^C\pi_c^{t_c} \quad\Rightarrow\quad L_i=-\sum_{c=1}^C t_c\ln\pi_c=-\ln\pi_{\text{observed class}}.

Observed class: cat. Predicted probabilities: cat 0.7, dog 0.2, bird 0.1.
Which probabilities enter the loss?

Only the observed class: Li=−ln⁡(0.7)≈0.357L_i=-\ln(0.7)\approx0.357 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.

The output head and observation model must agree

Observation model Network output Negative log likelihood
Gaussian, fixed common variance Mean μθ(x)\mu_\theta(x) Scaled squared error + constant
Gaussian, learned variance Mean and log variance sθ(x)s_\theta(x) Weighted residual + log-scale term
Bernoulli One logit; sigmoid probability BCE
Categorical CC 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.

Part 3 · Update uncertainty with evidence

  1. Probability
  2. Likelihood
  3. Bayesian inference
  4. KL
  5. VAE

A prior describes uncertainty before these observations.
A posterior incorporates the observations.
Prediction carries the remaining uncertainty forward.

The elephant: a prior meets a noisy clue

Unknown mass m∼𝒩(4000,8002)m\sim\mathcal N(4000,800^2) kg.
Hypothetical report d=5000d=5000 kg; observation model d∣m∼𝒩(m,4002)d\mid m\sim\mathcal N(m,400^2).

Gaussian prior centered at 4000 kg, likelihood from a hypothetical 5000 kg report, and posterior centered at 4800 kg with standard deviation about 358 kg.

p(θ∣𝒟)=p(𝒟∣θ)p(θ)p(𝒟). p(\theta\mid\mathcal D)=\frac{p(\mathcal D\mid\theta)p(\theta)}{p(\mathcal D)}.

Multiply likelihood by prior, then normalize: here m∣d∼𝒩(4800,3582)m\mid d\sim\mathcal N(4800,358^2) approximately.

Hypothetical teaching values; exact posterior variance is 128000 kg². θ\theta 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.

The elephant: update one clue at a time

Three observers examine an elephant's tail, leg and trunk. Four conceptual mass distributions show a prior and successive updates after tail, leg and trunk evidence.

mm: unknown mass.
e1,e2,e3e_1,e_2,e_3: tail, leg, trunk clues.

Start: p0(m)=p(m)p_0(m)=p(m).

Tail: p1(m)∝p(e1∣m)p0(m).p_1(m)\propto p(e_1\mid m)p_0(m).

Leg: p2(m)∝p(e2∣m,e1)p1(m).p_2(m)\propto p(e_2\mid m,e_1)p_1(m).

Trunk: p3(m)∝p(e3∣m,e1,e2)p2(m).p_3(m)\propto p(e_3\mid m,e_1,e_2)p_2(m).

Normalize each curve to area one. This posterior becomes the next prior.

∝\propto means “proportional to”: normalization is omitted. Instructor-supplied conceptual illustration, not computed posteriors. Bishop, PRML, Section 1.2.3.

MLE, MAP, and a full posterior

Result Operation What do we keep?
MLE — maximum likelihood estimation Maximize p(𝒟∣θ)p(\mathcal D\mid\theta) One parameter setting at the likelihood peak
MAP — maximum a posteriori estimation Maximize p(θ∣𝒟)p(\theta\mid\mathcal D) One parameter setting at the posterior-density peak (mode)
Full posterior Normalize p(𝒟∣θ)p(θ)p(\mathcal D\mid\theta)p(\theta) 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).

Gaussian weight prior and quadratic penalty

Task: fit the data while expressing a preference for weights near zero.
Assume independent θj∼𝒩(0,τ2)\theta_j\sim\mathcal N(0,\tau^2); fixed τ\tau is the prior standard deviation.

p(θj)=12πτ2exp⁡(−θj22τ2)⇒−ln⁡p(θj)=θj22τ2+constant.p(\theta_j)=\frac{1}{\sqrt{2\pi\tau^2}}\exp\!\left(-\frac{\theta_j^2}{2\tau^2}\right) \quad\Rightarrow\quad -\ln p(\theta_j)=\frac{\theta_j^2}{2\tau^2}+\text{constant}.

Left: zero-centered Gaussian densities for prior standard deviations 0.5 and 1. Right: their quadratic negative log penalties after subtracting parameter-independent constants. The narrower prior gives a steeper penalty.

Sum over independent weights: −ln⁡p(θ)=∥θ∥22/(2τ2)+constant-\ln p(\theta)=\|\theta\|_2^2/(2\tau^2)+\text{constant}, where ∥θ∥22=∑jθj2\|\theta\|_2^2=\sum_j\theta_j^2.

Narrower prior (left) → steeper quadratic penalty (right).

τ\tau: weight-prior scale; σ\sigma: observation-noise scale. The next slide combines this penalty with NLL through MAP. Bishop, PRML, Section 1.2.6.

MAP produces L2 regularization

Extend the loss recipe: observation NLL + negative log prior → MAP

θ̂MAP=arg⁡minθ[−lnp(𝒟∣θ)−lnp(θ)]. \widehat\theta_{\mathrm{MAP}} =\arg\min_\theta\left[-\ln p(\mathcal D\mid\theta)-\ln p(\theta)\right].

=arg⁡minθ[∑i=1nLi(θ)+∥θ∥222τ2]. =\arg\min_\theta\left[\sum_{i=1}^n L_i(\theta)+\frac{\|\theta\|_2^2}{2\tau^2}\right].

Written objective Coefficient giving this MAP fit
Mean NLL +λ∥θ∥22+\lambda\|\theta\|_2^2 λ=1/(2nτ2)\lambda=1/(2n\tau^2)
MSE +λ∥θ∥22+\lambda\|\theta\|_2^2 λ=σ2/(nτ2)\lambda=\sigma^2/(n\tau^2)

The L2 coefficient depends on the loss scale and reduction.

Drop evidence, which is constant in θ\theta. MSE row assumes fixed common Gaussian variance σ2\sigma^2, with no factor ½ in MSE. MAP is point estimation; decoupled optimizer weight decay is not generally this objective. Bishop, PRML §1.2.6.

Prediction after fitting

One fitted parameter setting

pθ̂MAP(y*∣x*). p_{\widehat\theta_{\mathrm{MAP}}}(y_*\mid x_*).

Evaluate one model at the new input.

Posterior predictive

∫pθ(y*∣x*)p(θ∣𝒟)dθ. \int p_\theta(y_*\mid x_*)p(\theta\mid\mathcal D)\,d\theta.

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.

x*,y*x_*,y_* denote a future input and target. Rainfall prediction. Bishop, PRML §§1.2.3, 2.1.1.

Frequentist and Bayesian approaches to ML

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.

Part 4 · Compare distributions

  1. Probability
  2. Likelihood
  3. Bayesian inference
  4. KL
  5. VAE

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.

KL measures average extra log loss

Dry/rain reference frequencies: p=(0.7,0.3)p=(0.7,0.3).
Candidate predictions: q=(0.2,0.8)q=(0.2,0.8). Average outcomes using pp.

Aligned dry/rain bars: reference p=(0.7,0.3), candidate q=(0.2,0.8). The reference supplies the observation frequencies; the candidate assigns their probabilities.

For outcome aa, score with qq: −ln⁡q(a)-\ln q(a); reference score: −ln⁡p(a)-\ln p(a).
Extra log loss: −ln⁡q(a)−[−ln⁡p(a)]=ln⁡[p(a)/q(a)]-\ln q(a)-[-\ln p(a)]=\ln[p(a)/q(a)].

KL⁡(p‖q)=∑ap(a)ln⁡p(a)q(a)≈0.583nats.\operatorname{KL}(p\Vert q)=\sum_a p(a)\ln\frac{p(a)}{q(a)}\approx0.583\ \text{nats}.

The first argument supplies the averaging weights.

aa: dry or rain. Nats: units of log loss using natural logs. Here pp is empirical, not a known population law. Bishop, PRML, Section 1.6.1.

KL has a direction

Expression Average under Value
KL⁡(p‖q)\operatorname{KL}(p\Vert q) p=(0.7,0.3)p=(0.7,0.3) 0.583 nats
KL⁡(q‖p)\operatorname{KL}(q\Vert p) q=(0.2,0.8)q=(0.2,0.8) 0.534 nats
KL⁡(p‖p)\operatorname{KL}(p\Vert p) pp 0

KL is nonnegative; individual summands can be negative.
If p(a)>0p(a)>0 but q(a)=0q(a)=0, the forward KL is infinite.

For densities: KL⁡(p‖q)=∫p(u)ln⁡[p(u)/q(u)]du\operatorname{KL}(p\Vert q)=\int p(u)\ln[p(u)/q(u)]\,du.

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.

Part 5 · Infer and generate with a VAE

  1. Probability
  2. Likelihood
  3. Bayesian inference
  4. KL
  5. VAE

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 and VAE: point code or distribution

Two editable vector pipelines: a deterministic autoencoder sends an input through an encoder to one point code u, then a decoder reconstructs x. A VAE encoder predicts mean and log variance, defines a Gaussian, samples a code u, and decodes observation probabilities. A point and an axis-aligned ellipse contrast the latent representations.

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 p(u)p(u) and pθ(x∣u)p_\theta(x\mid u).

The VAE learns an approximate distribution of plausible codes for each image.

xx: image; uu: latent coordinate vector; θ\theta: decoder weights; ψ\psi: encoder weights. Paper z,ϕz,\phi become course u,ψu,\psi; course ϕ\phi remains an activation. Kingma & Welling, §§2–3.

Generation and inference

Generation: draw u from the prior, evaluate decoder observation probabilities, then sample x. Inference reverses the question: given x, which u could explain it?

pθ(x,u)=p(u)pθ(x∣u).p_\theta(x,u)=p(u)p_\theta(x\mid u).

Generate: u∼p(u)u\sim p(u), then x∼pθ(x∣u)x\sim p_\theta(x\mid u).

Infer: given xx, find plausible uu using pθ(u∣x)p_\theta(u\mid x).

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.

Bayes for a two-pixel image

Prior p(u=0)=p(u=1)=0.5p(u=0)=p(u=1)=0.5; pixels are independent given the code.

Code p(x1=1∣u)p(x_1=1\mid u) p(x2=1∣u)p(x_2=1\mid u) p((1,0)∣u)p((1,0)\mid u)
u=0u=0 0.8 0.2 0.8(1−0.2)=0.640.8(1-0.2)=0.64
u=1u=1 0.3 0.7 0.3(1−0.7)=0.090.3(1-0.7)=0.09

p(x=(1,0))=0.5(0.64)+0.5(0.09)=0.365.p(x=(1,0))=0.5(0.64)+0.5(0.09)=0.365. p(u∣x)=p(x∣u)p(u)p(x)=(64/73,9/73)≈(0.877,0.123).p(u\mid x)=\frac{p(x\mid u)p(u)}{p(x)}=(64/73,9/73)\approx(0.877,0.123).

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.

The posterior needs an evidence integral

For continuous codes, use a spherical standard-normal prior:
independent u1,u2∼𝒩(0,1)u_1,u_2\sim\mathcal N(0,1), written u∼𝒩(0,I2)u\sim\mathcal N(0,I_2).
Covariance averages the product of two variables’ deviations from their means.
I2I_2 is the identity covariance: unit variance in each coordinate and zero covariance between them.

pθ(u∣x)=pθ(x∣u)p(u)∫pθ(x∣v)p(v)dv⏟pθ(x).p_\theta(u\mid x)=\frac{p_\theta(x\mid u)p(u)}{\underbrace{\int p_\theta(x\mid v)p(v)\,dv}_{p_\theta(x)}}.

At one code

The decoder can evaluate pθ(x∣u)p_\theta(x\mid u).

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. vv is a dummy integration variable. Continuous variables alone do not imply intractability; model structure matters. Kingma & Welling, §2.1; Bishop, PRML §10.1.

The encoder proposes an approximate posterior

Given xx, the encoder predicts centre μu(x)\mu_u(x) and spreads σu(x)\sigma_u(x).
Under qq, the two coordinates are independent:

uj∣x∼𝒩(μu,j(x),σu,j2(x)),j=1,2.u_j\mid x\sim\mathcal N(\mu_{u,j}(x),\sigma_{u,j}^2(x)),\qquad j=1,2.

Left: one deterministic latent point. Right: a two-dimensional diagonal Gaussian approximation shown as a center and an axis-aligned standard-deviation ellipse; its widths can differ between coordinates.

Different coordinate spreads → an axis-aligned ellipse; equal spreads → a circle.

qψ(u∣x)=𝒩(μu(x),diag(σu2(x))).q_\psi(u\mid x)=\mathcal N\!\left(\mu_u(x),\operatorname{diag}(\sigma_u^2(x))\right).

diag\operatorname{diag}: coordinate variances on the diagonal; zeros elsewhere.

Encoder outputs μu\mu_u and logvaru=ln⁡σu2\mathrm{logvar}_u=\ln\sigma_u^2; σu=exp⁡(12logvaru)\sigma_u=\exp(\tfrac12\mathrm{logvar}_u). Covariance practice. Kingma & Welling, §3.

Bayes explains the ELBO

We need a training objective even when the exact latent posterior is hard to compute.
q=qψ(u∣x)q=q_\psi(u\mid x) is the encoder’s approximation; 𝔼q\mathbb E_q averages over its possible codes.

ln⁡pθ(x)=ℰ⏟evidence lower bound (ELBO)+KL⁡(q‖pθ(u∣x))⏟nonnegative posterior gap.\ln p_\theta(x)=\underbrace{\mathcal E}_{\text{evidence lower bound (ELBO)}} +\underbrace{\operatorname{KL}(q\Vert p_\theta(u\mid x))}_{\text{nonnegative posterior gap}}.

Bayes and the definition of KL give a usable expression:

ℰ=𝔼q[ln⁡pθ(x,u)−ln⁡qψ(u∣x)].\mathcal E=\mathbb E_q[\ln p_\theta(x,u)-\ln q_\psi(u\mid x)].

Log evidence ln⁡pθ(x)\ln p_\theta(x):
how well the generative model explains xx after averaging over the prior.

Posterior gap:
how far the encoder’s qq is from the exact posterior.

The gap cannot be negative: ℰ≤ln⁡pθ(x)\mathcal E\le\ln p_\theta(x).

Matching the exact posterior makes the bound exact. Line-by-line derivation and return link. Kingma & Welling, §2.2.

Tightening the lower bound

ELBO versus approximate posterior mass on code zero. For a fixed generative toy model, log evidence is a fixed horizontal upper line; the ELBO reaches it at posterior mass 64/73. The marked approximation 0.7 leaves a positive KL gap.

Hold the decoder and prior fixed. What changes when qq 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.

Two computable ELBO terms

Use the product rule pθ(x,u)=pθ(x∣u)p(u)p_\theta(x,u)=p_\theta(x\mid u)p(u):

ℰ=𝔼q[ln⁡pθ(x∣u)]⏟explain the observed image−KL⁡(qψ(u∣x)‖p(u))⏟compare to the prior.\mathcal E= \underbrace{\mathbb E_q[\ln p_\theta(x\mid u)]}_{\text{explain the observed image}} -\underbrace{\operatorname{KL}(q_\psi(u\mid x)\Vert p(u))}_{\text{compare to the prior}}.

If qq 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 LVAE=−ℰ=L_{\mathrm{VAE}}=-\mathcal E= 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.

The reparameterization trick

Problem: how can reconstruction gradients pass through a random draw to the encoder?
Draw noise independently of the encoder, then transform it:

ϵ∼𝒩(0,I2),u=μu+σu⊙ϵ.\epsilon\sim\mathcal N(0,I_2),\qquad u=\mu_u+\sigma_u\odot\epsilon.

Same six noise values reused as mean shifts and scale contracts. Each code is a differentiable transformation of fixed sampled noise and the encoder outputs.

Same noise: μu\mu_u shifts samples; σu\sigma_u changes spread.
Fix ϵ\epsilon during backpropagation: uu is differentiable in both outputs.

Reconstruction gradient → sampled code → mean and spread → encoder weights.

⊙\odot: coordinatewise multiplication. Sample fresh noise on later forward passes. Kingma & Welling, §2.4.

The binary-image VAE loss

Thresholded MNIST: xj∈{0,1}x_j\in\{0,1\}; decoder logits ax,j(u)a_{x,j}(u) give πx,j=sigmoid⁡(ax,j)\pi_{x,j}=\operatorname{sigmoid}(a_{x,j}).

−ln⁡pθ(x∣u)⏟reconstruction NLL=−∑j=1784[xjln⁡πx,j+(1−xj)ln⁡(1−πx,j)].\underbrace{-\ln p_\theta(x\mid u)}_{\text{reconstruction NLL}} =-\sum_{j=1}^{784}[x_j\ln\pi_{x,j}+(1-x_j)\ln(1-\pi_{x,j})].

KL⁡(qψ‖𝒩(0,I))⏟latent prior KL=12∑j=12[μu,j2+σu,j2−1−ln⁡σu,j2].\underbrace{\operatorname{KL}(q_\psi\Vert\mathcal N(0,I))}_{\text{latent prior KL}} =\frac12\sum_{j=1}^{2}[\mu_{u,j}^2+\sigma_{u,j}^2-1-\ln\sigma_{u,j}^2].

Sum pixels and latent coordinates per image, then average images.
Standard VAE uses coefficient 1 on prior KL; βVAE≠1\beta_{\mathrm{VAE}}\ne1 changes the objective.

Pixels conditionally independent given uu; compute BCE on logits. Latent dimension is 2 in this pilot. Gaussian KL derivation · Implementation and pilot settings. Kingma & Welling, Appendices B/C.

Reconstruction: decode an observed image’s mean code

Mean code: the encoder’s two-coordinate centre μu(x)\mu_u(x).
x→μu(x)→decoder⁡→πxx\ \to\ \mu_u(x)\ \to\ \operatorname{decoder}\ \to\ \pi_x (pixel probabilities).

Ten fixed validation examples, one per digit, shown as original grayscale sources, thresholded binary observations, and pixel-probability images decoded from their encoder mean codes. Several digits reconstruct imperfectly in the two-dimensional VAE.

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 μu(x)\mu_u(x) for this deterministic display. Existing MNIST pilot: β=1\beta=1; validation images; test set unused.

A latent map shows what the encoder learned

Reading task: where does the encoder place each validation image?

Encoder means of 2,000 validation images in two latent coordinates, colored by digit label. Several classes overlap. Four axis-aligned ellipses illustrate posterior spreads for selected images.

One dot: one image’s mean code μu(x)\mu_u(x).
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 β=1\beta=1. Ellipses show model spread, not calibrated confidence. Original MNIST pilot.

Generate a new image from the prior

  1. Draw a code: two independent standard-normal coordinates, u∼𝒩(0,I2)u\sim\mathcal N(0,I_2).
  2. Decode probabilities: πx=sigmoid⁡(decoder⁡(u))\pi_x=\operatorname{sigmoid}(\operatorname{decoder}(u)) for 784 pixels.
  3. Sample an image: xj∼Bernoulli⁡(πx,j)x_j\sim\operatorname{Bernoulli}(\pi_{x,j}) for each pixel.

Twelve independent latent prior draws decoded by the baseline model. Top row shows pixel probabilities; bottom row shows sampled binary pixels drawn from those same probabilities, which can look noisy.

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. I2I_2: unit coordinate variances, zero covariance. Baseline β=1\beta=1, predeclared gallery; original pilot.

One argument answers three questions

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.

Person of the day: Diederik P. Kingma

Instructor-supplied pencil-style portrait of Diederik P. (Durk) Kingma.

Diederik P. (Durk) Kingma

  • Coauthored Auto-Encoding Variational Bayes with Max Welling (2013 preprint).
  • Coauthored Adam with Jimmy Ba (2014 preprint).
  • PhD, University of Amsterdam, 2017, advised by Welling.

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.

Tutorial: predict, compute, and interpret

Rainfall

Same observations: likelihood → MLE → prior/posterior → prediction.
Explain which object describes data and which describes uncertainty about rr.

VAE

Identify inferred codes and fitted weights.
Explain reconstruction, latent maps, generation, and the sampling gradient path.

State the model → predict → compute → explain.

Reading: gradients and probability

Reading: latent-variable inference

Elephant graphical abstract supplied by the instructor. RNN diagrams redraw the Week 06 model; diagrams and sensitivity plots are original course figures.

Optional depth begins here

The main lecture is complete. Use the following slides for practice or selected live derivations.

Open the practice menu.

Cross-entropy is entropy plus KL

H(p,q)=𝔼p[−ln⁡q(A)]=H(p)⏟𝔼p[−ln⁡p(A)]+KL⁡(p‖q). H(p,q)=\mathbb E_p[-\ln q(A)] =\underbrace{H(p)}_{\mathbb E_p[-\ln p(A)]}+\operatorname{KL}(p\Vert q).

Our 7 dry and 3 rain observations define p̂=(0.7,0.3)\widehat p=(0.7,0.3):

Ln=−0.7ln⁡0.2−0.3ln⁡0.8≈0.611+0.583≈1.19nats. \frac Ln=-0.7\ln0.2-0.3\ln0.8 \approx0.611+0.583\approx1.19\ \text{nats}.

When pp is fixed, which term changes as we fit qq?

Only KL changes. Minimizing empirical categorical cross-entropy minimizes KL⁡(p̂‖q)\operatorname{KL}(\widehat p\Vert q). One-hot CE is −ln⁡πobserved class-\ln\pi_{\text{observed class}}.

H(p)H(p) 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.

RNN practice: the full backward ledger

Same tanh example: gzt=ght(1−ht2)g_{z_t}=g_{h_t}(1-h_t^2), ght−1=whgztg_{h_{t-1}}=w_hg_{z_t}.

Backward order ghtg_{h_t} 1−ht21-h_t^2 gztg_{z_t}
t=2t=2 −0.412 0.964 −0.397
t=1t=1 −0.318 0.696 −0.221
t=0t=0 −0.177 0.786 −0.139

Use these sensitivities to calculate all three parameter gradients.

∂L∂wx=gz0(1)+gz1(0.5)+gz2(−0.5)≈−0.0513,∂L∂wh=0+gz1h0+gz2h1≈−0.321,∂L∂wo=(ŷ−y)h2≈−0.0776. \begin{aligned} \frac{\partial L}{\partial w_x}&=g_{z_0}(1)+g_{z_1}(0.5)+g_{z_2}(-0.5)\approx-0.0513,\\ \frac{\partial L}{\partial w_h}&=0+g_{z_1}h_0+g_{z_2}h_1\approx-0.321,\\ \frac{\partial L}{\partial w_o}&=(\widehat y-y)h_2\approx-0.0776. \end{aligned}

Calculate with full precision; displayed values are rounded. Return to checkpoint · Check with code.

Match the arithmetic to a short computation

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.

Optional practice: probability

Use the same counts to check your reasoning. Each task has a worked answer revealed by a click.

  1. Marginal and conditional probabilities
  2. Weighted total probability
  3. Independence and mutual exclusivity
  4. Conditional independence

Public, ungraded lecture practice. Return to Steve · Continue with continuous probability.

Practice: marginal and conditional probabilities

Signal absent Signal present Total
Dry 54 6 60
Rain 16 24 40
Total 70 30 100

Find p(R=1)p(R=1), p(S=1)p(S=1), p(R=1∣S=1)p(R=1\mid S=1), and p(S=1∣R=1)p(S=1\mid R=1). Which denominators change?

p(R=1)=40/100=0.4,p(S=1)=30/100=0.3,p(R=1∣S=1)=24/30=0.8,p(S=1∣R=1)=24/40=0.6.\begin{aligned} p(R=1)&=40/100=0.4, &p(S=1)&=30/100=0.3,\\ p(R=1\mid S=1)&=24/30=0.8, &p(S=1\mid R=1)&=24/40=0.6. \end{aligned}

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.

Practice: total probability uses group weights

Given the same table:

p(R=1∣S=1)=2430,p(R=1∣S=0)=1670,p(S=1)=0.3.p(R=1\mid S=1)=\frac{24}{30},\quad p(R=1\mid S=0)=\frac{16}{70},\quad p(S=1)=0.3.

Recover p(R=1)p(R=1). Why would an unweighted average of the two conditionals fail?

p(R=1)=∑s∈{0,1}p(R=1∣S=s)p(S=s)p(R=1)=\sum_{s\in\{0,1\}}p(R=1\mid S=s)p(S=s) =243030100+167070100=0.4.=\frac{24}{30}\frac{30}{100}+\frac{16}{70}\frac{70}{100}=0.4.

The groups contain 30 and 70 observations. Giving them equal weight would yield approximately 0.5140.514, 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.

Practice: independent or mutually exclusive?

R⟂S⇔p(R=a,S=b)=p(R=a)p(S=b)for every a,b.R\perp S\ \Longleftrightarrow\ p(R=a,S=b)=p(R=a)p(S=b)\quad\text{for every }a,b.

Are rain and signal independent in our table? Can two mutually exclusive events with positive probability be independent?

Rain and signal: p(R=1,S=1)=0.24p(R=1,S=1)=0.24, whereas p(R=1)p(S=1)=0.4(0.3)=0.12p(R=1)p(S=1)=0.4(0.3)=0.12. 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.

Practice: independence after conditioning

A separate hypothetical sensor model

Rain R is the common parent of sensor signals F1 and F2. The declared model makes the signals independent conditional on rain, while mixing rain and dry groups can make them marginally dependent.

p(F1,F2∣R)=p(F1∣R)p(F2∣R).p(F_1,F_2\mid R)=p(F_1\mid R)p(F_2\mid R).

Each sensor has p(Fi=1∣R=1)=0.6p(F_i=1\mid R=1)=0.6, p(Fi=1∣R=0)=0.1p(F_i=1\mid R=0)=0.1; let p(R=1)=0.4p(R=1)=0.4.

Does conditional independence imply marginal independence? Compare p(F1=1,F2=1)p(F_1=1,F_2=1) with p(F1=1)p(F2=1)p(F_1=1)p(F_2=1).

p(Fi=1)=0.4(0.6)+0.6(0.1)=0.3;p(F_i=1)=0.4(0.6)+0.6(0.1)=0.3; p(F1=1,F2=1)=0.4(0.6)2+0.6(0.1)2=0.15≠0.32.p(F_1=1,F_2=1)=0.4(0.6)^2+0.6(0.1)^2=0.15\ne0.3^2.

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.

Optional practice: distributions and moments

Explore the longer calculations. Each fixed question has a worked answer revealed by a click.

  1. CDF and interval probability
  2. Beta: a density over a probability
  3. Covariance and dependence
  4. Gaussian location and scale
  5. When a normal approximation helps
  6. Multivariable rules

Public, ungraded lecture practice. Return to the rules · Continue to likelihood.

The CDF accumulates probability up to a boundary

FX(a)=P(X≤a)=∫−∞apX(x)dx.F_X(a)=P(X\le a)=\int_{-\infty}^{a}p_X(x)\,dx.

CDF of the zero-mean Gaussian error with standard deviation 0.2 metres. Its values at minus 0.2 and plus 0.2 metres are 0.159 and 0.841. The CDF rises monotonically from zero to one.

Use the two marked values to find P(−0.2≤X≤0.2)P(-0.2\le X\le0.2).

P(−0.2≤X≤0.2)=FX(0.2)−FX(−0.2)≈0.683.P(-0.2\le X\le0.2)=F_X(0.2)-F_X(-0.2)\approx0.683.

Rounded labels give 0.682; the full-precision calculation rounds to 0.683.

Same Gaussian as the core slide. FX′(x)=pX(x)F_X'(x)=p_X(x) where differentiable. Bishop, PRML §1.2.1. Practice menu · Return to density.

Beta: a density over a possible probability parameter

p(r)=rα−1(1−r)b0−1B(α,b0),0<r<1,α,b0>0.p(r)=\frac{r^{\alpha-1}(1-r)^{b_0-1}}{B(\alpha,b_0)},\qquad 0<r<1,\quad \alpha,b_0>0.

Beta(1,1) has uniform density over r. Beta(2,3) and Beta(8,12) both have mean 0.4, with Beta(8,12) narrower. All three curves integrate to one.

Do these curves describe a binary observation, or uncertainty over its probability rr?

Uncertainty over rr. The common mean is α/(α+b0)=0.4\alpha/(\alpha+b_0)=0.4 for Beta(2,3) and Beta(8,12); their variances are 0.040.04 and about 0.01140.0114.

B(α,b0)B(\alpha,b_0) normalizes the density. These are example models, not successive updates. Bishop, PRML §2.1.1. Practice menu · Return to Bernoulli.

Covariance describes how two variables vary together

Cov⁡(X,Y)=𝔼[(X−𝔼[X])(Y−𝔼[Y])]=𝔼[XY]−𝔼[X]𝔼[Y].\operatorname{Cov}(X,Y)=\mathbb E[(X-\mathbb E[X])(Y-\mathbb E[Y])] =\mathbb E[XY]-\mathbb E[X]\mathbb E[Y].

The rain/signal table

Cov⁡(R,S)=0.24−(0.4)(0.3)=0.12.\operatorname{Cov}(R,S)=0.24-(0.4)(0.3)=0.12.

Correlation divides by both standard deviations:

Corr⁡(R,S)=Cov⁡(R,S)SD⁡(R)SD⁡(S)≈0.535.\operatorname{Corr}(R,S)=\frac{\operatorname{Cov}(R,S)}{\operatorname{SD}(R)\operatorname{SD}(S)}\approx0.535.

Does zero covariance guarantee independence?

No. Let UU be uniform on {−1,0,1}\{-1,0,1\} and V=U2V=U^2.

UU −1 0 1
VV 1 0 1

𝔼[U]=𝔼[UV]=0\mathbb E[U]=\mathbb E[UV]=0, so Cov⁡(U,V)=0\operatorname{Cov}(U,V)=0. Yet VV is determined by UU 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.

Gaussian: location and scale for continuous values

pX(x)=12πσ2exp⁡[−(x−μ)22σ2],σ>0.p_X(x)=\frac{1}{\sqrt{2\pi\sigma^2}}\exp\!\left[-\frac{(x-\mu)^2}{2\sigma^2}\right],\qquad \sigma>0.

Normal densities with mean and standard deviation (0,0.2), (0.4,0.2), and (0,0.4). Shifting the mean shifts the curve. Increasing standard deviation spreads it and lowers its peak with unit area preserved.

Which parameter shifts the curve? Which parameter changes its width?

μ\mu sets location; σ\sigma sets spread. 𝒩(μ,σ2)\mathcal N(\mu,\sigma^2) has mean μ\mu and variance σ2\sigma^2. All these densities have unit area.

Gaussian support is the real line. Bishop, PRML §§1.2.4, 2.3. Practice menu · Return to density.

A normal approximation can help with counts

K∼Binomial⁡(n,r)K\sim\operatorname{Binomial}(n,r) counts nn independent Bernoulli(rr) trials, 0<r<10<r<1.
Use G∼𝒩(nr,nr(1−r))G\sim\mathcal N(nr,nr(1-r)). Orange points show P(k−0.5≤G≤k+0.5)P(k-0.5\le G\le k+0.5).

Exact binomial count masses versus Gaussian probabilities in matching unit-width bins. For 40 trials and r=0.5, the two nearly coincide. For 20 trials and r=0.02, the approximation misses the strong mass at zero and puts about 7.5 percent outside the bins for allowed counts.

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.

Same moments, different count probabilities

Rare-event example: K∼Binomial⁡(20,0.02)K\sim\operatorname{Binomial}(20,0.02); G∼𝒩(0.4,0.392)G\sim\mathcal N(0.4,0.392) is the matching Gaussian approximation.

Quantity Binomial KK Gaussian GG
Mean 0.4 0.4
Variance 0.392 0.392
Zero / zero bin P(K=0)≈0.668P(K=0)\approx0.668 P(−0.5≤G≤0.5)≈0.488P(-0.5\le G\le0.5)\approx0.488
Outside [−0.5,20.5][-0.5,20.5] 0 About 7.53%

Only nr=0.4nr=0.4 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.

Probability rules extend to many variables

Write x1:m=(x1,…,xm)x_{1:m}=(x_1,\ldots,x_m), with 1≤m<k1\le m<k. Shading marks the variables eliminated.

Marginalize the joint over every remaining coordinate

p(x1:m)=p(x_{1:m})= ∑xm+1,…,xk\sum_{x_{m+1},\ldots,x_k} p(x1:k)p(x_{1:k}) (discrete)

p(x1:m)=∫p(x1:k)p(x_{1:m})=\int p(x_{1:k}) dxm+1⋯dxkdx_{m+1}\cdots dx_k (continuous)

Chain rule: factor the joint in a chosen order

p(x1:m)=p(x1)∏j=2mp(xj∣x1:j−1).p(x_{1:m})=p(x_1)\prod_{j=2}^{m}p(x_j\mid x_{1:j-1}).

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 m=1m=1, the empty product is one. Bishop, PRML §§1.2, 8.2. Practice menu · Return to the rules.

Worked answer: input-dependent Gaussian loss

Start with the scalar Gaussian negative log density:

−ln⁡p(yi∣xi)=(yi−μi)22σi2+ln⁡σi+12ln⁡(2π). -\ln p(y_i\mid x_i)=\frac{(y_i-\mu_i)^2}{2\sigma_i^2}+\ln\sigma_i+\frac12\ln(2\pi).

Substitute si=ln⁡σi2s_i=\ln\sigma_i^2: σi−2=e−si\sigma_i^{-2}=e^{-s_i} and ln⁡σi=si/2\ln\sigma_i=s_i/2.

Li=12[e−si(yi−μi)2+si]+12ln⁡(2π). L_i=\frac12\left[e^{-s_i}(y_i-\mu_i)^2+s_i\right]+\frac12\ln(2\pi).

Writing ei=yi−μie_i=y_i-\mu_i, ∂Li/∂si=12(1−e−siei2)\partial L_i/\partial s_i=\tfrac12(1-e^{-s_i}e_i^2). For fixed nonzero residual, the optimum is σi2=ei2\sigma_i^2=e_i^2. Without si/2s_i/2, arbitrarily large variance drives the residual term toward zero.

The constant can be omitted; the fitted log-variance term cannot.

If ei=0e_i=0, si→−∞s_i\to-\infty 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.

Rainfall: the Beta prior gives an exact update

p(r)∝rα−1(1−r)b0−1,p(𝒟∣r)=rk(1−r)n−k. p(r)\propto r^{\alpha-1}(1-r)^{b_0-1},\qquad p(\mathcal D\mid r)=r^k(1-r)^{n-k}.

p(r∣𝒟)∝rα+k−1(1−r)b0+n−k−1⇒r∣𝒟∼Beta⁡(α+k,b0+n−k). p(r\mid\mathcal D)\propto r^{\alpha+k-1}(1-r)^{b_0+n-k-1} \quad\Rightarrow\quad r\mid\mathcal D\sim\operatorname{Beta}(\alpha+k,b_0+n-k).

Prior Beta(2,3) and posterior Beta(5,10) after three rain events in ten observations. The posterior places more mass near a rain probability of one third.

Beta(2,3) + 3 rain + 7 dry → Beta(5,10).

Conjugacy: the posterior remains in the prior’s distribution family. Constant rr, common Bernoulli model, conditionally independent observations. Real weather may violate these assumptions. Bishop, PRML §2.1.1. Practice menu.

Same prior mean, different resistance to evidence

m0=αα+b0,κ=α+b0,𝔼[r∣𝒟]=κκ+nm0+nκ+nkn. m_0=\frac{\alpha}{\alpha+b_0},\quad\kappa=\alpha+b_0, \qquad \mathbb E[r\mid\mathcal D] =\frac{\kappa}{\kappa+n}m_0+\frac{n}{\kappa+n}\frac{k}{n}.

Two panels compare weak Beta(2,3) and strong Beta(20,30) priors, both with mean 0.4. Dashed curves are priors and solid curves are posteriors. After 3 of 10 rain observations the stronger prior has more influence; after 30 of 100 the posterior means are closer to the observed fraction 0.3.

Change only κ\kappa: which posterior mean moves further toward k/n=0.30k/n=0.30?

The weak prior moves farther: posterior mean 0.333 versus 0.383 after 3 of 10 rain observations.

Dashed = prior; solid = posterior. Synthetic datasets: (n,k)=(10,3)(n,k)=(10,3) and (100,30)(100,30). Fixed prior influence decreases in this model as nn grows. n>0n>0 in the displayed weighted-average identity. Bishop, PRML §2.1.1. Practice menu.

A posterior density is not a forecast of rain counts

Let KK count rain events in q=10q=10 future observations.
Given rr, use K∣r∼Binomial⁡(q,r)K\mid r\sim\operatorname{Binomial}(q,r); retain the same model assumptions.

p(K=j∣𝒟)=∫01p(K=j∣r)p(r∣𝒟)dr. p(K=j\mid\mathcal D)=\int_0^1p(K=j\mid r)\,p(r\mid\mathcal D)\,dr.

Left: Beta(5,10) posterior density over rain probability. Right: probability masses for rain count in ten future observations. The posterior-integrated Beta-binomial prediction is more spread out than a Binomial prediction using fixed probability one third; both have mean ten thirds.

Same mean count, different spread: integrating uncertainty changes the prediction.

Beta-binomial variance ≈3.47\approx3.47; plug-in Binomial variance ≈2.22\approx2.22. Axes represent different variables and units. A credible interval for rr is not a prediction interval for KK. Original calculation from the predictive integral; Bishop, PRML §2.1.1. Practice menu.

ELBO algebra from Bayes

For q=qψ(u∣x)q=q_\psi(u\mid x), insert Bayes into the definition of KL:

KL⁡(q‖pθ(u∣x))=𝔼q[ln⁡q−ln⁡pθ(u∣x)]=𝔼q[ln⁡q−ln⁡pθ(x,u)+ln⁡pθ(x)]=−ℰ+ln⁡pθ(x).\begin{aligned} \operatorname{KL}(q\Vert p_\theta(u\mid x)) &=\mathbb E_q[\ln q-\ln p_\theta(u\mid x)]\\ &=\mathbb E_q[\ln q-\ln p_\theta(x,u)+\ln p_\theta(x)]\\ &=-\mathcal E+\ln p_\theta(x). \end{aligned}

Evidence does not depend on the code, so it leaves the expectation.
Rearrange: ℰ=ln⁡pθ(x)−KL⁡(q‖posterior)≤ln⁡pθ(x)\mathcal E=\ln p_\theta(x)-\operatorname{KL}(q\Vert\text{posterior})\le\ln p_\theta(x).

Appropriate support and finite expectations assumed. Return to ELBO. Kingma & Welling, §2.2.

Gaussian KL: take the expectation

For independent coordinates of q=𝒩(μ,diag⁡(σ2))q=\mathcal N(\mu,\operatorname{diag}(\sigma^2)), p=𝒩(0,I)p=\mathcal N(0,I):

ln⁡q(u)p(u)=12∑j[−lnσj2−(uj−μj)2σj2+uj2].\ln\frac{q(u)}{p(u)}=\frac12\sum_j\left[-\ln\sigma_j^2-\frac{(u_j-\mu_j)^2}{\sigma_j^2}+u_j^2\right].

Use 𝔼q[(uj−μj)2]=σj2\mathbb E_q[(u_j-\mu_j)^2]=\sigma_j^2 and 𝔼q[uj2]=μj2+σj2\mathbb E_q[u_j^2]=\mu_j^2+\sigma_j^2:

KL⁡(q‖p)=12∑j[μj2+σj2−1−ln⁡σj2].\operatorname{KL}(q\Vert p)=\frac12\sum_j[\mu_j^2+\sigma_j^2-1-\ln\sigma_j^2].

Each coordinate’s contribution is zero at μj=0\mu_j=0, σj2=1\sigma_j^2=1.

This is KL to the prior, not to the model posterior. Return to image loss. Kingma & Welling, Appendix B.

Check the signs with the exact toy

For x=(1,0)x=(1,0) and q(u∣x)=(0.7,0.3)q(u\mid x)=(0.7,0.3):

Quantity Calculation Nats
Reconstruction log likelihood 0.7ln⁡0.64+0.3ln⁡0.090.7\ln0.64+0.3\ln0.09 −1.03
Prior KL KL⁡((0.7,0.3)‖(0.5,0.5))\operatorname{KL}((0.7,0.3)\Vert(0.5,0.5)) 0.0823
ELBO Reconstruction log likelihood − prior KL −1.12
Posterior gap KL⁡(q‖(64/73,9/73))\operatorname{KL}(q\Vert(64/73,9/73)) 0.109

ln⁡0.365≈−1.01(ℰ+gap checked before rounding). \ln0.365\approx-1.01\quad(\mathcal E+\mathrm{gap}\text{ checked before rounding}).

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.

What produced the figures we are about to inspect?

Fixed choice Pilot setting
Data 12,000 training + 2,000 disjoint validation images from MNIST’s training split
Observation Pixel/255 >0.5>0.5; all ten digit classes retained
Optimization 15 epochs, batch 256, Adam learning rate 0.001; 705 updates/model
Comparison βVAE∈{0.1,1,4}\beta_{\mathrm{VAE}}\in\{0.1,1,4\}; 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.

Sum coordinates, then average images

reconstruction = F.binary_cross_entropy_with_logits(
    pixel_logits, x, reduction="none"
).sum(dim=1)                         # 784 pixel terms → (B,)
kl = 0.5 * (
    mu.square() + logvar.exp() - 1 - logvar
).sum(dim=1)                         # 2 latent terms → (B,)
loss = (reconstruction + beta_vae * kl).mean()  # images → scalar

L̂β=1B∑i=1B[−lnpθ(xi∣ui)+βVAEKL(qψ(u∣xi)‖p(u))]. \widehat L_\beta =\frac1B\sum_{i=1}^{B}\left[ -\ln p_\theta(x_i\mid u_i) +\beta_{\mathrm{VAE}}\operatorname{KL}(q_\psi(u\mid x_i)\Vert p(u))\right].

At βVAE=1\beta_{\mathrm{VAE}}=1, 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.

This pilot measured two competing pressures

Validation curves for three matched runs. At epoch fifteen, reconstruction NLL is about 165.63, 169.49 and 171.27 nats per image for beta 0.1, 1 and 4. Latent KL is about 18.32, 5.54 and 3.00 respectively.

In this run, larger β\beta 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.

Compare the same latent region across models

Three nine-by-nine grids of decoder pixel probabilities for beta 0.1, 1 and 4, using the same latent-coordinate grid from minus two to two. Coverage and digit-like forms differ between models; each cell is a chosen coordinate rather than an independent prior draw.

Open discussion: compare recognizable and ambiguous regions. Expect differences in coverage; this grid alone cannot establish generation quality.

Chosen 9×99\times9 coordinates in [−2,2]2[-2,2]^2, 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.

Naive Bayes: two binary features

Toy classes A,BA,B; stipulated model probabilities, not estimates from counts.

Class Prior p(F1=1∣C)p(F_1=1\mid C) p(F2=1∣C)p(F_2=1\mid C)
AA 0.4 0.8 0.7
BB 0.6 0.2 0.3

Observe both features equal 1. Find p(A∣F1=1,F2=1)p(A\mid F_1=1,F_2=1). What permits the product?

Assume F1⟂F2∣CF_1\perp F_2\mid C: scores are sA=0.4(0.8)(0.7)=0.224s_A=0.4(0.8)(0.7)=0.224 and sB=0.036s_B=0.036. Normalize: p(A∣F1,F2)=0.224/0.260≈0.862p(A\mid F_1,F_2)=0.224/0.260\approx0.862.

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.

Observation noise and parameter uncertainty

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: Var⁡(y*∣x*,𝒟)=𝔼θ[Var⁡(y*∣x*,θ)]+Var⁡θ[𝔼(y*∣x*,θ)].\operatorname{Var}(y_*\mid x_*,\mathcal D)= \mathbb E_\theta[\operatorname{Var}(y_*\mid x_*,\theta)] +\operatorname{Var}_\theta[\mathbb E(y_*\mid x_*,\theta)]. 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.

Optional practice and worked answers

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.