CRF & HSMM Temporal Smoothing

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.

Decode one noisy stream four ways

0.90

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

One Bad Frame Fires an Alarm

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.

Count the false alarms

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.

0.80

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 failure, as symptom, measurement and fix

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.

The road

  1. Flicker: why independent labels break the segments, with numbers.
  2. Majority vote: the quick fix, and what it gets wrong.
  3. The CRF score: emissions plus transitions, for a whole path.
  4. Viterbi: the best path without listing every path.
  5. The forward algorithm: path probabilities, the partition function, training.
  6. Durations: what a switch cost assumes about segment lengths.
  7. The HSMM: decode whole segments with explicit lengths.
  8. Smooth a stream: the post-processor in code, and the hero in full.
  9. What smoothing costs: erased short events and online lag.
  10. The field guide: terms, numbers, a checklist, the code, links.
A 30 fps recognizer outputs "walk, walk, RUN, walk, walk" and a fall detector fires on the lone RUN. What is the root cause?

Chapter 1

Why Independent Labels Flicker

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.

Frame1234567
True labelAAABBBB
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
ArgmaxAB ×ABA ×BB

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.

Push scores across the line

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.

0.80

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 failure, as symptom, measurement and fix

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.

The 7-frame output was 71% accurate but had 5 switches where the truth had 1. What does that teach?

Chapter 2

The Quick Fix: a Majority Vote

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.

Say it aloud

y-hat-t equals the mode of the set a-sub-t-minus-h through a-sub-t-plus-h.

ŷt
y-hat-t the filtered label at frame t.
mode
the mode of the value that appears most often in the set. One wild vote cannot decide it.
at−h … at+h
a-sub-t-minus-h through a-sub-t-plus-h the raw argmax labels of the 2h + 1 frames centred on t. h is the half-width, in frames.
In plain words

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 numbers

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.

Widen the vote

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 failure, as symptom, measurement and fix

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.

A majority filter with a window of 5 frames runs on a stream with a real event that lasts 2 frames and has very strong scores. What happens?

Chapter 3

Score the Whole Path: the Linear-Chain CRF

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.

  1. The emission score of frame t for label y: how much frame t looks like y. These are the network's per-frame scores (the logits, before softmax).
  2. The transition score from label i to label j: how acceptable it is to go from i at one frame to j at the next. They form a K by K matrix for K labels.

Call the emission score φt(y), the transition score T[i, j], and the path y = (y1, …, yL) for L frames.

Say it aloud

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.

score(y)
the score of y one number for the whole path. Higher is better.
Σt=1..L
the sum over t from 1 to L one term for every frame.
φt(yt)
phi-t of y-t the emission score of the label this path picks at frame t.
Σt=2..L
the sum over t from 2 to L one term for every pair of neighbouring frames.
T[yt−1, yt]
T of y-t-minus-1, y-t the transition score from the previous label to this one. Here staying scores 0 and switching scores −λ (minus lambda).
In plain words

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 numbers

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.

Build a path, read its score

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.

2.0

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 failure, as symptom, measurement and fix

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.

Frame 2's emission favours B a little, yet the CRF scores A B A below A A A. Why?

Chapter 4

Viterbi: the Best Path Without Listing Paths

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.

Say it aloud

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.

δt(j)
delta-t of j the best score of any path over frames 1 to t that ends in label j.
φt(j)
phi-t of j the emission score of label j at frame t.
maxi
the max over i try every previous label i and keep the largest. Store the winning i as the backpointer.
δt−1(i)
delta-t-minus-1 of i the best score that ended in label i one frame earlier.
T[i, j]
T of i, j the transition score from i to j: 0 to stay, minus lambda to switch.
In plain words

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.

With numbers

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.

CellArrive from AArrive from Bδ (from)
Frame 1startstartA 2, B −0.5
Frame 2, A2 + 0 = 2−0.5 − 2 = −2.51.5 + 2 = 3.5 (A)
Frame 2, B2 − 2 = 0−0.5 + 0 = −0.50 + 0 = 0 (A)
Frame 3, A3.50 − 2 = −20 + 3.5 = 3.5 (A)
Frame 3, B3.5 − 2 = 1.501 + 1.5 = 2.5 (A)
Frame 4, A3.52.5 − 2 = 0.51.8 + 3.5 = 5.3 (A)
Frame 4, B1.52.50 + 2.5 = 2.5 (B)

Fill the lattice, trace the winner

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.

2.0

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 failure, as symptom, measurement and fix

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.

How much work does Viterbi do for L frames and K labels, and why?

Chapter 5

Probabilities and Training: the Forward Algorithm

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.

Say it aloud

P of y given x equals e to the score of y, divided by Z.

P(y | x)
P of y given x the probability of label path y, given the network scores x.
exp(score(y))
e to the score of y a positive weight for the path. One extra point of score multiplies it by about 2.7.
Z
Z the partition function: the sum of e to the score over every possible path. It makes the probabilities add to 1.
In plain words

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.

With numbers

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.

Say it aloud

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.

