Skip to content

ADescribe · audio.speakers

Compare voices (speaker embeddings)

Which recordings sound like the same person, and how well can voices be told apart?

Turns each recording into a speaker embedding with ECAPA-TDNN (SpeechBrain's VoxCeleb model, converted to safetensors and written out in Python and R on torch; a one-time download you approve), compares every pair by cosine similarity, groups recordings that sound alike and names each file's closest match. With a known speaker column, every pair becomes a verification trial: the equal error rate, the minimum detection cost, a DET curve and how often the closest file has the same speaker. Speaker embeddings are biometric data: the result never goes to an AI provider, and embeddings saved from it are marked biometric.

Experimental Python and R agree to 6 decimals Also called speaker embeddings, speaker verification, speaker recognition…

A real result

Example “Voices known speakers”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Speaker embeddingsRecorded · Python and R agreeRecorded 2026-11-25 · 18 values compared
R

6 recordings were turned into 192-value speaker embeddings and fell into 3 voice groups at cosine similarity 0.5. Among 3 same-speaker and 12 different-speaker pairs, the equal error rate was 0.0% and the closest other file had the same speaker 100% of the time.

Voice groups
3
Mean similarity to the closest file
0.6686
EER
0.0%

Plots

Voice similarity (cosine)What do the values of a square or rectangular result matrix look like at a glance?
View data
FileSimilarityFileCosine similarity
1. ana_1.wav1.001. ana_1.wav1
2. ana_2.wav0.761. ana_1.wav0.7616
3. ben_1.wav0.281. ana_1.wav0.2784
4. ben_2.wav0.321. ana_1.wav0.3230
5. cal_1.wav0.481. ana_1.wav0.4774
6. cal_2.wav0.411. ana_1.wav0.4109
1. ana_1.wav0.762. ana_2.wav0.7616
2. ana_2.wav1.002. ana_2.wav1
3. ben_1.wav0.332. ana_2.wav0.3310
4. ben_2.wav0.352. ana_2.wav0.3481
5. cal_1.wav0.482. ana_2.wav0.4788
6. cal_2.wav0.452. ana_2.wav0.4478
1. ana_1.wav0.283. ben_1.wav0.2784
2. ana_2.wav0.333. ben_1.wav0.3310
3. ben_1.wav1.003. ben_1.wav1
4. ben_2.wav0.663. ben_1.wav0.6615
5. cal_1.wav0.463. ben_1.wav0.4587
6. cal_2.wav0.423. ben_1.wav0.4151
1. ana_1.wav0.324. ben_2.wav0.3230
2. ana_2.wav0.354. ben_2.wav0.3481
3. ben_1.wav0.664. ben_2.wav0.6615
4. ben_2.wav1.004. ben_2.wav1
5. cal_1.wav0.574. ben_2.wav0.5736
6. cal_2.wav0.504. ben_2.wav0.4951
1. ana_1.wav0.485. cal_1.wav0.4774
2. ana_2.wav0.485. cal_1.wav0.4788
3. ben_1.wav0.465. cal_1.wav0.4587
4. ben_2.wav0.575. cal_1.wav0.5736
5. cal_1.wav1.005. cal_1.wav1
6. cal_2.wav0.585. cal_1.wav0.5826
1. ana_1.wav0.416. cal_2.wav0.4109
2. ana_2.wav0.456. cal_2.wav0.4478
3. ben_1.wav0.426. cal_2.wav0.4151
4. ben_2.wav0.506. cal_2.wav0.4951
5. cal_1.wav0.586. cal_2.wav0.5826
6. cal_2.wav1.006. cal_2.wav1
Detection error tradeoff of the voice comparisonsHow many misses does each false-alarm rate cost — and where do the two errors balance?
View data
Miss rate (same speaker rejected)False alarm rate (different speakers accepted)
01
00.9167
00.8333
00.7500
00.6667
00.5833
00.5000
00.4167
00.3333
00.2500
00.1667
00.0833
00
0.33330
0.66670
Similarity of same-speaker and different-speaker pairsWhat is the smooth shape of a distribution, and how much does it depend on the bandwidth?
View data
PairCosine similarity
Same speaker0.7616
Different speakers0.2784
Different speakers0.3230
Different speakers0.4774
Different speakers0.4109
Different speakers0.3310
Different speakers0.3481
Different speakers0.4788
Different speakers0.4478
Same speaker0.6615
Different speakers0.4587
Different speakers0.4151
Different speakers0.5736
Different speakers0.4951
Same speaker0.5826

Assumptions

  • Voices identify people — Speaker embeddings are biometric data. This result is never sent to an AI provider; saved embeddings are marked biometric. Get consent before comparing other people's voices.
  • One speaker per file — Each file gets one embedding; a file with several voices is a blend of them. Use speaker diarization for conversations.
  • Recordings like VoxCeleb — The model learned from interview speech; shortest file 1.50 s.

Voices

pathSecondsVoice groupMost similar fileCosine similarityspeaker
media/aud3/ana_1.wav1.500V1ana_2.wav0.7616ana
media/aud3/ana_2.wav1.500V1ana_1.wav0.7616ana
media/aud3/ben_1.wav1.500V2ben_2.wav0.6615ben
media/aud3/ben_2.wav1.500V2ben_1.wav0.6615ben
media/aud3/cal_1.wav1.500V3cal_2.wav0.5826cal
media/aud3/cal_2.wav1.500V3cal_1.wav0.5826cal

Same speaker or not: every pair of files with a known speaker

MeasureValue
Target pairs (same speaker)3
Non-target pairs12
Mean similarity, same speaker0.6686
Mean similarity, different speakers0.4198
Equal error rate0
Minimum DCF (π = 0.01)0
Closest-file speaker accuracy1
  • ECAPA-TDNN speaker embeddings by SpeechBrain (Ravanelli et al. 2021), trained on VoxCeleb; 16 kHz mono, float64. Similarity is the cosine of two embeddings (1 = the same direction). Voice groups: average-linkage clustering of the embeddings. Speaker embeddings are biometric data: this result stays on this computer and is never sent to an AI provider.
Python

6 recordings were turned into 192-value speaker embeddings and fell into 3 voice groups at cosine similarity 0.5. Among 3 same-speaker and 12 different-speaker pairs, the equal error rate was 0.0% and the closest other file had the same speaker 100% of the time.

Voice groups
3
Mean similarity to the closest file
0.6686
EER
0.0%

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Voices identify people — Speaker embeddings are biometric data. This result is never sent to an AI provider; saved embeddings are marked biometric. Get consent before comparing other people's voices.
  • One speaker per file — Each file gets one embedding; a file with several voices is a blend of them. Use speaker diarization for conversations.
  • Recordings like VoxCeleb — The model learned from interview speech; shortest file 1.50 s.

Voices

pathSecondsVoice groupMost similar fileCosine similarityspeaker
media/aud3/ana_1.wav1.500V1ana_2.wav0.7616ana
media/aud3/ana_2.wav1.500V1ana_1.wav0.7616ana
media/aud3/ben_1.wav1.500V2ben_2.wav0.6615ben
media/aud3/ben_2.wav1.500V2ben_1.wav0.6615ben
media/aud3/cal_1.wav1.500V3cal_2.wav0.5826cal
media/aud3/cal_2.wav1.500V3cal_1.wav0.5826cal

Same speaker or not: every pair of files with a known speaker

MeasureValue
Target pairs (same speaker)3
Non-target pairs12
Mean similarity, same speaker0.6686
Mean similarity, different speakers0.4198
Equal error rate0
Minimum DCF (π = 0.01)0
Closest-file speaker accuracy1
  • ECAPA-TDNN speaker embeddings by SpeechBrain (Ravanelli et al. 2021), trained on VoxCeleb; 16 kHz mono, float64. Similarity is the cosine of two embeddings (1 = the same direction). Voice groups: average-linkage clustering of the embeddings. Speaker embeddings are biometric data: this result stays on this computer and is never sent to an AI provider.

Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.

Worked examples in the app

  • Voices known speakersaud3_voices · audio: path · speaker: speaker
  • Voices three groupsaud3_voices · audio: path
  • Degenerate all naaud3_voices · audio: path · speaker: speaker
  • Degenerate n1aud3_voices · audio: path · speaker: speaker
  • Degenerate n2aud3_voices · audio: path · speaker: speaker
  • Pdna missing path and speakerpdna_audio · audio: path · speaker: speaker

In the guides

Where it sits in the decision guides

  • Multimodal data exploration (text, image, video) · DS & ML Decision Guide · Describe — summarize and visualize
  • Clustering (k-means, hierarchical) · DS & ML Decision Guide · Discover — find structure without labels

What you need

Audio file pathcategorical · 1 column
A column of audio file paths, such as the path column of an audio folder (Data → Add audio folder…). One speaker per file works best.
Known speaker (optional)categorical · 0–1 column
Who is speaking in each file, when you know it: every pair of files becomes a same-or-different trial with an equal error rate.

Choices you make

options

Group voices above this similaritydefault 0.5

Recordings join one voice group while their average cosine similarity stays above this. Higher makes more, tighter groups.

Number of voice groupsdefault —

Ask for exactly this many voice groups instead of using the similarity.

statistics

Target prior (π)default 0.01

How often two compared recordings would really be the same person; it weights misses against false alarms in the detection cost.

Advanced

Seconds read per filedefault 60

Only the first part of each file is used; longer recordings add time but rarely change the voice.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Voices identify peopleNot checked from data: state why it holds

    Speaker embeddings are biometric data. The result never goes to an AI provider; get consent before comparing other people's voices.

  • One speaker per fileNot checked from data: state why it holds

    Each file gets one embedding, so a file with several voices is a blend. Use speaker diarization for conversations.

  • Recordings like VoxCeleb

    The model learned from interview speech; very short clips (under about 1 s), music or heavy noise make embeddings unreliable.

What it reports

n_rows
Files with a path that decode are analyzed; the rest are counted. Only the first part of each file is read.
n_files
Files with a path that decode are analyzed; the rest are counted. Only the first part of each file is read.
n_embedded
Files with a path that decode are analyzed; the rest are counted. Only the first part of each file is read.
n_unreadable
Files with a path that decode are analyzed; the rest are counted. Only the first part of each file is read.
n_no_path
Files with a path that decode are analyzed; the rest are counted. Only the first part of each file is read.
audio_seconds
Files with a path that decode are analyzed; the rest are counted. Only the first part of each file is read.
dim
A vector (192 values from ECAPA-TDNN) that is close for recordings of the same voice, whatever is said. Biometric data.
n_groups
Recordings joined by average-linkage clustering while their average similarity stays above the threshold.
similarity_threshold
Recordings joined by average-linkage clustering while their average similarity stays above the threshold.
mean_nearest_similarity
The cosine of two speaker embeddings: near 1 for the same voice, lower for different voices; scale varies by recording.
p_target
With known speakers, every pair of files is a trial; the EER and minimum DCF say how well similarity separates them.
n_target_trials
With known speakers, every pair of files is a trial; the EER and minimum DCF say how well similarity separates them.
n_nontarget_trials
With known speakers, every pair of files is a trial; the EER and minimum DCF say how well similarity separates them.
mean_target_similarity
The cosine of two speaker embeddings: near 1 for the same voice, lower for different voices; scale varies by recording.
mean_nontarget_similarity
The cosine of two speaker embeddings: near 1 for the same voice, lower for different voices; scale varies by recording.
eer
With known speakers, every pair of files is a trial; the EER and minimum DCF say how well similarity separates them.
min_dcf
With known speakers, every pair of files is a trial; the EER and minimum DCF say how well similarity separates them.
nn_accuracy
How often a file's most similar other file has the same known speaker or label.

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses pandas, numpy, torch, safetensors, codesplash; R uses torch, jsonlite, nanoparquet, codesplashr.

Default traps between the two languages

  • Both engines read the same decoded samples and run the same ECAPA-TDNN twin in float64 on one thread (torch in Python and R); embeddings agree to about 1e-14, similarities and verification numbers to rounding.
  • Voice groups cluster cosine distances rounded to 1e-12, so last-bit differences can't change which recordings merge.
Python

The exact script CodeSplash ran for example “Voices known speakers” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Compare voices (speaker embeddings)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.speakers 1.0.0 · spec 0256aeda2cef25d2
# Dataset: aud3_voices (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd
import torch

import codesplash as cs
from codesplash import ml as csml
from codesplash.audio import diarize as dz  # average-linkage grouping (twin: codesplashr cs_diarize_*)
from codesplash.audio import ecapa  # ECAPA-TDNN speaker embeddings (twin: codesplashr cs_ecapa_*)
from codesplash.evaluate import verification as vf  # EER and DCF of the trials (twin: codesplashr cs_verif_*)

# %% Audio files listed in the path column
PATH = "path"
SPEAKER = "speaker"
N_GROUPS = None  # None: grouped by the similarity threshold
SIMILARITY = 0.5
P_TARGET = 0.01
DATA_DIR = os.path.dirname(os.path.abspath("tests/parity/fixtures/aud3_voices.parquet"))
df = pd.read_parquet("tests/parity/fixtures/aud3_voices.parquet", columns=[PATH] if SPEAKER is None else [PATH, SPEAKER])
if not len(df):
    cs.cs_error("CS_E_NO_ROWS")
paths = [None if (pd.isna(p) or not str(p).strip()) else str(p) for p in df[PATH].tolist()]  # None, NaN, pd.NA: no path
if all(p is None for p in paths):
    cs.cs_error("CS_E_ALL_MISSING", column=PATH)
# %% Media files (audio column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
import json as _media_json
from codesplash import media as cs_media
media = cs_media.setup(_media_json.loads("{\"ids_column\":\"media_id\",\"kind\":\"audio\",\"path_column\":\"path\",\"role\":\"audio\",\"transform\":{\"max_seconds\":60,\"mono\":true,\"offset_seconds\":0,\"sample_rate\":16000}}"), "target/academy-parity/run-8142/audio.speakers/voices-known-speakers/out-python", df, "tests/parity/fixtures/aud3_voices.parquet")
media_ids = cs_media.ids_of(media, df)
if media.get("root") is None:
    media["root"] = DATA_DIR  # outside the app, relative paths start next to the data file
warnings = []
status = cs_media.status(media, [m if p is not None else None for m, p in zip(media_ids, paths)])
ok = [i for i, (p, s) in enumerate(zip(paths, status)) if p is not None and s is None]
n_no_path = sum(p is None for p in paths)
unreadable = [i for i, (p, s) in enumerate(zip(paths, status)) if p is not None and s is not None]
if not ok:
    i = unreadable[0]
    cs.cs_error("CS_E_MEDIA_DECODE", file=paths[i], reason=status[i])
if len(ok) < 2:
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="Comparing voices", min=2, n=len(ok))
if n_no_path:
    warnings.append(f"{n_no_path} rows have no file path and are left out.")
