Skip to content

What is heard in recordings: sound tags and embeddings

Tag a folder of recordings with the 527 AudioSet sound classes, read what the scores do and don't say, and map recordings that sound alike with audio embeddings.

Applied ~12 min6 steps

What runs in CodeSplash

You will be able to

  • Read AudioSet tag scores as "heard somewhere in a window", not as calibrated probabilities or event times
  • Choose between the highest and the mean window score for long recordings
  • Use sound embeddings and their nearest neighbors to find recordings that sound alike, and save them as features

Read first

01

Recordings as data

Read

A folder of field recordings, machine noises or call snippets is hard to summarize by listening. A pretrained tagger gives every file a score on many sound classes at once. Here the Audio Spectrogram TransformerAudio Spectrogram Transformer (AST)A vision transformer applied to 16×16 patches of a log-mel spectrogram; this one was trained on AudioSet by MIT., trained by MIT on Google's AudioSet, scores each recording on 527 AudioSet classesAudioSet tagsGoogle's 527 sound classes (speech, music, dog, siren…); the tagger scores each one from 0 to 1 per file.: speech, music, dog, siren, engine, sine wave and so on. The app writes the model out in both Python and R, and both give the same scores.

The example folder holds four computed sounds: a 440 Hz tone, a rising chirp, white noise and a synthetic vowel from a formant synthesizer. Nobody's voice is involved.

02

Make a guess

Predict

Predict first

What will the tagger name first for the steady 440 Hz tone?

Sine waveMusicSpeech
Reveal

It is Sine wave, the top tag of 2 of the four files: the chirp is a sweeping sine, so it scores high on the same class.

03

Reading the tags

Read
Sound tagsRecorded · Python and R agreeRecorded 2026-11-25 · 15 values compared
R

4 recordings (4.5 s) were tagged with the 527 AudioSet classes; the most common top tag is “Sine wave” (2 of 4 files).

Files tagged
4
Mean top score
0.5335

Plots

Tag scores by fileWhat do the values of a square or rectangular result matrix look like at a glance?
View data
TagScoreFileScore
Sine wave0.711. tone_440.wav0.7139
Static0.001. tone_440.wav0.0001
Sound effect0.001. tone_440.wav0.0029
Music0.001. tone_440.wav0.0030
White noise0.001. tone_440.wav0.0002
Electronic music0.001. tone_440.wav0.0002
Synthesizer0.001. tone_440.wav0.0002
Chirp tone0.011. tone_440.wav0.0115
Dial tone0.071. tone_440.wav0.0691
Speech0.001. tone_440.wav0.0033
Beep, bleep0.021. tone_440.wav0.0218
Busy signal0.041. tone_440.wav0.0420
Sine wave0.292. chirp.wav0.2877
Static0.002. chirp.wav0.0002
Sound effect0.032. chirp.wav0.0307
Music0.022. chirp.wav0.0160
White noise0.002. chirp.wav0.0006
Electronic music0.002. chirp.wav0.0017
Synthesizer0.002. chirp.wav0.0050
Chirp tone0.072. chirp.wav0.0738
Dial tone0.012. chirp.wav0.0071
Speech0.012. chirp.wav0.0056
Beep, bleep0.032. chirp.wav0.0319
Busy signal0.002. chirp.wav0.0028
Sine wave0.003. noise.wav0.0003
Static0.763. noise.wav0.7562
Sound effect0.013. noise.wav0.0074
Music0.033. noise.wav0.0293
White noise0.183. noise.wav0.1805
Electronic music0.003. noise.wav0.0011
Synthesizer0.003. noise.wav0.0002
Chirp tone0.003. noise.wav4.379e-5
Dial tone0.003. noise.wav0.0001
Speech0.063. noise.wav0.0551
Beep, bleep0.003. noise.wav0.0006
Busy signal0.003. noise.wav0.0002
Sine wave0.004. ana_1.wav0.0005
Static0.004. ana_1.wav0.0013
Sound effect0.384. ana_1.wav0.3760
Music0.324. ana_1.wav0.3151
White noise0.004. ana_1.wav0.0007
Electronic music0.104. ana_1.wav0.0952
Synthesizer0.094. ana_1.wav0.0924
Chirp tone0.004. ana_1.wav0.0002
Dial tone0.004. ana_1.wav0.0003
Speech0.014. ana_1.wav0.0105
Beep, bleep0.004. ana_1.wav0.0009
Busy signal0.004. ana_1.wav0.0019
Top tag of each fileHow often does each category occur?
View data
Top tag
Sine wave
Sine wave
Static
Sound effect

Assumptions

  • Clip-level tags, not events — AudioSet tags say what is heard somewhere in each 10-second window, not when; scores are independent (several can be high).
  • Scores are not probabilities you can trust — Sigmoid outputs of a model trained on YouTube clips; compare them across files rather than reading them as chances.
  • Sounds like AudioSet — Shortest file 1.00 s.

Top 5 tags per file

pathSeconds10-s windowsTags (score)
media/aud3/tone_440.wav11Sine wave 0.71; Dial tone 0.07; Busy signal 0.04; Beep, bleep 0.02; Chirp tone 0.01
media/aud3/chirp.wav11Sine wave 0.29; Chirp tone 0.07; Beep, bleep 0.03; Sound effect 0.03; Music 0.02
media/aud3/noise.wav11Static 0.76; White noise 0.18; Speech 0.06; Music 0.03; Pink noise 0.02
media/aud3/ana_1.wav1.5001Sound effect 0.38; Music 0.32; Electronic music 0.10; Synthesizer 0.09; Techno 0.02

Most common tags (score ≥ 0.2)

TagFilesShare of filesMean score
Sine wave20.50000.2506
Static10.25000.1894
Sound effect10.25000.1043
Music10.25000.0909
White noise000.0455
Electronic music000.0246
Synthesizer000.0245
Chirp tone000.0214
Dial tone000.0192
Speech000.0186
Beep, bleep000.0138
Busy signal000.0117
Techno000.0064
Pink noise000.0059
Musical instrument000.0056
Noise000.0054
Boing000.0053
Sampler000.0042
Cacophony000.0041
Echo000.0037
Waterfall000.0032
Reverberation000.0031
Video game music000.0030
Spray000.0030
Ringtone000.0028
Inside, small room000.0023
Silence000.0023
Keyboard (musical)000.0021
Television000.0019
Vehicle000.0018
  • Audio Spectrogram Transformer (Gong, Chung & Glass 2021), MIT, fine-tuned on AudioSet; 16 kHz mono, 10.24-s windows, float64. A file's score for a tag is its largest window score.
The exact R script · R R version 4.5.1 (2025-06-13)
# Tag sounds (AudioSet)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.tag 1.0.0 · spec 9f28f0e5cc1f9da6
# Dataset: aud3_sounds (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_ast_* (Audio Spectrogram Transformer)

# %% Audio files listed in the path column
PATH <- "path"
TOP_K <- as.integer(5)
POOLING <- "max"  # max | mean over 10-second windows
THRESHOLD <- 0.2
DATA_DIR <- dirname(normalizePath("tests/parity/fixtures/aud3_sounds.parquet"))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/aud3_sounds.parquet", col_select = PATH))
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.tag/sounds-default/out-r", df,
                        "tests/parity/fixtures/aud3_sounds.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)
status <- cs_media_status(media, ifelse(is.na(paths), NA_character_, media_ids))
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 (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]]))

# %% AudioSet tags (AST, float64 on one thread: the Parity profile)
torch::torch_set_num_threads(1L)
model <- cs_ast_load(cs_ast_locate())
labels <- model$labels
progress <- cs_progress(sprintf("Tagging %d recordings", length(ok)), total = length(ok))
secs <- numeric(length(ok))
P <- matrix(0, nrow = length(ok), ncol = length(labels))
n_win <- integer(length(ok))
for (k in seq_along(ok)) {
  clip <- as.numeric(cs_media_audio(media, media_ids[ok[k]])[[1]])
  secs[k] <- length(clip) / 16000
  r <- cs_ast_run(model, list(clip), POOLING)
  P[k, ] <- r$probs[1, ]
  n_win[k] <- r$windows[1]
  cs_progress_update(progress, k)
}
cs_progress_done(progress)
tops <- cs_ast_top_k(P, labels, TOP_K)

