AI Wiki中文/EN

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.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

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

Time intervals determine the overlap matrix and global speaker mapping. Different collar and overlap policies change the scoring denominator; these bars compare protocols, not models.
Time intervals determine the overlap matrix and global speaker mapping. Different collar and overlap policies change the scoring denominator; these bars compare protocols, not models.

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 A,BA,B, this distance is:

d(A,B)=1∣A∣∣B∣∑i∈A∑j∈B(1−e^i⊤e^j),e^i=ei∥ei∥.d(A,B)=\frac{1}{|A||B|}\sum_{i\in A}\sum_{j\in B}\left(1-\widehat e_i^\top\widehat e_j\right),\qquad \widehat e_i=\frac{e_i}{\|e_i\|}.

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 R(t)R(t) and H(t)H(t) be the sets of active reference and hypothesis speakers at time tt, and UU the evaluated time region after exclusions. Their common-activity matrix is:

Whr=∫U1[h∈H(t)]1[r∈R(t)] dt,π∗=arg⁡max⁡π one-to-one∑hWh,π(h).W_{hr}=\int_U\mathbf1[h\in H(t)]\mathbf1[r\in R(t)]\,dt,\qquad \pi^*=\arg\max_{\pi\text{ one-to-one}}\sum_h W_{h,\pi(h)}.

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 nr=∣R(t)∣n_r=|R(t)|, nh=∣H(t)∣n_h=|H(t)|, and cc be the number of correctly matched active speakers. The instantaneous error counts are:

m(t)=max⁡(nr−nh,0),f(t)=max⁡(nh−nr,0),q(t)=min⁡(nr,nh)−c(t).m(t)=\max(n_r-n_h,0),\qquad f(t)=\max(n_h-n_r,0),\qquad q(t)=\min(n_r,n_h)-c(t).

Here mm counts missed speakers, ff counts excess hypothesis speakers, and qq 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:

TR=∫Unr(t) dt,Em=∫Um(t) dt,Ef=∫Uf(t) dt,Eq=∫Uq(t) dt,DER=Em+Ef+EqTR.T_R=\int_U n_r(t)\,dt,\qquad E_m=\int_U m(t)\,dt,\quad E_f=\int_U f(t)\,dt,\quad E_q=\int_U q(t)\,dt,\qquad \mathrm{DER}=\frac{E_m+E_f+E_q}{T_R}.

With overlap, TRT_R 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 TR=0T_R=0, 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 bb and full collar width γ\gamma, the inspected pyannote utility removes:

Cb=[b−γ2,b+γ2],O={{t:∣R(t)∣>1}exclude overlap,∅keep overlap,U′=U∖(⋃bCb∪O).C_b=\left[b-\frac\gamma2,b+\frac\gamma2\right],\quad O=\begin{cases}\{t:|R(t)|>1\}&\text{exclude overlap},\\\varnothing&\text{keep overlap},\end{cases}\quad U'=U\setminus\left(\bigcup_b C_b\cup O\right).

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 jj has duration Δj\Delta_j and constant count aja_j, its integral is the finite sum:

∫U′a(t) dt=∑j retainedΔjaj,Δj=tj+1−tj.\int_{U'}a(t)\,dt=\sum_{j\,\mathrm{retained}}\Delta_j a_j,\qquad \Delta_j=t_{j+1}-t_j.

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 1.4/6≈0.2333331.4/6\approx0.233333.

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 0.6/4.4≈0.1363640.6/4.4\approx0.136364. 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 NN embeddings of dimension DD, the example builds pairwise distances in O(N2D)O(N^2D) time and recomputes average-linkage candidates in up to O(N3)O(N^3) time, with O(N2+ND)O(N^2+ND) space. For scoring, let EE be the number of atomic time intervals, SS the total input segments and K≤6K\le6 the label count after padding. Endpoint sorting costs O(Elog⁡E)O(E\log E); scanning segments costs O(ES)O(ES); this simple common-activity loop uses list-index lookups and can cost O(EK3)O(EK^3); exhaustive assignment costs O(K!K)O(K!K). Saved intervals and the matrix occupy O(EK+K2)O(EK+K^2). 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

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

  2. 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 2×2=42\times2=4 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.

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

  4. 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?

Choose one answer

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

  1. pyannote.audio 2.1 speaker diarization pipeline: principle, benchmark, and recipe
    Hervé Bredin · 2023
  2. pyannote.metrics: diarization scoring at349f26f
    pyannote/pyannote-metrics contributors
  3. pyannote.metrics: duration-weighted identification at349f26f
    pyannote/pyannote-metrics contributors
  4. pyannote.metrics: label matching at349f26f
    pyannote/pyannote-metrics contributors
  5. 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:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.