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.
What runs in CodeSplash
- Tag sounds (AudioSet) Experimental
- Map recordings by sound (audio embeddings) Experimental
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
Recordings as data
ReadA 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.
Make a guess
PredictPredict first
What will the tagger name first for the steady 440 Hz tone?
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.
Long recordings
ExploreThe 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.
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
View data
| Tag | Score | File | Score |
|---|---|---|---|
| Sine wave | 0.49 | 1. scene_tone_noise.wav | 0.4881 |
| Dial tone | 0.02 | 1. scene_tone_noise.wav | 0.0238 |
| Busy signal | 0.05 | 1. scene_tone_noise.wav | 0.0506 |
| Static | 0.07 | 1. scene_tone_noise.wav | 0.0728 |
| White noise | 0.05 | 1. scene_tone_noise.wav | 0.0485 |
| Beep, bleep | 0.02 | 1. scene_tone_noise.wav | 0.0170 |
| Chirp tone | 0.00 | 1. scene_tone_noise.wav | 0.0022 |
| Speech | 0.01 | 1. scene_tone_noise.wav | 0.0065 |
| Music | 0.01 | 1. scene_tone_noise.wav | 0.0056 |
| Sound effect | 0.00 | 1. scene_tone_noise.wav | 0.0038 |
| Television | 0.00 | 1. scene_tone_noise.wav | 0.0033 |
| Burst, pop | 0.00 | 1. scene_tone_noise.wav | 0.0032 |
| Sine wave | 0.71 | 2. tone_440.wav | 0.7139 |
| Dial tone | 0.07 | 2. tone_440.wav | 0.0691 |
| Busy signal | 0.04 | 2. tone_440.wav | 0.0420 |
| Static | 0.00 | 2. tone_440.wav | 0.0001 |
| White noise | 0.00 | 2. tone_440.wav | 0.0002 |
| Beep, bleep | 0.02 | 2. tone_440.wav | 0.0218 |
| Chirp tone | 0.01 | 2. tone_440.wav | 0.0115 |
| Speech | 0.00 | 2. tone_440.wav | 0.0033 |
| Music | 0.00 | 2. tone_440.wav | 0.0030 |
| Sound effect | 0.00 | 2. tone_440.wav | 0.0029 |
| Television | 0.00 | 2. tone_440.wav | 0.0005 |
| Burst, pop | 0.00 | 2. tone_440.wav | 0.0004 |
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
| path | Seconds | 10-s windows | Tags (score) |
|---|---|---|---|
| media/aud3/scene_tone_noise.wav | 11.500 | 2 | Sine wave 0.49; Static 0.07; Busy signal 0.05; White noise 0.05; Dial tone 0.02 |
| media/aud3/tone_440.wav | 1 | 1 | Sine 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)
| Tag | Files | Share of files | Mean score |
|---|---|---|---|
| Sine wave | 2 | 1 | 0.6010 |
| Dial tone | 0 | 0 | 0.0465 |
| Busy signal | 0 | 0 | 0.0463 |
| Static | 0 | 0 | 0.0365 |
| White noise | 0 | 0 | 0.0243 |
| Beep, bleep | 0 | 0 | 0.0194 |
| Chirp tone | 0 | 0 | 0.0069 |
| Speech | 0 | 0 | 0.0049 |
| Music | 0 | 0 | 0.0043 |
| Sound effect | 0 | 0 | 0.0034 |
| Television | 0 | 0 | 0.0019 |
| Burst, pop | 0 | 0 | 0.0018 |
| Silence | 0 | 0 | 0.0017 |
| Tuning fork | 0 | 0 | 0.0015 |
| Noise | 0 | 0 | 0.0011 |
| Inside, small room | 0 | 0 | 0.0010 |
| Cacophony | 0 | 0 | 0.0009 |
| Singing bowl | 0 | 0 | 0.0008 |
| Waterfall | 0 | 0 | 0.0008 |
| Siren | 0 | 0 | 0.0007 |
| Pink noise | 0 | 0 | 0.0007 |
| Buzzer | 0 | 0 | 0.0007 |
| Spray | 0 | 0 | 0.0007 |
| Vehicle | 0 | 0 | 0.0006 |
| Male speech, man speaking | 0 | 0 | 0.0006 |
| Animal | 0 | 0 | 0.0005 |
| Sidetone | 0 | 0 | 0.0005 |
| Telephone | 0 | 0 | 0.0005 |
| Radio | 0 | 0 | 0.0005 |
| Outside, urban or manmade | 0 | 0 | 0.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
))
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
| path | Seconds | 10-s windows | Tags (score) |
|---|---|---|---|
| media/aud3/scene_tone_noise.wav | 11.500 | 2 | Sine wave 0.49; Static 0.07; Busy signal 0.05; White noise 0.05; Dial tone 0.02 |
| media/aud3/tone_440.wav | 1 | 1 | Sine 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)
| Tag | Files | Share of files | Mean score |
|---|---|---|---|
| Sine wave | 2 | 1 | 0.6010 |
| Dial tone | 0 | 0 | 0.0465 |
| Busy signal | 0 | 0 | 0.0463 |
| Static | 0 | 0 | 0.0365 |
| White noise | 0 | 0 | 0.0243 |
| Beep, bleep | 0 | 0 | 0.0194 |
| Chirp tone | 0 | 0 | 0.0069 |
| Speech | 0 | 0 | 0.0049 |
| Music | 0 | 0 | 0.0043 |
| Sound effect | 0 | 0 | 0.0034 |
| Television | 0 | 0 | 0.0019 |
| Burst, pop | 0 | 0 | 0.0018 |
| Silence | 0 | 0 | 0.0017 |
| Tuning fork | 0 | 0 | 0.0015 |
| Noise | 0 | 0 | 0.0011 |
| Inside, small room | 0 | 0 | 0.0010 |
| Cacophony | 0 | 0 | 0.0009 |
| Singing bowl | 0 | 0 | 0.0008 |
| Waterfall | 0 | 0 | 0.0008 |
| Siren | 0 | 0 | 0.0007 |
| Pink noise | 0 | 0 | 0.0007 |
| Buzzer | 0 | 0 | 0.0007 |
| Spray | 0 | 0 | 0.0007 |
| Vehicle | 0 | 0 | 0.0006 |
| Male speech, man speaking | 0 | 0 | 0.0006 |
| Animal | 0 | 0 | 0.0005 |
| Sidetone | 0 | 0 | 0.0005 |
| Telephone | 0 | 0 | 0.0005 |
| Radio | 0 | 0 | 0.0005 |
| Outside, urban or manmade | 0 | 0 | 0.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.
Recordings that sound alike
Checkpoint6 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
View data
| speaker | PC 1 | PC 2 |
|---|---|---|
| ana | −10.551 | −2.770 |
| ana | −11.446 | −10.405 |
| ben | 11.632 | −3.508 |
| ben | 13.268 | −3.942 |
| cal | −4.945 | 13.927 |
| cal | 2.041 | 6.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
| path | Seconds | PC 1 | PC 2 | Closest 1 (cosine) | speaker |
|---|---|---|---|---|---|
| media/aud3/ana_1.wav | 1 | −10.551 | −2.770 | ana_2.wav 0.86 | ana |
| media/aud3/ana_2.wav | 1 | −11.446 | −10.405 | ana_1.wav 0.86 | ana |
| media/aud3/ben_1.wav | 1 | 11.632 | −3.508 | ben_2.wav 0.95 | ben |
| media/aud3/ben_2.wav | 1 | 13.268 | −3.942 | ben_1.wav 0.95 | ben |
| media/aud3/cal_1.wav | 1 | −4.945 | 13.927 | cal_2.wav 0.89 | cal |
| media/aud3/cal_2.wav | 1 | 2.041 | 6.698 | cal_1.wav 0.89 | cal |
- 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
))
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
| path | Seconds | PC 1 | PC 2 | Closest 1 (cosine) | speaker |
|---|---|---|---|---|---|
| media/aud3/ana_1.wav | 1 | −10.551 | −2.770 | ana_2.wav 0.86 | ana |
| media/aud3/ana_2.wav | 1 | −11.446 | −10.405 | ana_1.wav 0.86 | ana |
| media/aud3/ben_1.wav | 1 | 11.632 | −3.508 | ben_2.wav 0.95 | ben |
| media/aud3/ben_2.wav | 1 | 13.268 | −3.942 | ben_1.wav 0.95 | ben |
| media/aud3/cal_1.wav | 1 | −4.945 | 13.927 | cal_2.wav 0.89 | cal |
| media/aud3/cal_2.wav | 1 | 2.041 | 6.698 | cal_1.wav 0.89 | cal |
- 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.
Do it on your own data
In the appAdd 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.
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])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