# %% Artifact: the top tags of every file (long format)
out <- cs_ml_out_dir("target/academy-parity/run-8142/audio.tag/sounds-default/out-r")
long <- do.call(rbind, lapply(seq_along(ok), function(k) data.frame(
  row = as.integer(ok[k] - 1L), media_id = media_ids[ok[k]], path = paths[ok[k]], rank = seq_along(tops[[k]]),
  tag = vapply(tops[[k]], function(t) t$label, character(1)), score = vapply(tops[[k]], function(t) t$score, numeric(1)),
  stringsAsFactors = FALSE)))
nanoparquet::write_parquet(long, file.path(out, "tags.parquet"))

# %% Tag summary: files where the tag scores at least the threshold
n_files_tag <- colSums(P >= THRESHOLD)
mean_score <- colMeans(P)
ord <- order(-n_files_tag, -mean_score, seq_along(labels), method = "radix")
summary_rows <- lapply(head(ord, 30), function(j) list(tag = labels[j], files = as.integer(n_files_tag[j]),
                                                         share = n_files_tag[j] / length(ok), mean_score = mean_score[j]))
top1 <- vapply(tops, function(t) t[[1]]$label, character(1))
counts <- table(top1)
cn <- names(counts)
cv <- as.integer(counts)
top_tag <- cn[order(-cv, cn, method = "radix")][1]

# %% Assumptions
assumptions <- list(
  list(key = "weak_labels", label = "Clip-level tags, not events", status = "info",
       detail = "AudioSet tags say what is heard somewhere in each 10-second window, not when; scores are independent (several can be high)."),
  list(key = "calibration", label = "Scores are not probabilities you can trust", status = "info",
       detail = "Sigmoid outputs of a model trained on YouTube clips; compare them across files rather than reading them as chances."),
  list(key = "domain", label = "Sounds like AudioSet", status = if (min(secs) < 1) "warn" else "pass",
       detail = paste0(sprintf("Shortest file %.2f s", min(secs)), if (min(secs) < 1) "; very short clips are padded with silence and tag poorly." else "."))
)

# %% Result
values <- list(n_rows = nrow(df), n_files = length(ok) + length(unreadable), n_tagged = length(ok), n_unreadable = length(unreadable),
               n_no_path = n_no_path, audio_seconds = sum(secs), n_windows = sum(n_win), top_tag = top_tag,
               top_tag_files = as.integer(counts[[top_tag]]), n_distinct_top = length(cn), n_labels = length(labels), threshold = THRESHOLD,
               pooling = POOLING, top_k = TOP_K, mean_top_score = mean(vapply(tops, function(t) t[[1]]$score, numeric(1))))
file_rows <- lapply(seq_along(ok), function(k) list(file = paths[ok[k]], seconds = secs[k], windows = n_win[k],
  tags = paste(vapply(tops[[k]], function(t) sprintf("%s %.2f", t$label, t$score), character(1)), collapse = "; ")))
tables <- list(
  list(key = "files", title = sprintf("Top %d tags per file", TOP_K), columns = list(
    list(key = "file", label = PATH, type = "string"), list(key = "seconds", label = "Seconds", type = "number"),
    list(key = "windows", label = "10-s windows", type = "integer"), list(key = "tags", label = "Tags (score)", type = "string")),
    rows = head(file_rows, 500), note = if (length(file_rows) > 500) "First 500 files." else NULL),
  list(key = "tags", title = sprintf("Most common tags (score ≥ %s)", format(THRESHOLD)), columns = list(
    list(key = "tag", label = "Tag", type = "string"), list(key = "files", label = "Files", type = "integer"),
    list(key = "share", label = "Share of files", type = "number"), list(key = "mean_score", label = "Mean score", type = "number")),
    rows = summary_rows)
)
m <- min(length(ok), 40L)
cols_t <- labels[head(ord, 12)]
jt <- match(cols_t, labels)
lv <- sprintf("%d. %s", seq_len(m), basename(paths[ok[seq_len(m)]]))
ia <- rep(seq_len(m), each = length(cols_t))
it <- rep(seq_along(cols_t), times = m)
charts <- list(
  cs_chart("heatmap", "matrix-heatmap", paste0("Tag scores by file", if (length(ok) > 40) " — first 40 files" else ""), list(
    row = cs_col("File", lv[ia], "categorical", levels = lv),
    col = cs_col("Tag", cols_t[it], "categorical", levels = cols_t),
    value = cs_col("Score", P[cbind(ia, jt[it])]),
    label = cs_col("Score", sprintf("%.2f", P[cbind(ia, jt[it])]), "categorical")),
    controls = list(scale = "sequential")),
  cs_chart("top", "bar", "Top tag of each file", list(x = cs_col("Top tag", top1, "categorical")), controls = list(orientation = "horizontal"))
)
summary <- sprintf("%d recordings (%.1f s) were tagged with the 527 AudioSet classes; the most common top tag is “%s” (%d of %d files).",
                   length(ok), sum(secs), top_tag, as.integer(counts[[top_tag]]), length(ok))
cs_publish(list(
  method = "audio.tag",
  methodVersion = "1.0.0",
  title = "Sound tags",
  engine = cs_engine_info("torch", "nanoparquet"),
  n = length(ok),
  summary = summary,
  statistics = list(list(key = "n_tagged", label = "Files tagged", value = length(ok), format = "integer"),
                    list(key = "mean_top_score", label = "Mean top score", value = values$mean_top_score)),
  tables = tables,
  assumptions = assumptions,
  warnings = as.list(warnings),
  notes = list(sprintf(paste0("Audio Spectrogram Transformer (Gong, Chung & Glass 2021), MIT, fine-tuned on AudioSet; 16 kHz mono, 10.24-s windows, ",
                              "float64. A file's score for a tag is its %s window score."), if (POOLING == "max") "largest" else "mean")),
  charts = charts,
  artifacts = list(list(key = "tags", path = file.path(out, "tags.parquet"), format = "parquet")),
  values = values
))
Python

4 recordings (4.5 s) were tagged with the 527 AudioSet classes; the most common top tag is “Sine wave” (2 of 4 files).

Files tagged
4
Mean top score
0.5335

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

Assumptions

  • Clip-level tags, not events — AudioSet tags say what is heard somewhere in each 10-second window, not when; scores are independent (several can be high).
  • Scores are not probabilities you can trust — Sigmoid outputs of a model trained on YouTube clips; compare them across files rather than reading them as chances.
  • Sounds like AudioSet — Shortest file 1.00 s.

Top 5 tags per file

pathSeconds10-s windowsTags (score)
media/aud3/tone_440.wav11Sine wave 0.71; Dial tone 0.07; Busy signal 0.04; Beep, bleep 0.02; Chirp tone 0.01
media/aud3/chirp.wav11Sine wave 0.29; Chirp tone 0.07; Beep, bleep 0.03; Sound effect 0.03; Music 0.02
media/aud3/noise.wav11Static 0.76; White noise 0.18; Speech 0.06; Music 0.03; Pink noise 0.02
media/aud3/ana_1.wav1.5001Sound effect 0.38; Music 0.32; Electronic music 0.10; Synthesizer 0.09; Techno 0.02

Most common tags (score ≥ 0.2)

TagFilesShare of filesMean score
Sine wave20.50000.2506
Static10.25000.1894
Sound effect10.25000.1043
Music10.25000.0909
White noise000.0455
Electronic music000.0246
Synthesizer000.0245
Chirp tone000.0214
Dial tone000.0192
Speech000.0186
Beep, bleep000.0138
Busy signal000.0117
Techno000.0064
Pink noise000.0059
Musical instrument000.0056
Noise000.0054
Boing000.0053
Sampler000.0042
Cacophony000.0041
Echo000.0037
Waterfall000.0032
Reverberation000.0031
Video game music000.0030
Spray000.0030
Ringtone000.0028
Inside, small room000.0023
Silence000.0023
Keyboard (musical)000.0021
Television000.0019
Vehicle000.0018
  • Audio Spectrogram Transformer (Gong, Chung & Glass 2021), MIT, fine-tuned on AudioSet; 16 kHz mono, 10.24-s windows, float64. A file's score for a tag is its largest window score.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Tag sounds (AudioSet)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.tag 1.0.0 · spec 9f28f0e5cc1f9da6