αt(j)
alpha-t of j the log of the total weight of all paths over frames 1 to t that end in label j.
φt(j)
phi-t of j the emission score of label j at frame t.
logsumexpi
the log-sum-exp over i raise e to each term, add them, take the log. It is a soft max: never below the largest term.
αt−1(i)
alpha-t-minus-1 of i the same quantity one frame earlier, for label i.
T[i, j]
T of i, j the transition score from i to j.
In plain words

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.

With numbers

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.

Max versus log-sum-exp

Left: max. Right: log-sum-exp. Move λ and watch log Z and the best path's probability.

2.0

Chapter 3's made-up scores. Each forward cell is at least its Viterbi cell: a sum is at least its largest term.

The failure, as symptom, measurement and fix

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.

Why does the forward algorithm use log-sum-exp with the max subtracted, and not a plain sum of e to the scores?

Chapter 6

How Long a Label Lasts

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.

Say it aloud

P of d equals p to the d minus 1, times one minus p.

P(d)
P of d the probability that a segment lasts exactly d frames.
pd−1
p to the d minus 1 the chance of staying d − 1 times in a row. p, between 0 and 1, is the stay chance per frame.
1 − p
one minus p the chance of leaving at the end.
In plain words

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 numbers

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.

Compare two beliefs about length

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.

0.95
20

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 failure, as symptom, measurement and fix

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.

A CRF or HMM uses one fixed stay probability per label. What shape does its implied duration distribution have?

Chapter 7

Decode Segments: the Hidden Semi-Markov Model

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.

StretchFramesMargin per frameTotal evidence
Real reach7 to 10 (4 frames)+1.14.4
Noise blip14 to 15 (2 frames)+2.34.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.

Say it aloud

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.

Vt(j)
V-t of j the best score of a segmentation of frames 1 to t whose last segment is label j and ends at t.
maxd
the max over d try every length d for that last segment, from 1 to a cap D, and keep the best.
maxi≠j(…)
the max over i not equal to j of V-t-minus-d of i plus T of i, j the best way to arrive. Take the best segmentation that ended at frame t − d in another label i, plus the switch score.
log pj(d)
log p-j of d the duration score: the log-probability that label j lasts d frames.
Σ φs(j)
the sum over s of phi-s of j the emission scores of label j over the segment's d frames, s from t − d + 1 to t.
In plain words

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.

With numbers

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.

Keep the reach, drop the blip

Warm bars are B's margin per frame. Pick a decoder, then sweep λ or B's typical length.

1.00
4

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 failure, as symptom, measurement and fix

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.

A noise blip has slightly more total evidence than a real short event. Why can an HSMM keep the event and drop the blip when a CRF cannot?

Chapter 8

Smooth a Real Stream

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.

Break four decoders at once

Each row decodes the same logits. Raise the noise, then tune λ and the window. Try λ = 0, and try λ = 12.

1.10
3.00
2

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 failure, as symptom, measurement and fix

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.

What does a CRF post-processor on a frozen network's logits buy you?

Chapter 9

What Smoothing Costs

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λ.

Say it aloud

Keep the segment if n times e is greater than two lambda.

n
n the length of the segment, in frames.
e
e the margin: how much the segment's label beats the surrounding label at each frame.
2λ
two lambda the price of switching in and switching out.
In plain words

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 numbers

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.

Find the price of smoothing

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.

2.5
0.80
6

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 failure, as symptom, measurement and fix

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.

You raise λ until all flicker is gone. What should you check next?

Chapter 10

The Field Guide

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.

TermMeaningNumber to remember
Flickerlone label flips from per-frame argmax7 frames: 71% right, 5 switches for 1 true
Majority filtermode of 2h + 1 raw labelswindow 5 erases a real 2-frame event
CRF scoresum of emissions plus transitionsA 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 functionZ = sum of e to every path's scorelog Z 5.476, P(best) 0.84
Log-sum-expm + log of the sum of e to (v − m)[2, 1, 0] gives 2.408
Geometric durationpd−1(1 − p), peak at d = 1p = 0.9: P(1) 0.10, mean 10
HSMMsegments with per-label duration curvesL·K·D + L·K2 with caching
Keep rulen · e > 2λe = 0.8, λ = 2.5: 7 frames minimum
Online lagflip once new evidence beats λ3 frames at λ = 2.5, e = 0.8

Checklist before you ship a smoother

The core, in code

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

Which decoder, when

MethodDurationsCostUse when
Per-frame argmaxnoneL × Knever alone on a sequence
Majority filtera hard floor, the windowL × windowevery real segment is longer than the window
Linear-chain CRFgeometricL × K2general smoothing; NER and part-of-speech tags
HMMgeometricL × K2you also model how observations arise
HSMMany shapeL·K·D + L·K2length is signal: phones, actions, dwell times

Keep going

The takeaway. The world does not change every frame, so do not let your labels. Add a switch cost or a duration curve, decode the whole path, and measure what the smoothing erased.

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.

CRF & HSMM Temporal Smoothing: From Flicker to Stable Segments
Next: Hidden Markov Models · Back to Gleams