if unreadable:
    warnings.append(f"{len(unreadable)} files couldn't be decoded and are left out (first: {paths[unreadable[0]]}: {status[unreadable[0]]}).")

# %% Speaker embeddings (ECAPA-TDNN, float64 on one thread: the Parity profile). Biometric: kept out of AI.
torch.set_num_threads(1)
model = ecapa.load(ecapa.locate())
progress = cs.progress(f"Embedding {len(ok)} voices", total=len(ok))
clips, E = [], np.zeros((len(ok), int(model["config"]["lin_neurons"])))
for k, i in enumerate(ok):
    clip = np.asarray(cs_media.audio(media, [media_ids[i]])[0], dtype=np.float64)
    clips.append(clip.size / 16000.0)
    E[k] = ecapa.embed(model, [clip])[0]
    progress.update(k + 1)
progress.done()
S = ecapa.cosine(E, E)

# %% Voice groups (average linkage on cosine distance) and each file's closest other file
labels = dz.ahc(E, n_speakers=N_GROUPS, similarity=SIMILARITY, max_speakers=len(ok))
n_groups = int(labels.max()) + 1
names = [os.path.basename(paths[i]) for i in ok]
near, near_sim = [], []
for k in range(len(ok)):
    row = S[k].copy()
    row[k] = -np.inf
    j = int(np.argmax(row))
    near.append(names[j])
    near_sim.append(float(S[k, j]))