# Dataset: aud3_sounds (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 ast  # Audio Spectrogram Transformer (twin: codesplashr cs_ast_*)

# %% Audio files listed in the path column
PATH = "path"
TOP_K = int(5)
POOLING = "max"  # max | mean over 10-second windows
THRESHOLD = 0.2
DATA_DIR = os.path.dirname(os.path.abspath("tests/parity/fixtures/aud3_sounds.parquet"))
df = pd.read_parquet("tests/parity/fixtures/aud3_sounds.parquet", columns=[PATH])
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.tag/sounds-default/out-python", df, "tests/parity/fixtures/aud3_sounds.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 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]]}).")

# %% AudioSet tags (AST, float64 on one thread: the Parity profile)
torch.set_num_threads(1)
model = ast.load(ast.locate())
labels = model["labels"]
progress = cs.progress(f"Tagging {len(ok)} recordings", total=len(ok))
secs, P, n_win = [], np.zeros((len(ok), len(labels))), np.zeros(len(ok), dtype=np.int64)
for k, i in enumerate(ok):
    clip = np.asarray(cs_media.audio(media, [media_ids[i]])[0], dtype=np.float64)
    secs.append(clip.size / 16000.0)
    r = ast.run(model, [clip], POOLING)
    P[k] = r["probs"][0]
    n_win[k] = int(r["windows"][0])
    progress.update(k + 1)
progress.done()
tops = ast.top_k(P, labels, TOP_K)

# %% Artifact: the top tags of every file (long format)
out = csml.out_dir("target/academy-parity/run-8142/audio.tag/sounds-default/out-python")
long = pd.DataFrame([{"row": i, "media_id": media_ids[i], "path": paths[i], "rank": r + 1, "tag": t, "score": s}
                     for k, i in enumerate(ok) for r, (t, s) in enumerate(tops[k])])
long["row"] = long["row"].astype(np.int64)
long["rank"] = long["rank"].astype(np.int64)
long.to_parquet(os.path.join(out, "tags.parquet"), index=False)

# %% Tag summary: files where the tag scores at least the threshold
present = P >= THRESHOLD
n_files_tag = present.sum(axis=0)
mean_score = P.mean(axis=0)
order = np.lexsort((np.arange(len(labels)), -mean_score, -n_files_tag))
summary_rows = [{"tag": labels[j], "files": int(n_files_tag[j]), "share": float(n_files_tag[j] / len(ok)), "mean_score": float(mean_score[j])}
                for j in order[:30]]
top1 = [t[0][0] for t in tops]
counts = {}
for t in top1:
    counts[t] = counts.get(t, 0) + 1
top_tag = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[0][0]

# %% Assumptions
assumptions = [
    {"key": "weak_labels", "label": "Clip-level tags, not events", "status": "info",
     "detail": "AudioSet tags say what is heard somewhere in each 10-second window, not when; scores are independent (several can be high)."},
    {"key": "calibration", "label": "Scores are not probabilities you can trust", "status": "info",
     "detail": "Sigmoid outputs of a model trained on YouTube clips; compare them across files rather than reading them as chances."},
    {"key": "domain", "label": "Sounds like AudioSet", "status": "warn" if min(secs) < 1.0 else "pass",
     "detail": f"Shortest file {min(secs):.2f} s" + ("; very short clips are padded with silence and tag poorly." if min(secs) < 1.0 else ".")},
]

# %% Result
values = {"n_rows": len(df), "n_files": len(ok) + len(unreadable), "n_tagged": len(ok), "n_unreadable": len(unreadable), "n_no_path": n_no_path,
          "audio_seconds": float(sum(secs)), "n_windows": int(n_win.sum()), "top_tag": top_tag, "top_tag_files": counts[top_tag],
          "n_distinct_top": len(counts), "n_labels": len(labels), "threshold": THRESHOLD, "pooling": POOLING, "top_k": TOP_K,
          "mean_top_score": float(np.mean([t[0][1] for t in tops]))}
file_rows = [{"file": paths[i], "seconds": secs[k], "windows": int(n_win[k]),
              "tags": "; ".join(f"{t} {s:.2f}" for t, s in tops[k])} for k, i in enumerate(ok)]
tables = [
    {"key": "files", "title": f"Top {TOP_K} tags per file", "columns": [
        {"key": "file", "label": PATH, "type": "string"}, {"key": "seconds", "label": "Seconds", "type": "number"},
        {"key": "windows", "label": "10-s windows", "type": "integer"}, {"key": "tags", "label": "Tags (score)", "type": "string"}],
     "rows": file_rows[:500], "note": "First 500 files." if len(file_rows) > 500 else None},
    {"key": "tags", "title": f"Most common tags (score ≥ {THRESHOLD:g})", "columns": [
        {"key": "tag", "label": "Tag", "type": "string"}, {"key": "files", "label": "Files", "type": "integer"},
        {"key": "share", "label": "Share of files", "type": "number"}, {"key": "mean_score", "label": "Mean score", "type": "number"}],
     "rows": summary_rows},
]
m = min(len(ok), 40)
cols_t = [labels[j] for j in order[:12]]
lv = [f"{k + 1}. {os.path.basename(paths[ok[k]])}" for k in range(m)]
charts = [
    cs.chart("heatmap", "matrix-heatmap", "Tag scores by file" + (" — first 40 files" if len(ok) > 40 else ""), {
        "row": cs.col("File", [lv[a] for a in range(m) for _ in cols_t], "categorical", levels=lv),
        "col": cs.col("Tag", [t for _ in range(m) for t in cols_t], "categorical", levels=cols_t),
        "value": cs.col("Score", [float(P[a, labels.index(t)]) for a in range(m) for t in cols_t]),
        "label": cs.col("Score", [f"{P[a, labels.index(t)]:.2f}" for a in range(m) for t in cols_t], "categorical")},
        controls={"scale": "sequential"}),
    cs.chart("top", "bar", "Top tag of each file", {"x": cs.col("Top tag", top1, "categorical")}, controls={"orientation": "horizontal"}),
]
summary = (f"{len(ok)} recordings ({sum(secs):.1f} s) were tagged with the 527 AudioSet classes; the most common top tag is "
           f"“{top_tag}” ({counts[top_tag]} of {len(ok)} files).")
cs.publish({
    "method": "audio.tag",
    "methodVersion": "1.0.0",
    "title": "Sound tags",
    "engine": cs.engine_info("numpy", "torch"),
    "n": len(ok),
    "summary": summary,
    "statistics": [{"key": "n_tagged", "label": "Files tagged", "value": len(ok), "format": "integer"},
                   {"key": "mean_top_score", "label": "Mean top score", "value": values["mean_top_score"]}],
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Audio Spectrogram Transformer (Gong, Chung & Glass 2021), MIT, fine-tuned on AudioSet; 16 kHz mono, 10.24-s windows, "
              f"float64. A file's score for a tag is its {'largest' if POOLING == 'max' else 'mean'} window score."],
    "charts": charts,
    "artifacts": [{"key": "tags", "path": os.path.join(out, "tags.parquet"), "format": "parquet"}],
    "values": values,
})

Each file's top tags come with scores between 0 and 1. The scores are independent: a file can score high on "Music" and "Speech" at once, and the scores of one file don't add up to 1. They come from a model trained on YouTube clips, so they are not probabilities you can trust as chances; compare them across files. The noise came out as "Static" and "White noise", and the synthetic vowel as a "Sound effect" or "Music": a formant synthesizer doesn't sound like a person to a model that has heard real voices.

Check yourself

