A per-frame classifier flickers: walk, walk, RUN, walk. On the stream below its raw labels switch about 40 times where the truth switches 5. A smoother that knows labels last decodes the same scores with about 5 switches.
Pick a decoder and raise the noise. Watch which output stays in clean blocks. Then we build, piece by piece, the majority vote, the CRF score, Viterbi, the forward algorithm, explicit durations and the price of smoothing.
You need what a probability is and a little Python. We build the rest from zero, including the dynamic programming.
Illustrative toy: 96 frames, 3 labels (stand, walk, run), 5 true switches. Each frame's score is +1.6 for the true label plus Gaussian noise. The CRF uses a switch penalty of 3. The HSMM is told typical lengths of 19, 19 and 10 frames.
Chapter 0
Watch a fall detector raise alarms for runs that never happened
A camera watches a person in a care home. Thirty times a second, a network looks at one frame and names the action: walk, walk, walk. A passing hand blurs one frame. The network says run. A fall detector downstream sees "run" and raises an alarm. Nobody ran.
The network labels each frame alone. That is per-frame argmax: for each frame, pick the label with the highest score, with no memory of the frame before. Noise in one score is enough to flip one label. A one-frame flip is called flicker.
The person walks for 120 frames and runs once, for 12 frames. Each red flag is an alarm on a run that did not happen. Raise the noise.
Illustrative toy: two labels, a score gap of 1.6 between the true and the wrong label, Gaussian noise. The detector fires on every switch from walk to run.
A bigger network lowers the rate of flips. It does not remove them. Over thousands of frames, a few scores always land on the wrong side. The fix uses a fact the network never sees: labels last. People do not switch from walking to running and back in 33 ms.
So we add a temporal prior, a rule about how labels behave over time, and decode the whole sequence at once. Two models do this. The linear-chain CRF charges a cost for each label switch. The HSMM also knows how long each label usually lasts. Both sit on top of the network you already have. You retrain nothing.
The symptom is alarms, counts or state changes that nobody can explain. To measure it, count label switches in the output and compare with the true number of switches on a labelled clip. The fix is the rest of this lesson.
Chapter 1
Push noisy scores across a hard threshold and count the broken segments
Take two labels, A and B, and seven frames. The truth is A A A B B B B: one switch, after frame 3. For each frame the network gives a margin s: the score of B minus the score of A. The rule is: if s is above 0, say B; else say A.
The clean margin is −2 in the A region and +2 in the B region. Noise adds a random amount to each frame. Here are seven frames where two caught bad noise.
| Frame | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
| True label | A | A | A | B | B | B | B |
| Clean margin | −2.0 | −2.0 | −2.0 | +2.0 | +2.0 | +2.0 | +2.0 |
| Noise | +0.3 | +2.6 | −0.4 | −0.5 | −3.1 | +0.2 | −0.6 |
| Noisy margin s | −1.7 | +0.6 | −2.4 | +1.5 | −1.1 | +2.2 | +1.4 |
| Argmax | A | B × | A | B | A × | B | B |
Frame 2 got +2.6 of noise, so its margin is +0.6 and it flips to B. Frame 5 got −3.1, so it flips to A. The output is A B A B A B B. Five of seven frames are right: 71%. But the output has 5 switches where the truth has 1.
That is the real damage. A fall detector, a billing meter or a state machine acts on switches, not on per-frame accuracy. Two wrong frames made four extra switches, because each lone flip makes two: one in, one out.
The teal curve is the clean margin. Warm dots are noisy margins. A dot on the wrong side of the dashed zero line is a flipped frame, ringed in red. Drag the noise.
Illustrative toy: 48 frames, the clean margin moves from −2 to +2 around frame 24. The noise is the same seeded draw at every setting, scaled by the slider.
Three facts make flicker certain. Scores are noisy. Argmax is a hard threshold, so a small change near zero flips the label. And argmax decides each frame alone. We cannot remove the first two. We can remove the third: let each frame's label depend on its neighbours' labels.
The symptom is good per-frame accuracy and a bad segment count. Measure both: accuracy, and output switches divided by true switches. Here that ratio is 5. The fix is to couple each frame to its neighbours.
Chapter 2
Let each frame's neighbours vote, and see what the vote throws away
The cheapest fix: let each frame ask its neighbours. Look at a window of frames centred on frame t. Output the label that appears most often in it. This is the majority filter. For two labels it is the same as a median filter on 0 and 1.
Call the raw argmax label at frame k ak. Call the half-width of the window h, so the window holds 2h + 1 frames. Call the filtered label ŷt.
y-hat-t equals the mode of the set a-sub-t-minus-h through a-sub-t-plus-h.
Slide a window of 2h + 1 raw labels a along the stream. At each frame t, count the labels in the window. Write the most common one as y-hat-t.
With made-up labels: raw A A B A A A B B B A B B and h = 1. At frame 3 the window is {A, B, A}, so y-hat-3 = A. At frame 10 it is {B, A, B}, so y-hat-10 = B. The output is A A A A A A B B B B B B: 1 switch instead of 5.
The raw labels have 3 phantom frames. The truth also holds one real B segment that lasts 2 frames. Pick a window and compare the filtered row with the truth.
Illustrative toy: 30 frames, two labels. Edge frames repeat the first or last label to fill the window.
Two faults show up. First, the vote counts labels and throws away the scores. A frame where B won by 0.01 and a frame where B won by 5 get the same one vote. Second, the window size is a hard floor on segment length. A window of 5 erases every real segment shorter than 3 frames, even with strong evidence.
We want a decoder that weighs the scores, charges a price for each switch, and keeps a short segment when its evidence pays that price. That decoder is the CRF.
The symptom is brief real events that never appear in the output. Measure the recall of true segments shorter than the window. The fix is a score-weighted decoder, Chapter 3.
Chapter 3
Add up evidence and switch costs for a whole label sequence, and see a lone spike lose
A label path is one label for every frame, for example A A B A. The CRF gives each whole path one number, its score. The best path is the one with the highest score. The score has two parts.
Call the emission score φt(y), the transition score T[i, j], and the path y = (y1, …, yL) for L frames.
The score of y equals the sum over t from 1 to L of phi-t of y-t, plus the sum over t from 2 to L of T of y-t-minus-1, y-t.
Walk the path frame by frame. Add the emission phi-t of each chosen label. Then add T for each step from one label to the next, which takes away lambda at every switch.
With made-up scores for 4 frames: phi(A) = 2, 1.5, 0, 1.8 and phi(B) = −0.5, 0, 1, 0, with lambda = 2. Path A A A A: 2 + 1.5 + 0 + 1.8 = 5.3, no switch, score 5.3. Path A A B A: emissions 6.3, two switches cost 4, score 2.3. The lone B loses by 3.
Frame 3 favours B by 1. To honour it, the path must switch in and switch out: two penalties, 4 in all. The spike is not worth it. That is how the CRF couples neighbours: a label now changes the price of the label next.
Each column is a frame; each cell shows its emission score. Tap a cell to put the path there. Change the switch penalty and try to beat the best path.
The scores are the made-up example above. With λ below 0.5 the lone B pays for itself and the best path is A A B A.
Only the gap between staying and switching matters. Stay +1 and switch −1 pick the same best path as 0 and −2. Every path has L − 1 steps, so the stay score adds the same amount to each. With λ = 0 you get per-frame argmax back.
The name: conditional because it scores labels given the observed scores and never models the pixels. Random field is the name for a graph of linked variables. Linear-chain means each label links only to its two neighbours, and that is what makes the next chapter fast.
The symptom is a CRF output that still flickers, or one that is a single block. Measure output switches against true switches while you sweep λ. The fix is to tune λ on a labelled clip.
Chapter 4
Fill a grid left to right, keep one best arrival per cell, and trace the winner back
With K labels and L frames there are KL paths. For 5 labels and 100 frames that is about 8 × 1069. We cannot score them all. Viterbi finds the best one with a grid sweep.
The idea: suppose the best path ends in B at frame t. Then its first t − 1 frames must be the best way to reach whatever label sits before that B. A worse prefix can only lower the total. So at each frame we keep, for each label, only the best score of any path that ends there.
Call that best score δt(j): the score of the best path over frames 1 to t that ends in label j. Call the previous label i.
Delta-t of j equals phi-t of j plus the max over i of delta-t-minus-1 of i plus T of i, j.
For each label j at frame t, look back at every label i. Add delta of i from the last frame and the step cost T of i, j. Keep the best, remember which i it came from, and add phi-t of j. Start with delta-1 of j equal to phi-1 of j.
Chapter 3's scores with lambda = 2. Frame 1: delta(A) = 2, delta(B) = −0.5. Frame 3, label B: 1 + max(3.5 − 2, 0 + 0) = 1 + 1.5 = 2.5, from A. Frame 4 ends with delta(A) = 5.3 and delta(B) = 2.5. A wins, and the backpointers trace A A A A.
| Cell | Arrive from A | Arrive from B | δ (from) |
|---|---|---|---|
| Frame 1 | start | start | A 2, B −0.5 |
| Frame 2, A | 2 + 0 = 2 | −0.5 − 2 = −2.5 | 1.5 + 2 = 3.5 (A) |
| Frame 2, B | 2 − 2 = 0 | −0.5 + 0 = −0.5 | 0 + 0 = 0 (A) |
| Frame 3, A | 3.5 | 0 − 2 = −2 | 0 + 3.5 = 3.5 (A) |
| Frame 3, B | 3.5 − 2 = 1.5 | 0 | 1 + 1.5 = 2.5 (A) |
| Frame 4, A | 3.5 | 2.5 − 2 = 0.5 | 1.8 + 3.5 = 5.3 (A) |
| Frame 4, B | 1.5 | 2.5 | 0 + 2.5 = 2.5 (B) |
Press Step to fill one cell. Teal arrows are backpointers. When the grid is full, the best final cell traces the path back. Then change λ and fill again.
Chapter 3's made-up scores. The bottom strip is the per-frame argmax, for comparison.
Count the work. Each of L frames has K cells, and each cell looks back at K labels: L × K2 steps. For K = 5 and L = 100 that is 2,500 steps instead of 8 × 1069 paths.
Viterbi gives the best whole path. That differs from picking the most likely label at each frame after smoothing. The whole path is always a consistent sequence, so for smoothing we want it.
The symptom is a decoded path that switches into a label the model calls nearly impossible. That happens when you pick the best label per frame instead of the best path. Measure it by scoring the decoded path. The fix is to decode with Viterbi and its backpointers.
Chapter 5
Swap max for log-sum-exp and the same grid adds up every path
To learn T from labelled clips, we need the probability of the true path. To turn a score into one, raise e to each path's score and divide by the total over all paths.
Call that total Z, the partition function. Call the observed network scores x.
P of y given x equals e to the score of y, divided by Z.
Turn each path's score into a weight with e to the score. Add the weights of all paths to get Z. The probability of y is its weight divided by Z.
Chapter 3's example has 16 paths. Their weights add to Z = e to the 5.476. The best path A A A A scores 5.3, so P = e to the (5.3 − 5.476) = 0.84.
Training minimises the loss log Z minus score(true). The score term pushes the true path up. The log Z term pushes every path down, so the model cannot inflate all scores. But Z sums KL weights, so we need Viterbi's grid again.
The forward algorithm is Viterbi with one change: it adds up all arrivals instead of keeping the best. Call αt(j) the log of the summed weights of all paths over frames 1 to t that end in j.
Alpha-t of j equals phi-t of j plus the log-sum-exp over i of alpha-t-minus-1 of i plus T of i, j.
Run Viterbi's sweep, but at each cell combine the arrivals alpha of i plus T of i, j with log-sum-exp instead of max. At the end, log Z is the log-sum-exp of the last column.
Chapter 3's example, lambda = 2. Frame 2, label A: 1.5 + logsumexp(2 + 0, −0.5 − 2) = 1.5 + 2.011 = 3.511. The last column is 5.382 and 3.056, so log Z = logsumexp(5.382, 3.056) = 5.476. That is above the best score, 5.3.
Why not a plain sum of e to the scores? e to 900 overflows. The stable recipe subtracts the largest term m first: logsumexp(v) = m + log of the sum of e to (v − m). For [2, 1, 0]: 2 + log(1 + 0.368 + 0.135) = 2.408, with no exponent above 0.
Left: max. Right: log-sum-exp. Move λ and watch log Z and the best path's probability.
Chapter 3's made-up scores. Each forward cell is at least its Viterbi cell: a sum is at least its largest term.
The symptom is a NaN or infinite loss on long clips: e to a large score overflowed. Check that log Z is finite and at least the Viterbi score. The fix is log-sum-exp with the max subtracted, at every cell.
Chapter 6
See what a fixed switch cost secretly believes about segment lengths
A walking bout lasts seconds. A phoneme lasts tens of milliseconds. Does the CRF know that? It knows only "switching costs λ", the same at every frame. What does that imply about how long a label lasts?
Think of the model as a coin flip at every frame: stay with probability p, leave with probability 1 − p. Call the length of a segment, in frames, its duration d.
P of d equals p to the d minus 1, times one minus p.
To last d frames, the segment stays d − 1 times, each with chance p, then leaves once, with chance 1 − p. Multiply those chances. This is the geometric distribution.
With p = 0.9: P(1) = 0.10, P(2) = 0.09, P(3) = 0.081, P(10) = 0.039. The average length is 1 / (1 − p) = 10 frames, yet length 1 is the single most likely length.
Every extra frame multiplies by p, which is below 1. So P(d) always falls, and its peak is always at d = 1. Even with p = 0.95 (average 20 frames), a 1-frame segment (0.05) is 2.6 times as likely as a 20-frame one (0.019). The CRF believes "segments are short" for every label.
Teal is what a fixed stay probability implies. Pink is an explicit duration curve you centre on the typical length. Move both sliders and look at d = 1.
The pink curve is a bell around the typical length, with a spread of a quarter of it, over 1 to 60 frames. Real systems fit it to labelled lengths.
The fix is to model duration directly. Give each label its own duration distribution, any shape you like: "walking lasts 60 to 120 frames, almost never 1". A fixed stay probability cannot put a bump at 40 frames. Explicit durations can.
The symptom is a CRF that must choose between keeping noise blips and keeping real short events. Measure it with a histogram of decoded segment lengths beside the true histogram. The fix is explicit durations, the HSMM in Chapter 7.
Chapter 7
Score whole segments with their lengths, and separate a real event from a blip that the CRF cannot
A hidden semi-Markov model (HSMM) decodes segments, not frames. It enters a label, draws a duration d from that label's curve, emits for d frames, then moves to a different label.
A test case: labels A (idle) and B (a reach of about 4 frames). Over 18 frames the margin of B over A is −1.5, except in two places.
| Stretch | Frames | Margin per frame | Total evidence |
|---|---|---|---|
| Real reach | 7 to 10 (4 frames) | +1.1 | 4.4 |
| Noise blip | 14 to 15 (2 frames) | +2.3 | 4.6 |
The CRF keeps a segment if its evidence beats two switch penalties, 2λ. Below λ = 2.2 it keeps both; from 2.2 to 2.3, only the blip; above 2.3, neither. No λ keeps the reach and drops the blip.
The HSMM adds a duration score per segment. Call the duration log-probability of label j for length d log pj(d). Call Vt(j) the best score of any segmentation of frames 1 to t whose last segment is label j and ends at frame t.
V-t of j equals the max over d of three terms. First, the max over i not equal to j of V-t-minus-d of i plus T of i, j. Then log p-j of d. Then the sum over s of phi-s of j.
To end a segment of label j at frame t, try each length d. Take the best score V that ended at frame t − d in another label. Add log p-j of d and the segment's emissions. Keep the best d.
B's curve peaks at 4 frames: log p(4) = −0.92, log p(2) = −2.92. A has no preferred length: log(1/18) = −2.89 per segment. Keeping the reach adds −0.92 − 2.89 + 4.4 = +0.59. Keeping the blip adds −2.92 − 2.89 + 4.6 = −1.21. The reach stays; the blip goes.
Warm bars are B's margin per frame. Pick a decoder, then sweep λ or B's typical length.
Made-up margins from the table. The HSMM has no switch penalty. A's duration curve is flat over 1 to 18 frames; B's is a bell with a spread of 1. A numpy check matches.
Each cell now tries D lengths. Cache the best arrival per frame and label, and the work is L × K × D + L × K2, not L × K2 × D. For L = 1,000, K = 10, D = 100: 1.1 million steps, not 10 million.
Self-transitions are forbidden (i ≠ j), because staying is the duration's job. Use an HSMM when length carries signal: dwell times, phonemes, assembly steps.
The symptom is a real segment cut up or merged at every λ. Measure the decoded length histogram per label. The fix is a duration curve fitted to labelled lengths, with D at the longest you expect.
Chapter 8
Bolt a decoder onto a network's logits, then break all four decoders side by side
The network gives logits of shape (L, K): L frames, K classes. Those are the emissions. Pick T: 0 on the diagonal, −λ off it.
Run Viterbi, L × K2 steps. Out comes an integer array of L labels. You retrain nothing and need no GPU.
pythonimport numpy as np def crf_smooth(logits, lam=3.0): # logits: (L, K) float, from the network L, K = logits.shape T = -lam * (1 - np.eye(K)) # 0 to stay, -lam to switch delta = logits[0].copy() # (K,) best score ending in each label bp = np.zeros((L, K), dtype=int) # backpointers for t in range(1, L): cand = delta[:, None] + T # (K, K): from i (row) to j (column) bp[t] = cand.argmax(0) delta = logits[t] + cand.max(0) path = [int(delta.argmax())] for t in range(L - 1, 0, -1): path.append(int(bp[t, path[-1]])) return np.array(path[::-1]) # (L,) int labels # raw = logits.argmax(1) flickers; crf_smooth(logits) does not
Pass logits or log-softmax, not probabilities. Log-softmax subtracts the same number from every label at a frame, so every path's score drops by the same total and the best path stays. Softmax probabilities are a different scale, and on a random test they changed the path.
To train the CRF with the network, use a CRF layer such as pytorch-crf. There, loss = -crf(emissions, tags) runs the forward algorithm. crf.decode(emissions) runs Viterbi. Joint training lets the logits learn that a smoother follows. Post-hoc smoothing ships today on a frozen model.
Each row decodes the same logits. Raise the noise, then tune λ and the window. Try λ = 0, and try λ = 12.
Illustrative toy: the hero's 96-frame stream. The HSMM knows typical lengths of 19, 19 and 10 frames, with a spread of 6, and uses no switch penalty.
Three experiments. Set λ to 0: the CRF row becomes the raw row, so all smoothing comes from T. Set λ to 12: the CRF swallows the 6-frame run. Raise the noise to 1.6: raw switches reach 60 and the HSMM holds at 5. The CRF slips to 9 at λ = 3, and a larger λ trades those switches for erased frames.
The symptom is a smoother tuned on one clip that over- or under-smooths on another. Measure accuracy and the switch ratio on several held-out clips. The fix is to tune λ (or fit durations) on a validation set, not by eye.
Chapter 9
Find the shortest event a smoother keeps, and the delay an online smoother adds
A smoother that resists false switches also resists real ones. That shows up in two ways: short real events disappear, and a smoother that cannot see the future reacts late.
First, short events. Take a segment of n frames whose label beats its neighbour by a margin e at every frame. Keeping it costs two switches, 2λ.
Keep the segment if n times e is greater than two lambda.
Add up the segment's evidence, n frames times margin e. If it beats the two switch penalties, offline Viterbi keeps the segment. If not, Viterbi erases the segment.
With made-up values e = 0.8 and lambda = 2.5: 2 lambda = 5. Six frames give 4.8, erased. Seven frames give 5.6, kept. The shortest event this smoother can show is 7 frames.
Second, delay. Offline Viterbi sees the whole clip, so it places a clean boundary exactly: the switch costs the same wherever it goes. A live system has no future frames. An online decoder outputs, at each frame, the label with the best δ so far. It flips only once the new label has gathered more than λ of evidence. With e = 0.8 and λ = 2.5 it flips on the 4th new frame (4 × 0.8 = 3.2 > 2.5): 3 frames late. Double λ to 5 and the lag is 6 frames.
The middle way is fixed-lag smoothing: decide frame t after seeing frames up to t + Δ. Here Δ = 3 removes the lag, at a cost of 3 frames of delay. You pay in latency either way.
The truth switches from A to B after frame 10, and later holds a short A segment. Pick a decoder, then move λ, the margin and the segment length.
Made-up clean margins with no noise, so every result is exact. A numpy check gives the same lags and the same 7-frame threshold at the defaults.
Match the smoothing to the cost of each mistake. If a false alarm is expensive, smooth hard and accept lag. If missing a brief event is expensive, smooth gently. An HSMM lets you set this per label: slow to leave a long state, quick to accept a short one.
The symptom is an output that looks clean but is wrong: wide blocks that start late and miss brief events. Measure boundary delay in frames and recall of short segments. The fix is a smaller λ, a fixed lag, or per-label durations.
Chapter 10
Keep the terms, the numbers, the checks and the code in one place
A network labels frames alone and flickers. A majority vote removes lone flips but ignores scores and erases short events. A linear-chain CRF scores whole paths with emissions and a switch penalty. Viterbi finds the best path in L × K2 steps. The forward algorithm gives log Z for training.
An HSMM adds a duration curve per label. Every smoother trades flicker for erased events and, online, for lag.
| Term | Meaning | Number to remember |
|---|---|---|
| Flicker | lone label flips from per-frame argmax | 7 frames: 71% right, 5 switches for 1 true |
| Majority filter | mode of 2h + 1 raw labels | window 5 erases a real 2-frame event |
| CRF score | sum of emissions plus transitions | A A A A 5.3 beats A A B A 2.3 at λ = 2 |
| Viterbi | δ = φ + max of (previous δ + T) | L × K2: 2,500 steps for K = 5, L = 100 |
| Partition function | Z = sum of e to every path's score | log Z 5.476, P(best) 0.84 |
| Log-sum-exp | m + log of the sum of e to (v − m) | [2, 1, 0] gives 2.408 |
| Geometric duration | pd−1(1 − p), peak at d = 1 | p = 0.9: P(1) 0.10, mean 10 |
| HSMM | segments with per-label duration curves | L·K·D + L·K2 with caching |
| Keep rule | n · e > 2λ | e = 0.8, λ = 2.5: 7 frames minimum |
| Online lag | flip once new evidence beats λ | 3 frames at λ = 2.5, e = 0.8 |
pythonimport numpy as np def logsumexp(v, axis=0): m = v.max(axis) return m + np.log(np.exp(v - np.expand_dims(m, axis)).sum(axis)) def log_partition(phi, T): # phi: (L, K), T: (K, K) alpha = phi[0] for t in range(1, len(phi)): alpha = phi[t] + logsumexp(alpha[:, None] + T, axis=0) return logsumexp(alpha) # log Z def hsmm_decode(phi, logdur, D): # logdur[j][d]: log p_j(d), d = 1..D L, K = phi.shape cs = np.vstack([np.zeros(K), phi.cumsum(0)]) # prefix sums of emissions V = np.full((L + 1, K), -np.inf); back = {} for t in range(1, L + 1): for j in range(K): for d in range(1, min(D, t) + 1): s = t - d prev = [V[s, i] if i != j else -np.inf for i in range(K)] i = int(np.argmax(prev)); arr = 0.0 if s == 0 else prev[i] v = arr + logdur[j][d] + cs[t, j] - cs[s, j] if v > V[t, j]: V[t, j] = v; back[t, j] = (d, i) j, t, out = int(V[L].argmax()), L, np.zeros(L, int) while t > 0: d, i = back[t, j]; out[t - d:t] = j; t, j = t - d, i return out
| Method | Durations | Cost | Use when |
|---|---|---|---|
| Per-frame argmax | none | L × K | never alone on a sequence |
| Majority filter | a hard floor, the window | L × window | every real segment is longer than the window |
| Linear-chain CRF | geometric | L × K2 | general smoothing; NER and part-of-speech tags |
| HMM | geometric | L × K2 | you also model how observations arise |
| HSMM | any shape | L·K·D + L·K2 | length is signal: phones, actions, dwell times |
Now press Present or Teach and explain from memory: why argmax flickers, the CRF score, the Viterbi sweep, log Z, the geometric trap and the keep rule. Then go back to the four decoders, raise the noise to the top, and say why the CRF and the HSMM hold.