# %% Known speakers: every pair of files is a trial (same speaker or not)
spk = None
trial = None
nn_acc = None
if SPEAKER is not None:
    spk = [None if pd.isna(v) else str(v) for v in df[SPEAKER].tolist()]  # None, NaN, pd.NA: unknown speaker
    lab = [spk[i] for i in ok]
    # Every pair a < b of files whose speakers are known, in the order a, then b, built in one pass (a loop over the
    # pairs held two Python lists of them: about 80 bytes and one interpreter step per pair at the row cap).
    levels = {}
    code = np.array([-1 if v is None else levels.setdefault(v, len(levels)) for v in lab], dtype=np.int64)
    pa, pb = np.triu_indices(len(ok), 1)
    known = (code[pa] >= 0) & (code[pb] >= 0)
    pa, pb = pa[known], pb[known]
    sc = np.asarray(S[pa, pb], dtype=np.float64)
    same = code[pa] == code[pb]
    del pa, pb, known
    if same.any() and (~same).any():
        trial = vf.summary(sc, same, P_TARGET, 1.0, 1.0, "linear")
        trial["mean_target"] = float(sc[same].mean())
        trial["mean_nontarget"] = float(sc[~same].mean())
        trial["pts"] = vf.det_points(sc, same)
        trial["scores"], trial["same"] = sc, same
    else:
        warnings.append("Known speakers need at least two files of one speaker and two different speakers for verification scores.")
    hits, n_id = 0, 0
    for a in range(len(ok)):
        if lab[a] is None or sum(1 for b in range(len(ok)) if b != a and lab[b] == lab[a]) == 0:
            continue
        row = np.array([S[a, b] if (b != a and lab[b] is not None) else -np.inf for b in range(len(ok))])
        j = int(np.argmax(row))
        hits += int(lab[j] == lab[a])
        n_id += 1
    nn_acc = hits / n_id if n_id else None