A file scores 0.62 on "Speech" and 0.55 on "Music". What does that mean?

Show the answer

Answer: b

AudioSet is multi-label: each of the 527 classes gets its own sigmoid score, so a song with singing scores high on both.

04

Long recordings

Explore

The model hears about ten seconds at a time. A longer file is cut into windows, and a tag's file score is either its highest window score ("heard somewhere") or its mean ("how much of the file it covers"); that is the score over windowsTag score over windowsA long file is cut into 10-second windows; a tag's file score is its highest window score, or the mean.. A tag counts as present from a chosen score (thresholdTag present from scoreA tag counts as present in a file when its score reaches this, for the most-common-tags table.) in the most-common-tags table.

Sound tagsRecorded · Python and R agreeRecorded 2026-11-25 · 15 values compared
R

2 recordings (12.5 s) were tagged with the 527 AudioSet classes; the most common top tag is “Sine wave” (2 of 2 files).

Files tagged
2
Mean top score
0.6010

Plots

Tag scores by fileWhat do the values of a square or rectangular result matrix look like at a glance?
View data
TagScoreFileScore
Sine wave0.491. scene_tone_noise.wav0.4881
Dial tone0.021. scene_tone_noise.wav0.0238
Busy signal0.051. scene_tone_noise.wav0.0506
Static0.071. scene_tone_noise.wav0.0728
White noise0.051. scene_tone_noise.wav0.0485
Beep, bleep0.021. scene_tone_noise.wav0.0170
Chirp tone0.001. scene_tone_noise.wav0.0022
Speech0.011. scene_tone_noise.wav0.0065
Music0.011. scene_tone_noise.wav0.0056
Sound effect0.001. scene_tone_noise.wav0.0038
Television0.001. scene_tone_noise.wav0.0033
Burst, pop0.001. scene_tone_noise.wav0.0032
Sine wave0.712. tone_440.wav0.7139
Dial tone0.072. tone_440.wav0.0691
Busy signal0.042. tone_440.wav0.0420
Static0.002. tone_440.wav0.0001
White noise0.002. tone_440.wav0.0002
Beep, bleep0.022. tone_440.wav0.0218
Chirp tone0.012. tone_440.wav0.0115
Speech0.002. tone_440.wav0.0033
Music0.002. tone_440.wav0.0030
Sound effect0.002. tone_440.wav0.0029
Television0.002. tone_440.wav0.0005
Burst, pop0.002. tone_440.wav0.0004
Top tag of each fileHow often does each category occur?
View data
Top tag
Sine wave
Sine wave

Assumptions

  • Clip-level tags, not events — AudioSet tags say what is heard somewhere in each 10-second window, not when; scores are independent (several can be high).
  • Scores are not probabilities you can trust — Sigmoid outputs of a model trained on YouTube clips; compare them across files rather than reading them as chances.
  • Sounds like AudioSet — Shortest file 1.00 s.

Top 5 tags per file

pathSeconds10-s windowsTags (score)
media/aud3/scene_tone_noise.wav11.5002Sine wave 0.49; Static 0.07; Busy signal 0.05; White noise 0.05; Dial tone 0.02
media/aud3/tone_440.wav11Sine wave 0.71; Dial tone 0.07; Busy signal 0.04; Beep, bleep 0.02; Chirp tone 0.01

Most common tags (score ≥ 0.2)

TagFilesShare of filesMean score
Sine wave210.6010
Dial tone000.0465
Busy signal000.0463
Static000.0365
White noise000.0243
Beep, bleep000.0194
Chirp tone000.0069
Speech000.0049
Music000.0043
Sound effect000.0034
Television000.0019
Burst, pop000.0018
Silence000.0017
Tuning fork000.0015
Noise000.0011
Inside, small room000.0010
Cacophony000.0009
Singing bowl000.0008
Waterfall000.0008
Siren000.0007
Pink noise000.0007
Buzzer000.0007
Spray000.0007
Vehicle000.0006
Male speech, man speaking000.0006
Animal000.0005
Sidetone000.0005
Telephone000.0005
Radio000.0005
Outside, urban or manmade000.0004
  • Audio Spectrogram Transformer (Gong, Chung & Glass 2021), MIT, fine-tuned on AudioSet; 16 kHz mono, 10.24-s windows, float64. A file's score for a tag is its mean window score.
The exact R script · R R version 4.5.1 (2025-06-13)
# Tag sounds (AudioSet)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.tag 1.0.0 · spec c53e81f6513fb66b
# Dataset: aud3_scene (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_ast_* (Audio Spectrogram Transformer)

# %% Audio files listed in the path column
PATH <- "path"
TOP_K <- as.integer(5)
POOLING <- "mean"  # max | mean over 10-second windows
THRESHOLD <- 0.2
DATA_DIR <- dirname(normalizePath("tests/parity/fixtures/aud3_scene.parquet"))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/aud3_scene.parquet", col_select = PATH))
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.tag/scene-mean-window/out-r", df,
                        "tests/parity/fixtures/aud3_scene.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)
status <- cs_media_status(media, ifelse(is.na(paths), NA_character_, media_ids))
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 (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]]))

# %% AudioSet tags (AST, float64 on one thread: the Parity profile)
torch::torch_set_num_threads(1L)
model <- cs_ast_load(cs_ast_locate())
labels <- model$labels
progress <- cs_progress(sprintf("Tagging %d recordings", length(ok)), total = length(ok))
secs <- numeric(length(ok))
P <- matrix(0, nrow = length(ok), ncol = length(labels))
n_win <- integer(length(ok))
for (k in seq_along(ok)) {
  clip <- as.numeric(cs_media_audio(media, media_ids[ok[k]])[[1]])
  secs[k] <- length(clip) / 16000
  r <- cs_ast_run(model, list(clip), POOLING)
  P[k, ] <- r$probs[1, ]
  n_win[k] <- r$windows[1]
  cs_progress_update(progress, k)
}
cs_progress_done(progress)
tops <- cs_ast_top_k(P, labels, TOP_K)

# %% Artifact: the top tags of every file (long format)
out <- cs_ml_out_dir("target/academy-parity/run-8142/audio.tag/scene-mean-window/out-r")
long <- do.call(rbind, lapply(seq_along(ok), function(k) data.frame(
  row = as.integer(ok[k] - 1L), media_id = media_ids[ok[k]], path = paths[ok[k]], rank = seq_along(tops[[k]]),
  tag = vapply(tops[[k]], function(t) t$label, character(1)), score = vapply(tops[[k]], function(t) t$score, numeric(1)),
  stringsAsFactors = FALSE)))
nanoparquet::write_parquet(long, file.path(out, "tags.parquet"))

# %% Tag summary: files where the tag scores at least the threshold
n_files_tag <- colSums(P >= THRESHOLD)
mean_score <- colMeans(P)
ord <- order(-n_files_tag, -mean_score, seq_along(labels), method = "radix")
summary_rows <- lapply(head(ord, 30), function(j) list(tag = labels[j], files = as.integer(n_files_tag[j]),
                                                         share = n_files_tag[j] / length(ok), mean_score = mean_score[j]))
top1 <- vapply(tops, function(t) t[[1]]$label, character(1))
counts <- table(top1)
cn <- names(counts)
cv <- as.integer(counts)
top_tag <- cn[order(-cv, cn, method = "radix")][1]

# %% Assumptions
assumptions <- list(
  list(key = "weak_labels", label = "Clip-level tags, not events", status = "info",
       detail = "AudioSet tags say what is heard somewhere in each 10-second window, not when; scores are independent (several can be high)."),
  list(key = "calibration", label = "Scores are not probabilities you can trust", status = "info",
       detail = "Sigmoid outputs of a model trained on YouTube clips; compare them across files rather than reading them as chances."),
  list(key = "domain", label = "Sounds like AudioSet", status = if (min(secs) < 1) "warn" else "pass",
       detail = paste0(sprintf("Shortest file %.2f s", min(secs)), if (min(secs) < 1) "; very short clips are padded with silence and tag poorly." else "."))
)

