---
title: "Latent variable and sampling lab: Viterbi, Metropolis, Gibbs and boosting"
heading: The most likely hidden-state path by dynamic programming checked against brute force, a random-walk Metropolis sampler whose acceptance rate matches theory, a Gibbs sampler's slow mixing under correlation, and AdaBoost with decision stumps
eyebrow: S14 · Lesson 45 · Sampling lab
xp: 60
---

::: hook
Lessons 40 to 44 described algorithms whose behavior is easiest to believe once you've run them: dynamic programming that finds the best of exponentially many state paths in linear time, Markov chains that sample a distribution they can only evaluate up to a constant, and boosting that builds a strong classifier from very weak ones. In this lab you'll write each in a few lines and check it against brute force or a closed-form prediction.
:::

::: play
- A random-walk Metropolis sampler targets a Gaussian with standard deviation σ and proposes Gaussian steps of standard deviation s. The curve is its average acceptance rate against s/σ, which works out to $\frac2\pi\tan^{-1}(2\sigma/s)$.
- Tiny steps are almost always accepted but barely move; huge ones are almost always rejected. The best compromise for a one-dimensional Gaussian is s ≈ 2.4σ, at about 44% acceptance.
:::

```sim plot
view: graph
x: d = 0.1..20 log
y: a = 0..1
plot: 2/pi*atan(2/d) | label: acceptance rate
point: 2.4, 2/pi*atan(2/2.4) | label: best step
```

::: predict
## A Metropolis sampler for a Gaussian of standard deviation 0.5 proposes steps of standard deviation 1. About what fraction of proposals does it accept?

- [ ] About 90%
- [ ] About 70%
- [x] About 50%
- [ ] About 10%

::: reveal
With steps twice the target's width, $\frac2\pi\tan^{-1}(1)$ = 0.50: half the proposals are accepted. Task 2's sampler measures 50.3% over 20,000 steps. Halving the step raises acceptance to 70%, but the chain then moves more slowly; acceptance alone isn't the goal.
:::
:::

::: nameit
## What the lab computes

- **Viterbi**: in log space, $\delta_1(k) = \ln\pi_k + \ln B_k(o_1)$ and $\delta_t(j) = \max_i[\delta_{t-1}(i) + \ln A_{ij}] + \ln B_j(o_t)$, remembering each maximizing i; the best path is traced back from the largest final δ. It costs $NK^2$ operations against the $K^N$ paths of brute force.
- **Metropolis**: propose $x' = x + \epsilon$ with $\epsilon \sim \mathcal N(0, s^2)$, and accept with probability $\min(1, p(x')/p(x))$, comparing logs; a rejected proposal repeats the current state.
- **Gibbs**: for a standard bivariate Gaussian with correlation ρ, alternate $x \sim \mathcal N(\rho y, 1 - \rho^2)$ and $y \sim \mathcal N(\rho x, 1 - \rho^2)$. The x chain's lag-one autocorrelation is ρ².
- **AdaBoost with stumps**: each round picks the threshold and polarity with the lowest weighted error ε (thresholds at midpoints between distinct inputs, plus one below them all), gives it a vote $\alpha = \frac12\ln\frac{1 - \epsilon}\epsilon$, multiplies each example's weight by $e^{-\alpha y h(x)}$ and renormalizes. Ties go to the first candidate found.
:::

::: check
kind: python

## Write `viterbi(pi, A, B, obs)` returning the most likely state path and its log probability.

```python starter
def viterbi(pi, A, B, obs):
    return [0] * len(obs), 0.0
```

```python solution
import math

def viterbi(pi, A, B, obs):
    K = len(pi)
    d = [math.log(pi[k]) + math.log(B[k][obs[0]]) for k in range(K)]
    back = []
    for o in obs[1:]:
        nd, bp = [], []
        for j in range(K):
            i = max(range(K), key=lambda i: d[i] + math.log(A[i][j]))
            nd.append(d[i] + math.log(A[i][j]) + math.log(B[j][o]))
            bp.append(i)
        d = nd
        back.append(bp)
    k = max(range(K), key=lambda k: d[k])
    best = d[k]
    path = [k]
    for bp in reversed(back):
        k = bp[k]
        path.append(k)
    return path[::-1], best
```