# %% Artifact: one row per embedded file (biometric — never shared with AI)
out = csml.out_dir("target/academy-parity/run-8142/audio.speakers/voices-known-speakers/out-python")
art = pd.DataFrame({"row": np.array(ok, dtype=np.int64), "media_id": [media_ids[i] for i in ok], "path": [paths[i] for i in ok],
                    "voice_group": [f"V{g + 1}" for g in labels]})
for d in range(E.shape[1]):
    art[f"emb_{d + 1}"] = E[:, d]
art.to_parquet(os.path.join(out, "speakers.parquet"), index=False)

# %% Assumptions
assumptions = [
    {"key": "biometric", "label": "Voices identify people", "status": "info",
     "detail": "Speaker embeddings are biometric data. This result is never sent to an AI provider; saved embeddings are marked biometric. Get consent before comparing other people's voices."},
    {"key": "one_speaker", "label": "One speaker per file", "status": "info",
     "detail": "Each file gets one embedding; a file with several voices is a blend of them. Use speaker diarization for conversations."},
    {"key": "domain", "label": "Recordings like VoxCeleb", "status": "warn" if min(clips) < 1.0 else "pass",
     "detail": f"The model learned from interview speech; shortest file {min(clips):.2f} s" + ("; below about 1 s the embeddings are unreliable." if min(clips) < 1.0 else ".")},
]

# %% Result
f3 = lambda v: "—" if v is None else f"{v:.3f}"
values = {"n_rows": len(df), "n_files": len(ok) + len(unreadable), "n_embedded": len(ok), "n_unreadable": len(unreadable), "n_no_path": n_no_path,
          "audio_seconds": float(sum(clips)), "dim": int(E.shape[1]), "n_groups": n_groups, "similarity_threshold": SIMILARITY if N_GROUPS is None else None,
          "mean_nearest_similarity": float(np.mean(near_sim)), "p_target": P_TARGET,
          "n_target_trials": int(trial["n_target"]) if trial else None, "n_nontarget_trials": int(trial["n_nontarget"]) if trial else None,
          "mean_target_similarity": trial["mean_target"] if trial else None, "mean_nontarget_similarity": trial["mean_nontarget"] if trial else None,
          "eer": trial["eer"] if trial else None, "min_dcf": trial["min_dcf"] if trial else None, "nn_accuracy": nn_acc}
file_rows = []
for k, i in enumerate(ok):
    r = {"file": paths[i], "seconds": clips[k], "voice_group": f"V{labels[k] + 1}", "nearest": near[k], "similarity": near_sim[k]}
    if spk is not None:
        r["speaker"] = spk[i]
    file_rows.append(r)
cols = [{"key": "file", "label": PATH, "type": "string"}, {"key": "seconds", "label": "Seconds", "type": "number"},
        {"key": "voice_group", "label": "Voice group", "type": "string"}, {"key": "nearest", "label": "Most similar file", "type": "string"},
        {"key": "similarity", "label": "Cosine similarity", "type": "number"}]
if spk is not None:
    cols.append({"key": "speaker", "label": SPEAKER, "type": "string"})