# %% Result
values <- list(n_rows = nrow(df), n_files = length(ok) + length(unreadable), n_tagged = length(ok), n_unreadable = length(unreadable),
               n_no_path = n_no_path, audio_seconds = sum(secs), n_windows = sum(n_win), top_tag = top_tag,
               top_tag_files = as.integer(counts[[top_tag]]), n_distinct_top = length(cn), n_labels = length(labels), threshold = THRESHOLD,
               pooling = POOLING, top_k = TOP_K, mean_top_score = mean(vapply(tops, function(t) t[[1]]$score, numeric(1))))
file_rows <- lapply(seq_along(ok), function(k) list(file = paths[ok[k]], seconds = secs[k], windows = n_win[k],
  tags = paste(vapply(tops[[k]], function(t) sprintf("%s %.2f", t$label, t$score), character(1)), collapse = "; ")))
tables <- list(
  list(key = "files", title = sprintf("Top %d tags per file", TOP_K), columns = list(
    list(key = "file", label = PATH, type = "string"), list(key = "seconds", label = "Seconds", type = "number"),
    list(key = "windows", label = "10-s windows", type = "integer"), list(key = "tags", label = "Tags (score)", type = "string")),
    rows = head(file_rows, 500), note = if (length(file_rows) > 500) "First 500 files." else NULL),
  list(key = "tags", title = sprintf("Most common tags (score ≥ %s)", format(THRESHOLD)), columns = list(
    list(key = "tag", label = "Tag", type = "string"), list(key = "files", label = "Files", type = "integer"),
    list(key = "share", label = "Share of files", type = "number"), list(key = "mean_score", label = "Mean score", type = "number")),
    rows = summary_rows)
)
m <- min(length(ok), 40L)
cols_t <- labels[head(ord, 12)]
jt <- match(cols_t, labels)
lv <- sprintf("%d. %s", seq_len(m), basename(paths[ok[seq_len(m)]]))
ia <- rep(seq_len(m), each = length(cols_t))
it <- rep(seq_along(cols_t), times = m)
charts <- list(
  cs_chart("heatmap", "matrix-heatmap", paste0("Tag scores by file", if (length(ok) > 40) " — first 40 files" else ""), list(
    row = cs_col("File", lv[ia], "categorical", levels = lv),
    col = cs_col("Tag", cols_t[it], "categorical", levels = cols_t),
    value = cs_col("Score", P[cbind(ia, jt[it])]),
    label = cs_col("Score", sprintf("%.2f", P[cbind(ia, jt[it])]), "categorical")),
    controls = list(scale = "sequential")),
  cs_chart("top", "bar", "Top tag of each file", list(x = cs_col("Top tag", top1, "categorical")), controls = list(orientation = "horizontal"))
)
summary <- sprintf("%d recordings (%.1f s) were tagged with the 527 AudioSet classes; the most common top tag is “%s” (%d of %d files).",
                   length(ok), sum(secs), top_tag, as.integer(counts[[top_tag]]), length(ok))
cs_publish(list(
  method = "audio.tag",
  methodVersion = "1.0.0",
  title = "Sound tags",
  engine = cs_engine_info("torch", "nanoparquet"),
  n = length(ok),
  summary = summary,
  statistics = list(list(key = "n_tagged", label = "Files tagged", value = length(ok), format = "integer"),
                    list(key = "mean_top_score", label = "Mean top score", value = values$mean_top_score)),
  tables = tables,
  assumptions = assumptions,
  warnings = as.list(warnings),
  notes = list(sprintf(paste0("Audio Spectrogram Transformer (Gong, Chung & Glass 2021), MIT, fine-tuned on AudioSet; 16 kHz mono, 10.24-s windows, ",
                              "float64. A file's score for a tag is its %s window score."), if (POOLING == "max") "largest" else "mean")),
  charts = charts,
  artifacts = list(list(key = "tags", path = file.path(out, "tags.parquet"), format = "parquet")),
  values = values
))
Python

2 recordings (12.5 s) were tagged with the 527 AudioSet classes; the most common top tag is “Sine wave” (2 of 2 files).

Files tagged
2
Mean top score
0.6010

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

Assumptions

  • Clip-level tags, not events — AudioSet tags say what is heard somewhere in each 10-second window, not when; scores are independent (several can be high).
  • Scores are not probabilities you can trust — Sigmoid outputs of a model trained on YouTube clips; compare them across files rather than reading them as chances.
  • Sounds like AudioSet — Shortest file 1.00 s.

Top 5 tags per file

pathSeconds10-s windowsTags (score)
media/aud3/scene_tone_noise.wav11.5002Sine wave 0.49; Static 0.07; Busy signal 0.05; White noise 0.05; Dial tone 0.02
media/aud3/tone_440.wav11Sine wave 0.71; Dial tone 0.07; Busy signal 0.04; Beep, bleep 0.02; Chirp tone 0.01

Most common tags (score ≥ 0.2)

TagFilesShare of filesMean score
Sine wave210.6010
Dial tone000.0465
Busy signal000.0463
Static000.0365
White noise000.0243
Beep, bleep000.0194
Chirp tone000.0069
Speech000.0049
Music000.0043
Sound effect000.0034
Television000.0019
Burst, pop000.0018
Silence000.0017
Tuning fork000.0015
Noise000.0011
Inside, small room000.0010
Cacophony000.0009
Singing bowl000.0008
Waterfall000.0008
Siren000.0007
Pink noise000.0007
Buzzer000.0007
Spray000.0007
Vehicle000.0006
Male speech, man speaking000.0006
Animal000.0005
Sidetone000.0005
Telephone000.0005
Radio000.0005
Outside, urban or manmade000.0004
  • Audio Spectrogram Transformer (Gong, Chung & Glass 2021), MIT, fine-tuned on AudioSet; 16 kHz mono, 10.24-s windows, float64. A file's score for a tag is its mean window score.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Tag sounds (AudioSet)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.tag 1.0.0 · spec c53e81f6513fb66b
# Dataset: aud3_scene (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 ast  # Audio Spectrogram Transformer (twin: codesplashr cs_ast_*)

# %% Audio files listed in the path column
PATH = "path"
TOP_K = int(5)
POOLING = "mean"  # max | mean over 10-second windows
THRESHOLD = 0.2
DATA_DIR = os.path.dirname(os.path.abspath("tests/parity/fixtures/aud3_scene.parquet"))
df = pd.read_parquet("tests/parity/fixtures/aud3_scene.parquet", columns=[PATH])
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.tag/scene-mean-window/out-python", df, "tests/parity/fixtures/aud3_scene.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 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]]}).")

# %% AudioSet tags (AST, float64 on one thread: the Parity profile)
torch.set_num_threads(1)
model = ast.load(ast.locate())
labels = model["labels"]
progress = cs.progress(f"Tagging {len(ok)} recordings", total=len(ok))
secs, P, n_win = [], np.zeros((len(ok), len(labels))), np.zeros(len(ok), dtype=np.int64)
for k, i in enumerate(ok):
    clip = np.asarray(cs_media.audio(media, [media_ids[i]])[0], dtype=np.float64)
    secs.append(clip.size / 16000.0)
    r = ast.run(model, [clip], POOLING)
    P[k] = r["probs"][0]
    n_win[k] = int(r["windows"][0])
    progress.update(k + 1)
progress.done()
tops = ast.top_k(P, labels, TOP_K)

# %% Artifact: the top tags of every file (long format)
out = csml.out_dir("target/academy-parity/run-8142/audio.tag/scene-mean-window/out-python")
long = pd.DataFrame([{"row": i, "media_id": media_ids[i], "path": paths[i], "rank": r + 1, "tag": t, "score": s}
                     for k, i in enumerate(ok) for r, (t, s) in enumerate(tops[k])])
long["row"] = long["row"].astype(np.int64)
long["rank"] = long["rank"].astype(np.int64)
long.to_parquet(os.path.join(out, "tags.parquet"), index=False)

