Speaker diarization: who spoke when, and how to count errors
说话人分离标注
Connect local embeddings to global labels, then integrate misses, false alarms and confusion with explicit overlap and collar policies.
speaker-diarizationWho spoke when, including when people interrupt?
Imagine a meeting recording with two people. One starts speaking before the other finishes. A transcript may recover their words, but it does not automatically tell you which person owns each time interval. Speaker diarization produces that time-based annotation: speaker A was active here, speaker B there, and sometimes both were active together.
The labels can be anonymous. “Speaker 0” need not identify a known person, and its number need not match “speaker 0” in another recording. Diarization also does not separate a mixture into clean audio tracks; that is a source-separation problem. This article focuses on assigning consistent speaker labels over time and evaluating that assignment.
The difficulty is not merely detecting changes. Two distant turns may belong to the same speaker, two speakers can overlap, and the total speaker count may be unknown. We will first describe how local speech evidence becomes global labels, then score an invented six-second example where changing the evaluation protocol changes the reported error rate.
Local evidence needs a global assignment
A pipeline separates several decisions
A modular diarization system estimates speech activity or local speaker activity, extracts speaker representations, groups compatible representations, and reconstructs a timeline. Errors can enter at each step: missed speech, a mixed-speaker embedding, an incorrect merge or an incorrect boundary. The pyannote.audio 2.1 paper combines local neural segmentation, local speaker embeddings, global agglomerative clustering and final aggregation. Its local speaker indices are not guaranteed to stay consistent across windows. Pipeline principle
In that reported pipeline, overlapping windows support local activity estimates. Speaker embeddings use regions where one local speaker is active and the others are inactive, reducing contamination by overlapping voices. This depends on the local segmentation being correct. Final aggregation reconciles clustered local activity and estimated speaker counts into a timeline. These are properties of the 2023 paper’s pipeline; later library versions and our small implementation are separate objects. Local embeddings and aggregation
The implementation below starts with supplied segment embeddings. It unit-normalizes each vector and uses average pairwise cosine distance between clusters. For clusters , this distance is:
Start with one cluster per embedding. Repeatedly merge the pair with the smallest distance while that distance is at most a chosen threshold. The stopping rule determines the remaining cluster count; it is not a proof of how many people were present. Average linkage considers every cross-cluster pair, unlike single linkage, which can connect groups through one close pair. The cited pipeline uses centroid linkage, so our average-linkage example must not be described as a reimplementation of it. Clustering choice
Anonymous labels must be matched before scoring
Suppose the reference calls two people A and B while the hypothesis calls them x and y. Correct intervals should not become errors just because their names differ. Find one global, one-to-one mapping between hypothesis and reference labels over the evaluated region.
Let and be the sets of active reference and hypothesis speakers at time , and the evaluated time region after exclusions. Their common-activity matrix is:
Pad the assignment with unmatched dummy labels when counts differ. The fixed pyannote implementation uses Hungarian assignment on this matrix and retains positive-overlap matches. Our program enumerates assignments for at most six labels per annotation, making the optimum independently checkable. It does not claim an efficient Hungarian implementation. Crucially, the mapping remains fixed across the recording: allowing it to change at every instant would hide speaker-confusion errors. Global mapping Diarization scoring order
Count errors in speaker-time
Split the timeline at every reference and hypothesis boundary, so the active speaker sets remain constant inside each resulting interval. After mapping hypothesis labels, let , , and be the number of correctly matched active speakers. The instantaneous error counts are:
Here counts missed speakers, counts excess hypothesis speakers, and counts confusion among the remaining paired speakers. For example, if two reference speakers are active but the hypothesis correctly supplies only one, the interval contributes one correct speaker and one miss. If one reference speaker is active and a different mapped speaker is output, it contributes one confusion rather than both a miss and a false alarm. Error decomposition Per-interval matching
Weight those counts by duration. The diarization error rate (DER) divides total error time by reference speaker-time:
With overlap, is not simply the recording duration: two people speaking for one second contribute two speaker-seconds. False-alarm speaker-time can also make DER exceed one. Our code returns an undefined rate (None) when , while retaining error counts. The inspected pyannote identification implementation instead returns zero or one in its zero-denominator branch, depending on the numerator. This difference is intentional and recorded. Duration integration and empty denominator
Decide which time is evaluated before mapping labels
An evaluation map limits scoring to chosen regions. Some protocols also remove a collar around reference boundaries to avoid penalizing small boundary disagreements; others exclude reference overlap. For a reference boundary and full collar width , the inspected pyannote utility removes:
The overlap exclusion is optional; collars and overlap are separate settings. Other tools may name a one-sided radius “collar,” so a numeric value without its definition is incomplete. Our parameter is the full width. Crop and exclude first, then compute the global mapping on what remains. Otherwise, labels could be matched using speech that does not contribute to the score. Collar implementation Crop before mapping
To avoid sampling approximation, the program collects every relevant endpoint and integrates each constant region exactly up to floating-point arithmetic. If interval has duration and constant count , its integral is the finite sum:
Half-open input intervals assign their endpoint to at most the following segment; touching turns do not create a positive-duration overlap. Duplicate overlapping tracks with the same speaker label are rejected here and must be merged beforehand. That restriction differs from tools that preserve multiple tracks even when their labels are identical.
Score a conversation whose errors you can count
Save the complete program as diarization.py and run python diarization.py with Python 3.12 and NumPy 1.26.4. The scorer accepts at most 32 intervals and six speaker labels in each annotation, times from 0 to 100 seconds, and an explicit nonempty evaluation interval. It has no speech detector or embedding network.
"""Original small clustering and overlap-aware time scoring; no audio inference."""
import itertools
import json
import numpy as np
def finite(value):
return type(value) in (int,float) and np.isfinite(value)
def segments(rows):
if not isinstance(rows,(list,tuple)) or len(rows)>32:raise ValueError('At most32 explicit segments')
out=[]
for row in rows:
if not isinstance(row,(list,tuple)) or len(row)!=3:raise ValueError('Use start,end,label triples')
start,end,label=row
if not finite(start) or not finite(end) or not 0<=start<end<=100:
raise ValueError('Finite half-open intervals in [0,100] seconds')
if not isinstance(label,str) or not 1<=len(label)<=24:raise ValueError('Short speaker labels required')
out.append((float(start),float(end),label))
if len({x[2] for x in out})>6:raise ValueError('At most6 speakers per annotation')
out.sort()
for label in {x[2] for x in out}:
chosen=sorted((a,b) for a,b,c in out if c==label)
if any(b>c for (a,b),(c,d) in zip(chosen,chosen[1:])):
raise ValueError('Overlapping tracks with the same label must first be merged')
return out
def score(reference,hypothesis,region=(0.,10.),collar=0.,skip_overlap=False):
ref,hyp=segments(reference),segments(hypothesis)
if not isinstance(region,(list,tuple)) or len(region)!=2 or not all(finite(x) for x in region) or not 0<=region[0]<region[1]<=100:
raise ValueError('Explicit nonempty evaluation region in [0,100]')
if not finite(collar) or not 0<=collar<=2 or type(skip_overlap) is not bool:
raise ValueError('Collar full width0..2 and Boolean overlap policy')
lo,hi=region;boundaries=[t for a,b,_ in ref for t in (a,b)]
edges={float(lo),float(hi)}
for a,b,_ in ref+hyp:edges.update([max(lo,min(hi,a)),max(lo,min(hi,b))])
for t in boundaries:edges.update([max(lo,min(hi,t-collar/2)),max(lo,min(hi,t+collar/2))])
edges=sorted(edges);atoms=[]
for a,b in zip(edges,edges[1:]):
mid=(a+b)/2;r={c for x,y,c in ref if x<=mid<y};h={c for x,y,c in hyp if x<=mid<y}
if collar and any(abs(mid-t)<collar/2 for t in boundaries):continue
if skip_overlap and len(r)>1:continue
atoms.append(dict(start=a,end=b,reference=sorted(r),hypothesis=sorted(h)))
rl=sorted({x for atom in atoms for x in atom['reference']});hl=sorted({x for atom in atoms for x in atom['hypothesis']})
n=max(len(rl),len(hl));overlap=np.zeros((n,n))
for atom in atoms:
dt=atom['end']-atom['start']
for h in atom['hypothesis']:
for r in atom['reference']:overlap[hl.index(h),rl.index(r)]+=dt
# Exhaustive bounded assignment, not a claimed cubic Hungarian implementation.
best=();mass=-1.
for assignment in itertools.permutations(range(n)):
value=sum(overlap[i,j] for i,j in enumerate(assignment))
if value>mass:mass=value;best=assignment
mapping={h:(rl[best[i]] if best[i]<len(rl) and overlap[i,best[i]]>0 else None) for i,h in enumerate(hl)}
total=dict(reference=0.,correct=0.,miss=0.,false_alarm=0.,confusion=0.,evaluated_time=0.)
for atom in atoms:
r,h=atom['reference'],atom['hypothesis'];dt=atom['end']-atom['start']
correct=sum(mapping[label] in r for label in h)
counts=dict(reference=len(r),correct=correct,miss=max(0,len(r)-len(h)),
false_alarm=max(0,len(h)-len(r)),confusion=min(len(r),len(h))-correct)
atom['counts']=counts;total['evaluated_time']+=dt
for key,value in counts.items():total[key]+=dt*value
errors=total['miss']+total['false_alarm']+total['confusion']
return dict(**total,error_time=errors,der=errors/total['reference'] if total['reference'] else None,
mapping=mapping,cooccurrence=overlap.tolist(),atoms=atoms,
collar_full_width=collar,skip_overlap=skip_overlap)
def agglomerate(embeddings,threshold=.3):
raw=np.asarray(embeddings)
if raw.ndim!=2 or raw.dtype.kind not in 'fiu' or not 1<=len(raw)<=12 or not 1<=raw.shape[1]<=8:
raise ValueError('Use1..12 small real embeddings')
x=raw.astype(float)
if not np.isfinite(x).all() or np.max(abs(x))>20 or not finite(threshold) or not 0<=threshold<=2:
raise ValueError('Finite vectors and cosine-distance threshold0..2')
norm=np.linalg.norm(x,axis=1)
if (norm<1e-10).any():raise ValueError('Nonzero embeddings required')
x=x/norm[:,None];distance=np.clip(1-x@x.T,0,2)
groups=[(i,) for i in range(len(x))];trace=[]
while len(groups)>1:
candidates=[(float(distance[np.ix_(a,b)].mean()),i,j) for i,a in enumerate(groups) for j,b in enumerate(groups) if i<j]
value,i,j=min(candidates)
if value>threshold:break
trace.append(dict(left=list(groups[i]),right=list(groups[j]),distance=value))
merged=tuple(sorted(groups[i]+groups[j]));groups=[g for k,g in enumerate(groups) if k not in (i,j)]+[merged];groups.sort()
labels=np.zeros(len(x),int)
for k,g in enumerate(groups):labels[list(g)]=k
return dict(labels=labels.tolist(),merges=trace,distance=distance.tolist(),linkage='average pairwise cosine distance')
def demo():
reference=[(0,3,'A'),(2,5,'B')]
hypothesis=[(.2,3,'x'),(3,5.2,'y')]
vectors=[[1,.1],[1,-.1],[.1,1],[-.1,1],[-1,0]]
renamed=[(a,b,{'x':'q','y':'p'}[c]) for a,b,c in hypothesis]
return dict(reference=reference,hypothesis=hypothesis,
strict=score(reference,hypothesis,(0,6)),renamed=score(reference,renamed,(0,6)),
collar=score(reference,hypothesis,(0,6),collar=.4),
without_overlap=score(reference,hypothesis,(0,6),skip_overlap=True),
empty=score([],[(1,2,'x')],(0,3)),
clustering=agglomerate(vectors),embeddings=vectors,
scope='Supplied segments and embeddings; no segmentation network, speaker identity or source separation.')
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2,allow_nan=False))
The invented reference is A on [0,3) and B on [2,5); the hypothesis is x on [0.2,3) and y on [3,5.2). The evaluated region is [0,6). Global matching gives x→A and y→B. Reference speaker-time is six seconds. The hypothesis misses A’s first 0.2 seconds and one second of B during overlap, then falsely extends B by 0.2 seconds. Hence miss time is 1.2, false-alarm time 0.2, confusion zero, and DER is .
A full-width collar of 0.4 removes time around every reference boundary, including B’s onset and A’s offset inside the conversation. The remaining reference time is 4.4 speaker-seconds, with 0.6 missed speaker-seconds, giving . Excluding overlap instead gives 4 reference speaker-seconds and 0.4 error seconds, or DER 0.1. These are different scoring conditions for the same hypothesis, not three systems with different accuracy.
The clustering example uses five supplied directions and returns labels [0,0,1,1,2]. Try enlarging the merge threshold: fewer clusters are a consequence of the rule, not evidence that a speaker vanished. Then rename every hypothesis label consistently; DER must remain unchanged. Finally, restrict the evaluated region before mapping and observe that the best label assignment can change.
For embeddings of dimension , the example builds pairwise distances in time and recomputes average-linkage candidates in up to time, with space. For scoring, let be the number of atomic time intervals, the total input segments and the label count after padding. Endpoint sorting costs ; scanning segments costs ; this simple common-activity loop uses list-index lookups and can cost ; exhaustive assignment costs . Saved intervals and the matrix occupy . These deliberate small-data bounds are not a claim of production scalability.
One DER value leaves several questions unanswered
An incorrect speech detector can create misses before clustering begins. A short or overlapping region may yield an unreliable speaker embedding. Clustering thresholds can merge two people or split one into several labels. Local segmentation and global identity consistency therefore need separate diagnosis; improving one part does not automatically improve the whole pipeline. Pipeline dependencies
A low DER need not mean that each short utterance is attributed well, because duration weighting lets long stretches dominate. Report miss, false alarm and confusion separately, plus the evaluation region, overlap policy and collar definition. If a benchmark supplies oracle speech activity or the speaker count, say so. Its result answers a different question from a fully automatic pipeline. The 2023 pyannote paper explicitly discusses incompatible benchmark protocols and reports its chosen no-collar, overlap-inclusive setting. Benchmark protocol
Anonymous diarization also does not identify the person behind a label. To attach known identities, use separately evaluated enrollment and recognition; to recover isolated waveforms, use source separation. Neither capability is supplied by our temporal scorer. The example has no real recordings, speaker model or benchmark reproduction.
For a broader discussion of merge rules, see hierarchical clustering. Its linkage choices explain different cluster shapes; the diarization task still requires a protocol for converting those clusters back into time intervals.
Count, rename and change the protocol
-
The reference has A and B, while an otherwise perfect hypothesis calls them y and x. Should renaming alone increase DER?
Answer: No. A consistent global one-to-one assignment recovers y→A and x→B. The names are arbitrary. The mapping must be global, however: relabeling independently at each instant would conceal real speaker swaps.
-
Two reference speakers talk simultaneously for two seconds. The hypothesis correctly outputs just one of them throughout. What are reference speaker-time, missed time and DER?
Answer: Reference speaker-time is seconds, missed time is 2 seconds, and DER is 0.5. Dividing by the two-second recording duration would give the wrong denominator for overlap-inclusive scoring.
-
A tool uses full collar width 0.2 around each reference boundary. The reference is A on
[1,2)and the hypothesis is x on[1.1,2). What remains to score?Answer: The start collar removes
[0.9,1.1]and the end collar removes[1.9,2.1]. The remaining reference interval has duration 0.8, matched correctly by x, so DER is zero under this protocol. The original 0.1-second onset discrepancy still exists; the protocol deliberately excludes it. -
A six-second recording has no reference speech, but a system outputs one second of speech. What should our report contain?
Answer: One false-alarm speaker-second and an undefined DER because reference speaker-time is zero. Do not silently call it perfect. If comparing another library, inspect its empty-reference convention; the fixed pyannote branch discussed above would return one for a nonzero numerator.
Check the pipeline and the scorer separately
Use the pipeline paper to understand local activity, embeddings, clustering and aggregation. Use the fixed metrics implementation to understand label matching, duration integration and evaluation exclusions. Our calculations provide an independent small example with explicit differences: average linkage, exhaustive assignment, unique active-label sets and an undefined empty-reference rate. Pipeline DER Duration counts Mapping Evaluation regions
Make a prediction, then check
Two speakers overlap for2seconds; one is correctly output. What is DER when overlap is included?
Learning objectives
- Distinguish anonymous time labels from identity recognition and separated waveforms.
- Match labels globally after evaluation-region exclusions.
- Compute overlap-aware DER using reference speaker-time.
- State linkage, collar width and empty-reference conventions.
Prerequisites & connections
Explore related knowledge →References
- pyannote.audio 2.1 speaker diarization pipeline: principle, benchmark, and recipe
Hervé Bredin · 2023 - pyannote.metrics: diarization scoring at349f26f
pyannote/pyannote-metrics contributors - pyannote.metrics: duration-weighted identification at349f26f
pyannote/pyannote-metrics contributors - pyannote.metrics: label matching at349f26f
pyannote/pyannote-metrics contributors - pyannote.metrics: evaluation-region collars at349f26f
pyannote/pyannote-metrics contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-13 · Single AI author checked the scoped pyannote2.1 pipeline and fixed metrics code: crop/collar/overlap policies precede one global mapping, speaker-time denominator, missed/false/confused durations and explicit zero-reference policy. Six paired equations and four explained exercises. Tiny exact permutation mapping and average-cosine clustering differ from Hungarian optimization and paper centroid linkage; no source separation or real speaker identity claims.
- Verified global label permutations, reference speaker-time6, miss1.2 and false alarm0.2, DER1.4/6, full-width0.4 collar giving0.6/4.4, overlap exclusion0.1, empty-reference None and average-cosine labels00112.
- Four computed SVGs bind exact bilingual MDX. The three-topic group passed ten numeric/encoding checks and 18 isolated language/width cases with four fallback fonts; six representative final screenshots inspected by the AI author. Literal-prose AST checked before freezing. Full article browser acceptance is separate; no human peer review.
Source locations checked:
- pyannote.audio 2.1 speaker diarization pipeline: principle, benchmark, and recipe · Read local segmentation, embedding, centroid clustering and aggregation/protocol sections; visually inspected physical pages2–3. No benchmark or speed replicated. Tutorial uses average linkage and is not a2.1 pipeline or later-release compatibility claim.
- pyannote.metrics: diarization scoring at349f26f · Read class notes and105–177: crop/exclude before global mapping and invoke mapped identification scoring. MIT license read; upstream code not run or copied.
- pyannote.metrics: duration-weighted identification at349f26f · Read class notes and130–173: duration counts and denominator0 branch returning0/1. Our unique-label scorer returns None with retained errors when reference speaker-time is zero.
- pyannote.metrics: label matching at349f26f · Read38–155 per-interval counts and157–174 positive co-occurrence Hungarian mapping. Our bounded assignment is exhaustive, not Hungarian; duplicate same-label overlap is rejected.
- pyannote.metrics: evaluation-region collars at349f26f · Read40–108: collar full width split equally around reference boundaries and optional overlap exclusion. Remaining timeline utilities not audited.
Related topics