tables = [{"key": "files", "title": "Voices", "columns": cols, "rows": file_rows[:500], "note": "First 500 files." if len(file_rows) > 500 else None}]
if trial:
    tables.append({"key": "verification", "title": "Same speaker or not: every pair of files with a known speaker",
                   "columns": [{"key": "measure", "label": "Measure", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
                   "rows": [{"measure": "Target pairs (same speaker)", "value": trial["n_target"]},
                            {"measure": "Non-target pairs", "value": trial["n_nontarget"]},
                            {"measure": "Mean similarity, same speaker", "value": trial["mean_target"]},
                            {"measure": "Mean similarity, different speakers", "value": trial["mean_nontarget"]},
                            {"measure": "Equal error rate", "value": trial["eer"]},
                            {"measure": f"Minimum DCF (π = {P_TARGET:g})", "value": trial["min_dcf"]},
                            {"measure": "Closest-file speaker accuracy", "value": nn_acc}]})
charts = []
m = min(len(ok), 40)
lv = [f"{k + 1}. {names[k]}" for k in range(m)]
charts.append(cs.chart("similarity", "matrix-heatmap", "Voice similarity (cosine)" + (" — first 40 files" if len(ok) > 40 else ""), {
    "row": cs.col("File", [lv[a] for a in range(m) for _ in range(m)], "categorical", levels=lv),
    "col": cs.col("File", [lv[b] for _ in range(m) for b in range(m)], "categorical", levels=lv),
    "value": cs.col("Cosine similarity", [float(S[a, b]) for a in range(m) for b in range(m)]),
    "label": cs.col("Similarity", [f"{S[a, b]:.2f}" for a in range(m) for b in range(m)], "categorical")},
    controls={"scale": "sequential"}))
scores_note = []
if trial:
    pts = trial["pts"]
    inner = [i for i in range(pts["threshold"].size) if np.isfinite(pts["threshold"][i])]
    keep = [inner[j] for j in vf.thin(len(inner))]
    charts.append(cs.chart("det", "det-curve", "Detection error tradeoff of the voice comparisons", {
        "fpr": cs.col("False alarm rate (different speakers accepted)", [float(pts["fpr"][i]) for i in keep]),
        "fnr": cs.col("Miss rate (same speaker rejected)", [float(pts["fnr"][i]) for i in keep])},
        controls={"eer": trial["eer"], "minDcf": trial["min_dcf"], "minDcfFpr": trial["min_dcf_fpr"], "minDcfFnr": trial["min_dcf_fnr"]}))
    # Every pair up to 20,000; above that a seeded sample within each kind of pair (R draws the same pairs). The EER,
    # detection costs and DET curve above use every pair.
    shown = vf.chart_sample(trial["same"], 20000, seed=1)
    n_pairs = int(trial["same"].size)
    if shown.size < n_pairs:
        scores_note.append(f"The similarity chart draws a seeded sample of {shown.size:,} of the {n_pairs:,} pairs (the rarer kind keeps "
                           "up to half of it, so both curves keep their shape; the same pairs in Python and R). The equal error rate, "
                           "the detection costs and the DET curve use every pair.")
    charts.append(cs.chart("scores", "density", "Similarity of same-speaker and different-speaker pairs"
                           + (f" — a sample of {shown.size:,} of {n_pairs:,} pairs" if shown.size < n_pairs else ""), {
        "x": cs.col("Cosine similarity", [float(v) for v in trial["scores"][shown]]),
        "group": cs.col("Pair", ["Same speaker" if t else "Different speakers" for t in trial["same"][shown]], "categorical",
                        levels=["Different speakers", "Same speaker"])},
        controls={"compare": False}))
summary = (f"{len(ok)} recordings were turned into {E.shape[1]}-value speaker embeddings and fell into {n_groups} voice "
           f"group{'s' if n_groups != 1 else ''}" + (f" at cosine similarity {SIMILARITY:g}." if N_GROUPS is None else " (the number asked for)."))
if trial:
    summary += (f" Among {trial['n_target']} same-speaker and {trial['n_nontarget']} different-speaker pairs, the equal error rate was "
                f"{100 * trial['eer']:.1f}% and the closest other file had the same speaker {100 * nn_acc:.0f}% of the time." if nn_acc is not None else "")
cs.publish({
    "method": "audio.speakers",
    "methodVersion": "1.0.0",
    "title": "Speaker embeddings",
    "engine": cs.engine_info("numpy", "torch"),
    "n": len(ok),
    "biometric": True,
    "summary": summary,
    "statistics": [{"key": "n_groups", "label": "Voice groups", "value": n_groups, "format": "integer"},
                   {"key": "mean_nearest_similarity", "label": "Mean similarity to the closest file", "value": values["mean_nearest_similarity"]}]
                  + ([{"key": "eer", "label": "EER", "value": trial["eer"], "format": "percent"}] if trial else []),
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": ["ECAPA-TDNN speaker embeddings by SpeechBrain (Ravanelli et al. 2021), trained on VoxCeleb; 16 kHz mono, float64. "
              "Similarity is the cosine of two embeddings (1 = the same direction). Voice groups: average-linkage clustering of the "
              "embeddings. Speaker embeddings are biometric data: this result stays on this computer and is never sent to an AI provider."]
             + scores_note,
    "charts": charts,
    "artifacts": [{"key": "speakers", "path": os.path.join(out, "speakers.parquet"), "format": "parquet", "biometric": True}],
    "values": values,
})
R

The exact script CodeSplash ran for example “Voices known speakers” · R version 4.5.1 (2025-06-13)

# Compare voices (speaker embeddings)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.speakers 1.0.0 · spec 0256aeda2cef25d2
# Dataset: aud3_voices (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_ecapa_* (ECAPA-TDNN), cs_diarize_ahc (grouping), cs_verif_* (EER, DCF)

# %% Audio files listed in the path column
PATH <- "path"
SPEAKER <- "speaker"
N_GROUPS <- NULL  # NULL: grouped by the similarity threshold
SIMILARITY <- 0.5
P_TARGET <- 0.01
DATA_DIR <- dirname(normalizePath("tests/parity/fixtures/aud3_voices.parquet"))
df <- nanoparquet::read_parquet("tests/parity/fixtures/aud3_voices.parquet", col_select = if (is.null(SPEAKER)) PATH else c(PATH, SPEAKER))
df <- as.data.frame(df)
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
paths <- as.character(df[[PATH]])
paths[is.na(paths) | !nzchar(trimws(paths))] <- NA_character_
if (all(is.na(paths))) cs_error("CS_E_ALL_MISSING", column = PATH)
# %% Media files (audio column path)
# In the app the files were decoded once into float32 arrays (media.json in the run folder). Elsewhere they are
# decoded here the same way: PNG and WAV give the app's values; JPEG, MP3 and other lossy files can differ slightly.
media <- cs_media_setup(jsonlite::fromJSON("{\"ids_column\":\"media_id\",\"kind\":\"audio\",\"path_column\":\"path\",\"role\":\"audio\",\"transform\":{\"max_seconds\":60,\"mono\":true,\"offset_seconds\":0,\"sample_rate\":16000}}", simplifyVector = FALSE), "target/academy-parity/run-8142/audio.speakers/voices-known-speakers/out-r", df,
                        "tests/parity/fixtures/aud3_voices.parquet")
media_ids <- cs_media_ids(media, df)
if (is.null(media$root)) media$root <- DATA_DIR  # outside the app, relative paths start next to the data file
warnings <- character(0)
ids_for <- ifelse(is.na(paths), NA_character_, media_ids)
status <- cs_media_status(media, ids_for)
ok <- which(!is.na(paths) & is.na(status))
n_no_path <- sum(is.na(paths))
unreadable <- which(!is.na(paths) & !is.na(status))
if (!length(ok)) cs_error("CS_E_MEDIA_DECODE", file = paths[unreadable[1]], reason = status[unreadable[1]])
if (length(ok) < 2) cs_error("CS_E_TOO_FEW_ROWS", what = "Comparing voices", min = 2, n = length(ok))
if (n_no_path > 0) warnings <- c(warnings, sprintf("%d rows have no file path and are left out.", n_no_path))
if (length(unreadable)) warnings <- c(warnings, sprintf("%d files couldn't be decoded and are left out (first: %s: %s).",
                                                        length(unreadable), paths[unreadable[1]], status[unreadable[1]]))

# %% Speaker embeddings (ECAPA-TDNN, float64 on one thread: the Parity profile). Biometric: kept out of AI.
torch::torch_set_num_threads(1L)
model <- cs_ecapa_load(cs_ecapa_locate())
progress <- cs_progress(sprintf("Embedding %d voices", length(ok)), total = length(ok))
secs <- numeric(length(ok))
E <- matrix(0, nrow = length(ok), ncol = as.integer(model$config$lin_neurons))
for (k in seq_along(ok)) {
  clip <- as.numeric(cs_media_audio(media, media_ids[ok[k]])[[1]])
  secs[k] <- length(clip) / 16000
  E[k, ] <- cs_ecapa_embed(model, list(clip))[1, ]
  cs_progress_update(progress, k)
}
cs_progress_done(progress)
S <- cs_ecapa_cosine(E, E)

# %% Voice groups (average linkage on cosine distance) and each file's closest other file
labels <- cs_diarize_ahc(E, n_speakers = N_GROUPS, similarity = SIMILARITY, max_speakers = length(ok))
n_groups <- max(labels) + 1L
names_ <- basename(paths[ok])
near <- character(length(ok))
near_sim <- numeric(length(ok))
for (k in seq_along(ok)) {
  row <- S[k, ]
  row[k] <- -Inf
  j <- which.max(row)
  near[k] <- names_[j]
  near_sim[k] <- S[k, j]
}

# %% Known speakers: every pair of files is a trial (same speaker or not)
spk <- NULL
trial <- NULL
nn_acc <- NULL
if (!is.null(SPEAKER)) {
  spk <- as.character(df[[SPEAKER]])
  lab <- spk[ok]
  # Every pair a < b of files whose speakers are known, in the order a, then b, built in one pass (growing the two
  # vectors pair by pair copied them once per pair: hours at the row cap).
  k <- length(ok)
  pa <- rep.int(seq_len(k), k - seq_len(k))
  pb <- as.integer(unlist(lapply(seq_len(k), function(a) if (a < k) (a + 1L):k else integer(0)), use.names = FALSE))
  known <- !is.na(lab[pa]) & !is.na(lab[pb])
  pa <- pa[known]
  pb <- pb[known]
  sc <- as.numeric(S[cbind(pa, pb)])
  same <- lab[pa] == lab[pb]
  if (any(same) && any(!same)) {
    trial <- cs_verif_summary(sc, same, P_TARGET, 1, 1, "linear")
    trial$mean_target <- mean(sc[same])
    trial$mean_nontarget <- mean(sc[!same])
    trial$pts <- cs_verif_det_points(sc, same)
    trial$scores <- sc
    trial$same <- same
  } else {
    warnings <- c(warnings, "Known speakers need at least two files of one speaker and two different speakers for verification scores.")
  }
  hits <- 0L
  n_id <- 0L
  for (a in seq_along(ok)) {
    if (is.na(lab[a]) || sum(seq_along(ok) != a & !is.na(lab) & lab == lab[a]) == 0) next
    row <- vapply(seq_along(ok), function(b) if (b != a && !is.na(lab[b])) S[a, b] else -Inf, numeric(1))
    j <- which.max(row)
    hits <- hits + as.integer(lab[j] == lab[a])
    n_id <- n_id + 1L
  }
  nn_acc <- if (n_id > 0) hits / n_id else NULL
}

# %% Artifact: one row per embedded file (biometric — never shared with AI)
out <- cs_ml_out_dir("target/academy-parity/run-8142/audio.speakers/voices-known-speakers/out-r")
art <- data.frame(row = as.integer(ok - 1L), media_id = media_ids[ok], path = paths[ok], voice_group = sprintf("V%d", labels + 1L),
                  stringsAsFactors = FALSE)
for (d in seq_len(ncol(E))) art[[sprintf("emb_%d", d)]] <- E[, d]
nanoparquet::write_parquet(art, file.path(out, "speakers.parquet"))

# %% Assumptions
assumptions <- list(
  list(key = "biometric", label = "Voices identify people", status = "info",
       detail = "Speaker embeddings are biometric data. This result is never sent to an AI provider; saved embeddings are marked biometric. Get consent before comparing other people's voices."),
  list(key = "one_speaker", label = "One speaker per file", status = "info",
       detail = "Each file gets one embedding; a file with several voices is a blend of them. Use speaker diarization for conversations."),
  list(key = "domain", label = "Recordings like VoxCeleb", status = if (min(secs) < 1) "warn" else "pass",
       detail = paste0(sprintf("The model learned from interview speech; shortest file %.2f s", min(secs)),
                       if (min(secs) < 1) "; below about 1 s the embeddings are unreliable." else "."))
)

# %% Result
values <- list(n_rows = nrow(df), n_files = length(ok) + length(unreadable), n_embedded = length(ok), n_unreadable = length(unreadable),
               n_no_path = n_no_path, audio_seconds = sum(secs), dim = ncol(E), n_groups = n_groups,
               similarity_threshold = if (is.null(N_GROUPS)) SIMILARITY else NULL, mean_nearest_similarity = mean(near_sim), p_target = P_TARGET,
               n_target_trials = if (!is.null(trial)) as.integer(trial$n_target) else NULL,
               n_nontarget_trials = if (!is.null(trial)) as.integer(trial$n_nontarget) else NULL,
               mean_target_similarity = if (!is.null(trial)) trial$mean_target else NULL,
               mean_nontarget_similarity = if (!is.null(trial)) trial$mean_nontarget else NULL,
               eer = if (!is.null(trial)) trial$eer else NULL, min_dcf = if (!is.null(trial)) trial$min_dcf else NULL, nn_accuracy = nn_acc)
file_rows <- lapply(seq_along(ok), function(k) {
  r <- list(file = paths[ok[k]], seconds = secs[k], voice_group = sprintf("V%d", labels[k] + 1L), nearest = near[k], similarity = near_sim[k])
  if (!is.null(spk)) r$speaker <- spk[ok[k]]
  r
})
cols <- list(list(key = "file", label = PATH, type = "string"), list(key = "seconds", label = "Seconds", type = "number"),
             list(key = "voice_group", label = "Voice group", type = "string"), list(key = "nearest", label = "Most similar file", type = "string"),
             list(key = "similarity", label = "Cosine similarity", type = "number"))
if (!is.null(spk)) cols[[length(cols) + 1L]] <- list(key = "speaker", label = SPEAKER, type = "string")
tables <- list(list(key = "files", title = "Voices", columns = cols, rows = head(file_rows, 500),
                    note = if (length(file_rows) > 500) "First 500 files." else NULL))
if (!is.null(trial)) tables[[length(tables) + 1L]] <- list(key = "verification", title = "Same speaker or not: every pair of files with a known speaker",
  columns = list(list(key = "measure", label = "Measure", type = "string"), list(key = "value", label = "Value", type = "number")),
  rows = list(list(measure = "Target pairs (same speaker)", value = trial$n_target),
              list(measure = "Non-target pairs", value = trial$n_nontarget),
              list(measure = "Mean similarity, same speaker", value = trial$mean_target),
              list(measure = "Mean similarity, different speakers", value = trial$mean_nontarget),
              list(measure = "Equal error rate", value = trial$eer),
              list(measure = sprintf("Minimum DCF (π = %s)", format(P_TARGET)), value = trial$min_dcf),
              list(measure = "Closest-file speaker accuracy", value = nn_acc)))
m <- min(length(ok), 40L)
lv <- sprintf("%d. %s", seq_len(m), names_[seq_len(m)])
ia <- rep(seq_len(m), each = m)
ib <- rep(seq_len(m), times = m)
charts <- list(cs_chart("similarity", "matrix-heatmap", paste0("Voice similarity (cosine)", if (length(ok) > 40) " — first 40 files" else ""), list(
  row = cs_col("File", lv[ia], "categorical", levels = lv),
  col = cs_col("File", lv[ib], "categorical", levels = lv),
  value = cs_col("Cosine similarity", S[cbind(ia, ib)]),
  label = cs_col("Similarity", sprintf("%.2f", S[cbind(ia, ib)]), "categorical")),
  controls = list(scale = "sequential")))
scores_note <- list()
if (!is.null(trial)) {
  pts <- trial$pts
  inner <- which(is.finite(pts$threshold))
  keep <- inner[cs_verif_thin(length(inner))]
  charts[[length(charts) + 1L]] <- cs_chart("det", "det-curve", "Detection error tradeoff of the voice comparisons", list(
    fpr = cs_col("False alarm rate (different speakers accepted)", pts$fpr[keep]),
    fnr = cs_col("Miss rate (same speaker rejected)", pts$fnr[keep])),
    controls = list(eer = trial$eer, minDcf = trial$min_dcf, minDcfFpr = trial$min_dcf_fpr, minDcfFnr = trial$min_dcf_fnr))
  # Every pair up to 20,000; above that a seeded sample within each kind of pair (Python draws the same pairs). The EER,
  # detection costs and DET curve above use every pair.
  shown <- cs_verif_chart_sample(trial$same, 20000L, seed = 1L)
  n_pairs <- length(trial$same)
  big <- function(x) formatC(x, format = "d", big.mark = ",")
  if (length(shown) < n_pairs) scores_note <- list(paste0(sprintf("The similarity chart draws a seeded sample of %s of the %s pairs (the rarer kind keeps ",
                                                                  big(length(shown)), big(n_pairs)),
    "up to half of it, so both curves keep their shape; the same pairs in Python and R). The equal error rate, ",
    "the detection costs and the DET curve use every pair."))
  charts[[length(charts) + 1L]] <- cs_chart("scores", "density", paste0("Similarity of same-speaker and different-speaker pairs",
    if (length(shown) < n_pairs) sprintf(" — a sample of %s of %s pairs", big(length(shown)), big(n_pairs)) else ""), list(
    x = cs_col("Cosine similarity", trial$scores[shown]),
    group = cs_col("Pair", ifelse(trial$same[shown], "Same speaker", "Different speakers"), "categorical", levels = c("Different speakers", "Same speaker"))),
    controls = list(compare = FALSE))
}
summary <- paste0(sprintf("%d recordings were turned into %d-value speaker embeddings and fell into %d voice group%s", length(ok), ncol(E),
                          n_groups, if (n_groups != 1) "s" else ""),
                  if (is.null(N_GROUPS)) sprintf(" at cosine similarity %s.", format(SIMILARITY)) else " (the number asked for).")
if (!is.null(trial) && !is.null(nn_acc)) summary <- paste(summary, sprintf(
  "Among %d same-speaker and %d different-speaker pairs, the equal error rate was %.1f%% and the closest other file had the same speaker %.0f%% of the time.",
  as.integer(trial$n_target), as.integer(trial$n_nontarget), 100 * trial$eer, 100 * nn_acc))
statistics <- list(list(key = "n_groups", label = "Voice groups", value = n_groups, format = "integer"),
                   list(key = "mean_nearest_similarity", label = "Mean similarity to the closest file", value = values$mean_nearest_similarity))
if (!is.null(trial)) statistics[[length(statistics) + 1L]] <- list(key = "eer", label = "EER", value = trial$eer, format = "percent")
cs_publish(list(
  method = "audio.speakers",
  methodVersion = "1.0.0",
  title = "Speaker embeddings",
  engine = cs_engine_info("torch", "nanoparquet"),
  n = length(ok),
  biometric = TRUE,
  summary = summary,
  statistics = statistics,
  tables = tables,
  assumptions = assumptions,
  warnings = as.list(warnings),
  notes = c(list(paste0("ECAPA-TDNN speaker embeddings by SpeechBrain (Ravanelli et al. 2021), trained on VoxCeleb; 16 kHz mono, float64. ",
                        "Similarity is the cosine of two embeddings (1 = the same direction). Voice groups: average-linkage clustering of the ",
                        "embeddings. Speaker embeddings are biometric data: this result stays on this computer and is never sent to an AI provider.")),
            scores_note),
  charts = charts,
  artifacts = list(list(key = "speakers", path = file.path(out, "speakers.parquet"), format = "parquet", biometric = TRUE)),
  values = values
))

Sources

  • Desplanques, B., Thienpondt, J., & Demuynck, K. (2020). ECAPA-TDNN: Emphasized channel attention, propagation and aggregation in TDNN based speaker verification. Proceedings of Interspeech, 3830–3834.
  • Ravanelli, M., Parcollet, T., Plantinga, P., et al. (2021). SpeechBrain: A general-purpose speech toolkit. arXiv:2106.04624.
  • Snyder, D., Garcia-Romero, D., Sell, G., Povey, D., & Khudanpur, S. (2018). X-vectors: Robust DNN embeddings for speaker recognition. Proceedings of ICASSP, 5329–5333.
  • Nagrani, A., Chung, J. S., & Zisserman, A. (2017). VoxCeleb: a large-scale speaker identification dataset. Proceedings of Interspeech, 2616–2620.
  • Chung, J. S., Nagrani, A., & Zisserman, A. (2018). VoxCeleb2: Deep speaker recognition. Proceedings of Interspeech, 1086–1090.

From the CodeSplash method registry · audio.speakers v1.0.0.