# %% Tag summary: files where the tag scores at least the threshold
present = P >= THRESHOLD
n_files_tag = present.sum(axis=0)
mean_score = P.mean(axis=0)
order = np.lexsort((np.arange(len(labels)), -mean_score, -n_files_tag))
summary_rows = [{"tag": labels[j], "files": int(n_files_tag[j]), "share": float(n_files_tag[j] / len(ok)), "mean_score": float(mean_score[j])}
                for j in order[:30]]
top1 = [t[0][0] for t in tops]
counts = {}
for t in top1:
    counts[t] = counts.get(t, 0) + 1
top_tag = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[0][0]

# %% Assumptions
assumptions = [
    {"key": "weak_labels", "label": "Clip-level tags, not events", "status": "info",
     "detail": "AudioSet tags say what is heard somewhere in each 10-second window, not when; scores are independent (several can be high)."},
    {"key": "calibration", "label": "Scores are not probabilities you can trust", "status": "info",
     "detail": "Sigmoid outputs of a model trained on YouTube clips; compare them across files rather than reading them as chances."},
    {"key": "domain", "label": "Sounds like AudioSet", "status": "warn" if min(secs) < 1.0 else "pass",
     "detail": f"Shortest file {min(secs):.2f} s" + ("; very short clips are padded with silence and tag poorly." if min(secs) < 1.0 else ".")},
]

# %% Result
values = {"n_rows": len(df), "n_files": len(ok) + len(unreadable), "n_tagged": len(ok), "n_unreadable": len(unreadable), "n_no_path": n_no_path,
          "audio_seconds": float(sum(secs)), "n_windows": int(n_win.sum()), "top_tag": top_tag, "top_tag_files": counts[top_tag],
          "n_distinct_top": len(counts), "n_labels": len(labels), "threshold": THRESHOLD, "pooling": POOLING, "top_k": TOP_K,
          "mean_top_score": float(np.mean([t[0][1] for t in tops]))}
file_rows = [{"file": paths[i], "seconds": secs[k], "windows": int(n_win[k]),
              "tags": "; ".join(f"{t} {s:.2f}" for t, s in tops[k])} for k, i in enumerate(ok)]
tables = [
    {"key": "files", "title": f"Top {TOP_K} tags per file", "columns": [
        {"key": "file", "label": PATH, "type": "string"}, {"key": "seconds", "label": "Seconds", "type": "number"},
        {"key": "windows", "label": "10-s windows", "type": "integer"}, {"key": "tags", "label": "Tags (score)", "type": "string"}],
     "rows": file_rows[:500], "note": "First 500 files." if len(file_rows) > 500 else None},
    {"key": "tags", "title": f"Most common tags (score ≥ {THRESHOLD:g})", "columns": [
        {"key": "tag", "label": "Tag", "type": "string"}, {"key": "files", "label": "Files", "type": "integer"},
        {"key": "share", "label": "Share of files", "type": "number"}, {"key": "mean_score", "label": "Mean score", "type": "number"}],
     "rows": summary_rows},
]
m = min(len(ok), 40)
cols_t = [labels[j] for j in order[:12]]
lv = [f"{k + 1}. {os.path.basename(paths[ok[k]])}" for k in range(m)]
charts = [
    cs.chart("heatmap", "matrix-heatmap", "Tag scores by file" + (" — first 40 files" if len(ok) > 40 else ""), {
        "row": cs.col("File", [lv[a] for a in range(m) for _ in cols_t], "categorical", levels=lv),
        "col": cs.col("Tag", [t for _ in range(m) for t in cols_t], "categorical", levels=cols_t),
        "value": cs.col("Score", [float(P[a, labels.index(t)]) for a in range(m) for t in cols_t]),
        "label": cs.col("Score", [f"{P[a, labels.index(t)]:.2f}" for a in range(m) for t in cols_t], "categorical")},
        controls={"scale": "sequential"}),
    cs.chart("top", "bar", "Top tag of each file", {"x": cs.col("Top tag", top1, "categorical")}, controls={"orientation": "horizontal"}),
]
summary = (f"{len(ok)} recordings ({sum(secs):.1f} s) were tagged with the 527 AudioSet classes; the most common top tag is "
           f"“{top_tag}” ({counts[top_tag]} of {len(ok)} files).")
cs.publish({
    "method": "audio.tag",
    "methodVersion": "1.0.0",
    "title": "Sound tags",
    "engine": cs.engine_info("numpy", "torch"),
    "n": len(ok),
    "summary": summary,
    "statistics": [{"key": "n_tagged", "label": "Files tagged", "value": len(ok), "format": "integer"},
                   {"key": "mean_top_score", "label": "Mean top score", "value": values["mean_top_score"]}],
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Audio Spectrogram Transformer (Gong, Chung & Glass 2021), MIT, fine-tuned on AudioSet; 16 kHz mono, 10.24-s windows, "
              f"float64. A file's score for a tag is its {'largest' if POOLING == 'max' else 'mean'} window score."],
    "charts": charts,
    "artifacts": [{"key": "tags", "path": os.path.join(out, "tags.parquet"), "format": "parquet"}],
    "values": values,
})

The four files above are one window each, so both scores agree there. Here a tone runs past ten seconds, with a burst of noise in its short second window. With the highest window the two files' top scores average 0.79; with the mean they average 0.60, because the short second window scores low and pulls the mean down.

Check yourself

You want to find hour-long recordings in which a dog barks at least once. Which score over windows fits?

Show the answer

Answer: a

The mean would dilute one bark across 360 windows of silence; the highest window keeps it.

05

Recordings that sound alike

Checkpoint
Sound embeddingsRecorded · Python and R agreeRecorded 2026-11-25 · 12 values compared
R

6 recordings were turned into 768-value sound embeddings; the first two principal components keep 74% of their variance, and each file's closest neighbor has mean cosine similarity 0.90. The closest file has the same speaker 100% of the time.

Embedding size
768
Mean similarity to the closest file
0.8979
Closest file has the same label
100.0%

Plots

Recordings by sound (first two principal components of the embeddings)How do two numeric variables move together?
View data
speakerPC 1PC 2
ana−10.551−2.770
ana−11.446−10.405
ben11.632−3.508
ben13.268−3.942
cal−4.94513.927
cal2.0416.698

Assumptions

  • Frozen model — The encoder isn't trained on your recordings; the embedding reflects what the model learned from AudioSet's YouTube clips.
  • Two axes hide distance — The map keeps 74% of the embeddings' variance; nearest neighbors use every dimension.

Recordings on the map

pathSecondsPC 1PC 2Closest 1 (cosine)speaker
media/aud3/ana_1.wav1−10.551−2.770ana_2.wav 0.86ana
media/aud3/ana_2.wav1−11.446−10.405ana_1.wav 0.86ana
media/aud3/ben_1.wav111.632−3.508ben_2.wav 0.95ben
media/aud3/ben_2.wav113.268−3.942ben_1.wav 0.95ben
media/aud3/cal_1.wav1−4.94513.927cal_2.wav 0.89cal
media/aud3/cal_2.wav12.0416.698cal_1.wav 0.89cal
  • Audio Spectrogram Transformer (Gong, Chung & Glass 2021), MIT, fine-tuned on AudioSet: the mean of the class and distillation token outputs, averaged over 10.24-s windows; float64. Map: principal components of the centered embeddings, each axis signed so its largest coordinate is positive. Save the embeddings as columns with Add features from a pretrained model.
The exact R script · R R version 4.5.1 (2025-06-13)
# Map recordings by sound (audio embeddings)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.embed 1.0.0 · spec b323d9fb7a836e1f
# 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_ast_* (Audio Spectrogram Transformer), cs_ast_pca_map, cs_ast_neighbors

# %% Audio files listed in the path column
PATH <- "path"
LABEL <- "speaker"
K <- as.integer(1)
DATA_DIR <- dirname(normalizePath("tests/parity/fixtures/aud3_voices.parquet"))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/aud3_voices.parquet", col_select = if (is.null(LABEL)) PATH else c(PATH, LABEL)))
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\":1,\"mono\":true,\"offset_seconds\":0,\"sample_rate\":16000}}", simplifyVector = FALSE), "target/academy-parity/run-8142/audio.embed/voices-map-k1/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)
status <- cs_media_status(media, ifelse(is.na(paths), NA_character_, media_ids))
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) < 3) cs_error("CS_E_TOO_FEW_ROWS", what = "A map of recordings", min = 3, 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]]))