```python tests
import math, itertools
def brute(pi, A, B, obs):
    best = None
    for path in itertools.product(range(len(pi)), repeat=len(obs)):
        l = math.log(pi[path[0]]) + math.log(B[path[0]][obs[0]])
        for t in range(1, len(obs)):
            l += math.log(A[path[t - 1]][path[t]]) + math.log(B[path[t]][obs[t]])
        if best is None or l > best[1]:
            best = (list(path), l)
    return best
pi, A, B = [0.9, 0.1], [[0.95, 0.05], [0.3, 0.7]], [[0.9, 0.1], [0.3, 0.7]]
obs = [0, 1, 1, 0, 1, 1, 1, 0]
p, l = viterbi(pi, A, B, obs)
bp, bl = brute(pi, A, B, obs)
assert p == bp and abs(l - bl) < 1e-9, "The healthy/faulty machine: matches all 256 paths."
assert p == [0, 1, 1, 1, 1, 1, 1, 0], "One clean reading inside a run of alarms doesn't end the fault."
pi3 = [0.5, 0.3, 0.2]
A3 = [[0.6, 0.3, 0.1], [0.2, 0.5, 0.3], [0.1, 0.2, 0.7]]
B3 = [[0.7, 0.2, 0.1], [0.1, 0.6, 0.3], [0.2, 0.2, 0.6]]
o3 = [0, 2, 1, 2, 2, 0]
assert viterbi(pi3, A3, B3, o3)[0] == brute(pi3, A3, B3, o3)[0], "Three states: matches all 729 paths."
```

::: right
Right. The path keeps the machine faulty through the clean reading at hour 4, because a quick repair and relapse is less likely than one false all-clear.
:::
:::

::: check
kind: python

## Write `metropolis(logp, x0, step, n, seed)`: a random-walk Metropolis sampler using `random.Random(seed)`, returning the n states visited and the acceptance rate.

```python starter
import random

def metropolis(logp, x0, step, n, seed):
    r = random.Random(seed)
    return [x0 + r.gauss(0, step) for _ in range(n)], 1.0
```

```python solution
import math, random

def metropolis(logp, x0, step, n, seed):
    r = random.Random(seed)
    x, lx = x0, logp(x0)
    out, acc = [], 0
    for _ in range(n):
        y = x + r.gauss(0, step)
        ly = logp(y)
        if math.log(r.random()) < ly - lx:
            x, lx = y, ly
            acc += 1
        out.append(x)
    return out, acc / n
```

```python tests
import math
target = lambda x: -(x - 2) ** 2 / (2 * 0.25)
s, a = metropolis(target, 0.0, 1.0, 20000, 1)
m = sum(s) / len(s)
v = sum((t - m) ** 2 for t in s) / len(s)
assert abs(m - 2) < 0.05 and abs(v - 0.25) < 0.025, "It samples N(2, 0.5²) without knowing its normalizing constant."
assert abs(a - 2 / math.pi * math.atan(1)) < 0.02, "Acceptance matches (2/π) arctan(2σ/s) = 0.50."
_, a2 = metropolis(target, 0.0, 0.5, 20000, 2)
assert abs(a2 - 2 / math.pi * math.atan(2)) < 0.02, "Halving the step: 0.70."
```

::: right
Right. Only differences of log probabilities enter, so the normalizing constant is never needed.
:::
:::

::: check
kind: python

## Write `gibbs(rho, n, seed)`: n sweeps of a Gibbs sampler for a standard bivariate Gaussian with correlation ρ, starting at (0, 0), returning the list of (x, y) pairs.

```python starter
import random

def gibbs(rho, n, seed):
    r = random.Random(seed)
    return [(r.gauss(0, 1), r.gauss(0, 1)) for _ in range(n)]
```