# %% Clip embeddings (AST, float64 on one thread: the Parity profile)
torch::torch_set_num_threads(1L)
model <- cs_ast_load(cs_ast_locate())
progress <- cs_progress(sprintf("Embedding %d recordings", length(ok)), total = length(ok))
secs <- numeric(length(ok))
E <- matrix(0, nrow = length(ok), ncol = as.integer(model$config$hidden_size))
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_ast_run(model, list(clip))$embeddings[1, ]
  cs_progress_update(progress, k)
}
cs_progress_done(progress)

# %% Map (first two principal components) and nearest neighbors by cosine similarity
pca <- cs_ast_pca_map(E)
U <- E / sqrt(rowSums(E * E))
S <- U %*% t(U)
names_ <- basename(paths[ok])
k_eff <- min(K, length(ok) - 1L)
nbrs <- cs_ast_neighbors(S, k_eff)
lab <- NULL
nn_acc <- NULL
if (!is.null(LABEL)) {
  lab <- as.character(df[[LABEL]])[ok]
  hits <- 0L
  n_id <- 0L
  for (a in seq_along(ok)) {
    if (is.na(lab[a])) next
    row <- vapply(seq_along(ok), function(b) if (b != a && !is.na(lab[b])) S[a, b] else -Inf, numeric(1))
    if (!any(is.finite(row))) next
    b <- which.max(row)
    hits <- hits + as.integer(lab[b] == lab[a])
    n_id <- n_id + 1L
  }
  nn_acc <- if (n_id > 0) hits / n_id else NULL
}

# %% Artifact: one row per file with its embedding
out <- cs_ml_out_dir("target/academy-parity/run-8142/audio.embed/voices-map-k1/out-r")
art <- data.frame(row = as.integer(ok - 1L), media_id = media_ids[ok], path = paths[ok], pc1 = pca$coords[, 1], pc2 = pca$coords[, 2],
                  stringsAsFactors = FALSE)
for (d in seq_len(ncol(E))) art[[sprintf("emb_%d", d)]] <- E[, d]
nanoparquet::write_parquet(art, file.path(out, "embeddings.parquet"))

# %% Assumptions
assumptions <- list(
  list(key = "frozen", label = "Frozen model", status = "info",
       detail = "The encoder isn't trained on your recordings; the embedding reflects what the model learned from AudioSet's YouTube clips."),
  list(key = "map_distortion", label = "Two axes hide distance", status = "info",
       detail = sprintf("The map keeps %.0f%% of the embeddings' variance; nearest neighbors use every dimension.", 100 * (pca$share[1] + pca$share[2])))
)

# %% 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), pc1_share = pca$share[1], pc2_share = pca$share[2],
               k_neighbors = k_eff, mean_nn_similarity = mean(vapply(nbrs, function(nb) nb$similarity[1], numeric(1))), nn_label_accuracy = nn_acc)
rows <- lapply(seq_along(ok), function(k) {
  r <- list(file = paths[ok[k]], seconds = secs[k], pc1 = pca$coords[k, 1], pc2 = pca$coords[k, 2],
            neighbors = paste(sprintf("%s %.2f", names_[nbrs[[k]]$index], nbrs[[k]]$similarity), collapse = "; "))
  if (!is.null(lab)) r$label <- lab[k]
  r
})
cols <- list(list(key = "file", label = PATH, type = "string"), list(key = "seconds", label = "Seconds", type = "number"),
             list(key = "pc1", label = "PC 1", type = "number"), list(key = "pc2", label = "PC 2", type = "number"),
             list(key = "neighbors", label = sprintf("Closest %d (cosine)", k_eff), type = "string"))
if (!is.null(lab)) cols[[length(cols) + 1L]] <- list(key = "label", label = LABEL, type = "string")
tables <- list(list(key = "files", title = "Recordings on the map", columns = cols, rows = head(rows, 500),
                    note = if (length(rows) > 500) "First 500 files." else NULL))
roles_map <- list(x = cs_col("PC 1", pca$coords[, 1]), y = cs_col("PC 2", pca$coords[, 2]))
if (!is.null(lab)) {
  lv <- sort(unique(lab[!is.na(lab)]), method = "radix")
  if (length(lv) <= 8) roles_map$color <- cs_col(LABEL, lab, "categorical", levels = lv)
}
charts <- list(cs_chart("map", "scatter", "Recordings by sound (first two principal components of the embeddings)", roles_map, controls = list(fit = "none")))
summary <- sprintf(paste0("%d recordings were turned into %d-value sound embeddings; the first two principal components keep %.0f%% of their variance, ",
                          "and each file's closest neighbor has mean cosine similarity %.2f."),
                   length(ok), ncol(E), 100 * (pca$share[1] + pca$share[2]), values$mean_nn_similarity)
if (!is.null(nn_acc)) summary <- paste(summary, sprintf("The closest file has the same %s %.0f%% of the time.", LABEL, 100 * nn_acc))
statistics <- list(list(key = "dim", label = "Embedding size", value = ncol(E), format = "integer"),
                   list(key = "mean_nn_similarity", label = "Mean similarity to the closest file", value = values$mean_nn_similarity))
if (!is.null(nn_acc)) statistics[[length(statistics) + 1L]] <- list(key = "nn_label_accuracy", label = "Closest file has the same label", value = nn_acc, format = "percent")
cs_publish(list(
  method = "audio.embed",
  methodVersion = "1.0.0",
  title = "Sound embeddings",
  engine = cs_engine_info("torch", "nanoparquet"),
  n = length(ok),
  summary = summary,
  statistics = statistics,
  tables = tables,
  assumptions = assumptions,
  warnings = as.list(warnings),
  notes = list(paste0("Audio Spectrogram Transformer (Gong, Chung & Glass 2021), MIT, fine-tuned on AudioSet: the mean of the class and distillation ",
                      "token outputs, averaged over 10.24-s windows; float64. Map: principal components of the centered embeddings, each axis signed ",
                      "so its largest coordinate is positive. Save the embeddings as columns with Add features from a pretrained model.")),
  charts = charts,
  artifacts = list(list(key = "embeddings", path = file.path(out, "embeddings.parquet"), format = "parquet")),
  values = values
))
Python

6 recordings were turned into 768-value sound embeddings; the first two principal components keep 74% of their variance, and each file's closest neighbor has mean cosine similarity 0.90. The closest file has the same speaker 100% of the time.

Embedding size
768
Mean similarity to the closest file
0.8979
Closest file has the same label
100.0%

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

Assumptions

  • Frozen model — The encoder isn't trained on your recordings; the embedding reflects what the model learned from AudioSet's YouTube clips.
  • Two axes hide distance — The map keeps 74% of the embeddings' variance; nearest neighbors use every dimension.

Recordings on the map

pathSecondsPC 1PC 2Closest 1 (cosine)speaker
media/aud3/ana_1.wav1−10.551−2.770ana_2.wav 0.86ana
media/aud3/ana_2.wav1−11.446−10.405ana_1.wav 0.86ana
media/aud3/ben_1.wav111.632−3.508ben_2.wav 0.95ben
media/aud3/ben_2.wav113.268−3.942ben_1.wav 0.95ben
media/aud3/cal_1.wav1−4.94513.927cal_2.wav 0.89cal
media/aud3/cal_2.wav12.0416.698cal_1.wav 0.89cal
  • Audio Spectrogram Transformer (Gong, Chung & Glass 2021), MIT, fine-tuned on AudioSet: the mean of the class and distillation token outputs, averaged over 10.24-s windows; float64. Map: principal components of the centered embeddings, each axis signed so its largest coordinate is positive. Save the embeddings as columns with Add features from a pretrained model.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Map recordings by sound (audio embeddings)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method audio.embed 1.0.0 · spec b323d9fb7a836e1f
# 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 ast  # Audio Spectrogram Transformer (twin: codesplashr cs_ast_*)

# %% Audio files listed in the path column
PATH = "path"
LABEL = "speaker"
K = int(1)
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 LABEL is None else [PATH, LABEL])
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\":1,\"mono\":true,\"offset_seconds\":0,\"sample_rate\":16000}}"), "target/academy-parity/run-8142/audio.embed/voices-map-k1/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) < 3:
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="A map of recordings", min=3, 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]]}).")

# %% Clip embeddings (AST, float64 on one thread: the Parity profile)
torch.set_num_threads(1)
model = ast.load(ast.locate())
progress = cs.progress(f"Embedding {len(ok)} recordings", total=len(ok))
secs, E = [], np.zeros((len(ok), int(model["config"]["hidden_size"])))
for k, i in enumerate(ok):
    clip = np.asarray(cs_media.audio(media, [media_ids[i]])[0], dtype=np.float64)
    secs.append(clip.size / 16000.0)
    E[k] = ast.run(model, [clip])["embeddings"][0]
    progress.update(k + 1)
progress.done()

# %% Map (first two principal components) and nearest neighbors by cosine similarity
pca = ast.pca_map(E)
U = E / np.sqrt(np.sum(E * E, axis=1))[:, None]
S = U @ U.T
names = [os.path.basename(paths[i]) for i in ok]
k_eff = min(K, len(ok) - 1)
nbrs = ast.neighbors(S, k_eff)
lab = None
nn_acc = None
if LABEL is not None:
    lab = [None if pd.isna(v) else str(v) for v in (df[LABEL].tolist()[i] for i in ok)]  # None, NaN, pd.NA: unlabeled
    hits, n_id = 0, 0
    for a in range(len(ok)):
        if lab[a] is None:
            continue
        cand = [(b, S[a, b]) for b in range(len(ok)) if b != a and lab[b] is not None]
        if not cand:
            continue
        b = max(cand, key=lambda t: (t[1], -t[0]))[0]
        hits += int(lab[b] == lab[a])
        n_id += 1
    nn_acc = hits / n_id if n_id else None

# %% Artifact: one row per file with its embedding
out = csml.out_dir("target/academy-parity/run-8142/audio.embed/voices-map-k1/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],
                    "pc1": pca["coords"][:, 0], "pc2": pca["coords"][:, 1]})
for d in range(E.shape[1]):
    art[f"emb_{d + 1}"] = E[:, d]
art.to_parquet(os.path.join(out, "embeddings.parquet"), index=False)

# %% Assumptions
assumptions = [
    {"key": "frozen", "label": "Frozen model", "status": "info",
     "detail": "The encoder isn't trained on your recordings; the embedding reflects what the model learned from AudioSet's YouTube clips."},
    {"key": "map_distortion", "label": "Two axes hide distance", "status": "info",
     "detail": f"The map keeps {100 * (pca['share'][0] + pca['share'][1]):.0f}% of the embeddings' variance; nearest neighbors use every dimension."},
]

# %% Result
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(secs)), "dim": int(E.shape[1]), "pc1_share": float(pca["share"][0]), "pc2_share": float(pca["share"][1]),
          "k_neighbors": k_eff, "mean_nn_similarity": float(np.mean([nb[0][1] for nb in nbrs])), "nn_label_accuracy": nn_acc}
rows = []
for k, i in enumerate(ok):
    r = {"file": paths[i], "seconds": secs[k], "pc1": float(pca["coords"][k, 0]), "pc2": float(pca["coords"][k, 1]),
         "neighbors": "; ".join(f"{names[b]} {s:.2f}" for b, s in nbrs[k])}
    if lab is not None:
        r["label"] = lab[k]
    rows.append(r)
cols = [{"key": "file", "label": PATH, "type": "string"}, {"key": "seconds", "label": "Seconds", "type": "number"},
        {"key": "pc1", "label": "PC 1", "type": "number"}, {"key": "pc2", "label": "PC 2", "type": "number"},
        {"key": "neighbors", "label": f"Closest {k_eff} (cosine)", "type": "string"}]
if lab is not None:
    cols.append({"key": "label", "label": LABEL, "type": "string"})
tables = [{"key": "files", "title": "Recordings on the map", "columns": cols, "rows": rows[:500], "note": "First 500 files." if len(rows) > 500 else None}]
roles_map = {"x": cs.col("PC 1", pca["coords"][:, 0].tolist()), "y": cs.col("PC 2", pca["coords"][:, 1].tolist())}
if lab is not None:
    levels = sorted({v for v in lab if v is not None})
    if len(levels) <= 8:
        roles_map["color"] = cs.col(LABEL, [v if v is not None else None for v in lab], "categorical", levels=levels)
charts = [cs.chart("map", "scatter", "Recordings by sound (first two principal components of the embeddings)", roles_map, controls={"fit": "none"})]
summary = (f"{len(ok)} recordings were turned into {E.shape[1]}-value sound embeddings; the first two principal components keep "
           f"{100 * (pca['share'][0] + pca['share'][1]):.0f}% of their variance, and each file's closest neighbor has mean cosine similarity "
           f"{values['mean_nn_similarity']:.2f}.")
if nn_acc is not None:
    summary += f" The closest file has the same {LABEL} {100 * nn_acc:.0f}% of the time."
cs.publish({
    "method": "audio.embed",
    "methodVersion": "1.0.0",
    "title": "Sound embeddings",
    "engine": cs.engine_info("numpy", "torch"),
    "n": len(ok),
    "summary": summary,
    "statistics": [{"key": "dim", "label": "Embedding size", "value": int(E.shape[1]), "format": "integer"},
                   {"key": "mean_nn_similarity", "label": "Mean similarity to the closest file", "value": values["mean_nn_similarity"]}]
                  + ([{"key": "nn_label_accuracy", "label": "Closest file has the same label", "value": nn_acc, "format": "percent"}] if nn_acc is not None else []),
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": ["Audio Spectrogram Transformer (Gong, Chung & Glass 2021), MIT, fine-tuned on AudioSet: the mean of the class and distillation "
              "token outputs, averaged over 10.24-s windows; float64. Map: principal components of the centered embeddings, each axis signed "
              "so its largest coordinate is positive. Save the embeddings as columns with Add features from a pretrained model."],
    "charts": charts,
    "artifacts": [{"key": "embeddings", "path": os.path.join(out, "embeddings.parquet"), "format": "parquet"}],
    "values": values,
})

The same model also gives each recording a 768-value embedding. Sound embeddingsSound embedding mapEach recording's 768-value AST embedding, drawn on its first two principal components, with its closest neighbors. place recordings that sound alike close together; the map shows the first two principal components, and each file's closest neighbors use every dimension. Here six clips of three synthetic voices were mapped; the closest file had the same voice 100.0% of the time (closest-file accuracyClosest-file accuracyHow often a file's most similar other file has the same known speaker or label.). Three very different synthetic voices are easy; AudioSet embeddings are trained to say what kind of sound a file is, not who is speaking, so for real voices use speaker embeddings.

Check yourself

Two recordings sit far apart on the map, yet each lists the other as its closest neighbor. How can that be?

Show the answer

Answer: b

Check how much variance the two axes keep (the map's caption says it) before reading distances off the picture.

06

Do it on your own data

In the app

Add an audio folder in Data (the files stay where they are), then open Tag sounds (AudioSet) or Map recordings by sound. The model is a one-time 346 MB download that asks first. To use the embeddings in clustering or a learner, add them as columns with Add features from a pretrained model and the AST encoder.

Python
from codesplash.audio import ast

model = ast.load(ast.locate())
out = ast.run(model, [samples_16k])                  # float samples at 16 kHz, mono
print(ast.top_k(out["probs"], model["labels"], 5)[0])
R
library(codesplashr)
model <- cs_ast_load(cs_ast_locate())
out <- cs_ast_run(model, list(samples_16k))
cs_ast_top_k(out$probs, model$labels, 5)[[1]]

Concepts in this lesson