```python solution
import math, random

def gibbs(rho, n, seed):
    r = random.Random(seed)
    sd = math.sqrt(1 - rho * rho)
    x = y = 0.0
    out = []
    for _ in range(n):
        x = r.gauss(rho * y, sd)
        y = r.gauss(rho * x, sd)
        out.append((x, y))
    return out
```

```python tests
import math
def corr(a, b):
    ma, mb = sum(a) / len(a), sum(b) / len(b)
    return sum((p - ma) * (q - mb) for p, q in zip(a, b)) / math.sqrt(sum((p - ma) ** 2 for p in a) * sum((q - mb) ** 2 for q in b))
g = gibbs(0.8, 20000, 3)
xs, ys = [p[0] for p in g], [p[1] for p in g]
assert abs(corr(xs, ys) - 0.8) < 0.02, "The samples have the target's correlation."
assert abs(corr(xs[:-1], xs[1:]) - 0.64) < 0.03, "Successive x values are correlated by ρ² = 0.64."
```

::: right
Right. At ρ = 0.8 each sweep keeps 64% of the last state's correlation; at 0.99 it would keep 98%.
:::
:::

::: check
kind: python

## Write `adaboost(x, y, rounds)` for one-dimensional inputs and ±1 labels, returning a list of (threshold, polarity, α, ε) per round, where a stump predicts the polarity above the threshold and its negative below; and `predict(model, x)`.

```python starter
def adaboost(x, y, rounds):
    return []

def predict(model, x):
    return 1
```

```python solution
import math

def adaboost(x, y, rounds):
    n = len(x)
    w = [1 / n] * n
    xs = sorted(set(x))
    ths = [(xs[i] + xs[i + 1]) / 2 for i in range(len(xs) - 1)] + [xs[0] - 1]
    model = []
    for _ in range(rounds):
        best = None
        for th in ths:
            for pol in (1, -1):
                err = sum(wi for xi, yi, wi in zip(x, y, w) if (pol if xi > th else -pol) != yi)
                if best is None or err < best[0] - 1e-15:
                    best = (err, th, pol)
        err, th, pol = best
        alpha = 0.5 * math.log((1 - err) / err)
        w = [wi * math.exp(-alpha * yi * (pol if xi > th else -pol)) for xi, yi, wi in zip(x, y, w)]
        z = sum(w)
        w = [wi / z for wi in w]
        model.append((th, pol, alpha, err))
    return model

def predict(model, x):
    return 1 if sum(a * (p if x > t else -p) for t, p, a, e in model) > 0 else -1
```

```python tests
import math
X = [1, 2, 3, 4, 5, 6, 7, 8]
Y = [1, 1, -1, -1, 1, 1, -1, -1]
m1 = adaboost(X, Y, 1)
assert abs(m1[0][3] - 0.25) < 1e-12 and abs(m1[0][2] - 0.5 * math.log(3)) < 1e-12, "The best single stump errs on 2 of 8: α = ½ ln 3."
m = adaboost(X, Y, 3)
assert [round(e, 4) for _, _, _, e in m] == [0.25, 0.1667, 0.2], "Weighted errors 0.25, 0.167, 0.2."
assert all(predict(m, xi) == yi for xi, yi in zip(X, Y)), "Three stumps fit a pattern no single stump can."
```

::: right
Right. Each round reweights toward the examples the vote still gets wrong, so the next stump attends to them.
:::
:::

::: explain
## Why does a Gibbs sampler mix slowly when the variables are strongly correlated?

::: model
Gibbs sampling moves one variable at a time, drawing it from its distribution given the others' current values. When two variables are strongly correlated, that conditional distribution is narrow: knowing y pins x down to within $\sqrt{1 - \rho^2}$ of ρy, so each update can shift x only a little. The joint distribution, though, stretches far along the correlated direction, and the sampler can only travel along it by many small alternating steps, like climbing a narrow diagonal staircase. Successive samples are then highly correlated (by ρ² per sweep for a Gaussian), and the number of effectively independent samples falls accordingly. Updating the variables jointly, or rotating to uncorrelated coordinates first, removes the problem.
:::
:::
