ADescribe · audio.tag
Tag sounds (AudioSet)
What can be heard in these recordings — speech, music, traffic, birds, machines?
Tags each recording with the 527 AudioSet sound classes using the Audio Spectrogram Transformer (MIT's AudioSet model, written out in Python and R on torch from its safetensors weights; a one-time download you approve). Recordings are cut into 10-second windows; a tag's score is its highest (or mean) window score. Results: the top tags of every file, the most common tags across files, a file-by-tag heatmap and a table of top tags you can join back to the files. Scores say what is heard somewhere in a window, not when, and are not calibrated probabilities.
A real result
Example “Sounds default”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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
View data
| Tag | Score | File | Score |
|---|---|---|---|
| Sine wave | 0.71 | 1. tone_440.wav | 0.7139 |
| Static | 0.00 | 1. tone_440.wav | 0.0001 |
| Sound effect | 0.00 | 1. tone_440.wav | 0.0029 |
| Music | 0.00 | 1. tone_440.wav | 0.0030 |
| White noise | 0.00 | 1. tone_440.wav | 0.0002 |
| Electronic music | 0.00 | 1. tone_440.wav | 0.0002 |
| Synthesizer | 0.00 | 1. tone_440.wav | 0.0002 |
| Chirp tone | 0.01 | 1. tone_440.wav | 0.0115 |
| Dial tone | 0.07 | 1. tone_440.wav | 0.0691 |
| Speech | 0.00 | 1. tone_440.wav | 0.0033 |
| Beep, bleep | 0.02 | 1. tone_440.wav | 0.0218 |
| Busy signal | 0.04 | 1. tone_440.wav | 0.0420 |
| Sine wave | 0.29 | 2. chirp.wav | 0.2877 |
| Static | 0.00 | 2. chirp.wav | 0.0002 |
| Sound effect | 0.03 | 2. chirp.wav | 0.0307 |
| Music | 0.02 | 2. chirp.wav | 0.0160 |
| White noise | 0.00 | 2. chirp.wav | 0.0006 |
| Electronic music | 0.00 | 2. chirp.wav | 0.0017 |
| Synthesizer | 0.00 | 2. chirp.wav | 0.0050 |
| Chirp tone | 0.07 | 2. chirp.wav | 0.0738 |
| Dial tone | 0.01 | 2. chirp.wav | 0.0071 |
| Speech | 0.01 | 2. chirp.wav | 0.0056 |
| Beep, bleep | 0.03 | 2. chirp.wav | 0.0319 |
| Busy signal | 0.00 | 2. chirp.wav | 0.0028 |
| Sine wave | 0.00 | 3. noise.wav | 0.0003 |
| Static | 0.76 | 3. noise.wav | 0.7562 |
| Sound effect | 0.01 | 3. noise.wav | 0.0074 |
| Music | 0.03 | 3. noise.wav | 0.0293 |
| White noise | 0.18 | 3. noise.wav | 0.1805 |
| Electronic music | 0.00 | 3. noise.wav | 0.0011 |
| Synthesizer | 0.00 | 3. noise.wav | 0.0002 |
| Chirp tone | 0.00 | 3. noise.wav | 4.379e-5 |
| Dial tone | 0.00 | 3. noise.wav | 0.0001 |
| Speech | 0.06 | 3. noise.wav | 0.0551 |
| Beep, bleep | 0.00 | 3. noise.wav | 0.0006 |
| Busy signal | 0.00 | 3. noise.wav | 0.0002 |
| Sine wave | 0.00 | 4. ana_1.wav | 0.0005 |
| Static | 0.00 | 4. ana_1.wav | 0.0013 |
| Sound effect | 0.38 | 4. ana_1.wav | 0.3760 |
| Music | 0.32 | 4. ana_1.wav | 0.3151 |
| White noise | 0.00 | 4. ana_1.wav | 0.0007 |
| Electronic music | 0.10 | 4. ana_1.wav | 0.0952 |
| Synthesizer | 0.09 | 4. ana_1.wav | 0.0924 |
| Chirp tone | 0.00 | 4. ana_1.wav | 0.0002 |
| Dial tone | 0.00 | 4. ana_1.wav | 0.0003 |
| Speech | 0.01 | 4. ana_1.wav | 0.0105 |
| Beep, bleep | 0.00 | 4. ana_1.wav | 0.0009 |
| Busy signal | 0.00 | 4. ana_1.wav | 0.0019 |
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
| path | Seconds | 10-s windows | Tags (score) |
|---|---|---|---|
| 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 |
| media/aud3/chirp.wav | 1 | 1 | Sine wave 0.29; Chirp tone 0.07; Beep, bleep 0.03; Sound effect 0.03; Music 0.02 |
| media/aud3/noise.wav | 1 | 1 | Static 0.76; White noise 0.18; Speech 0.06; Music 0.03; Pink noise 0.02 |
| media/aud3/ana_1.wav | 1.500 | 1 | Sound effect 0.38; Music 0.32; Electronic music 0.10; Synthesizer 0.09; Techno 0.02 |
Most common tags (score ≥ 0.2)
| Tag | Files | Share of files | Mean score |
|---|---|---|---|
| Sine wave | 2 | 0.5000 | 0.2506 |
| Static | 1 | 0.2500 | 0.1894 |
| Sound effect | 1 | 0.2500 | 0.1043 |
| Music | 1 | 0.2500 | 0.0909 |
| White noise | 0 | 0 | 0.0455 |
| Electronic music | 0 | 0 | 0.0246 |
| Synthesizer | 0 | 0 | 0.0245 |
| Chirp tone | 0 | 0 | 0.0214 |
| Dial tone | 0 | 0 | 0.0192 |
| Speech | 0 | 0 | 0.0186 |
| Beep, bleep | 0 | 0 | 0.0138 |
| Busy signal | 0 | 0 | 0.0117 |
| Techno | 0 | 0 | 0.0064 |
| Pink noise | 0 | 0 | 0.0059 |
| Musical instrument | 0 | 0 | 0.0056 |
| Noise | 0 | 0 | 0.0054 |
| Boing | 0 | 0 | 0.0053 |
| Sampler | 0 | 0 | 0.0042 |
| Cacophony | 0 | 0 | 0.0041 |
| Echo | 0 | 0 | 0.0037 |
| Waterfall | 0 | 0 | 0.0032 |
| Reverberation | 0 | 0 | 0.0031 |
| Video game music | 0 | 0 | 0.0030 |
| Spray | 0 | 0 | 0.0030 |
| Ringtone | 0 | 0 | 0.0028 |
| Inside, small room | 0 | 0 | 0.0023 |
| Silence | 0 | 0 | 0.0023 |
| Keyboard (musical) | 0 | 0 | 0.0021 |
| Television | 0 | 0 | 0.0019 |
| Vehicle | 0 | 0 | 0.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.
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
| path | Seconds | 10-s windows | Tags (score) |
|---|---|---|---|
| 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 |
| media/aud3/chirp.wav | 1 | 1 | Sine wave 0.29; Chirp tone 0.07; Beep, bleep 0.03; Sound effect 0.03; Music 0.02 |
| media/aud3/noise.wav | 1 | 1 | Static 0.76; White noise 0.18; Speech 0.06; Music 0.03; Pink noise 0.02 |
| media/aud3/ana_1.wav | 1.500 | 1 | Sound effect 0.38; Music 0.32; Electronic music 0.10; Synthesizer 0.09; Techno 0.02 |
Most common tags (score ≥ 0.2)
| Tag | Files | Share of files | Mean score |
|---|---|---|---|
| Sine wave | 2 | 0.5000 | 0.2506 |
| Static | 1 | 0.2500 | 0.1894 |
| Sound effect | 1 | 0.2500 | 0.1043 |
| Music | 1 | 0.2500 | 0.0909 |
| White noise | 0 | 0 | 0.0455 |
| Electronic music | 0 | 0 | 0.0246 |
| Synthesizer | 0 | 0 | 0.0245 |
| Chirp tone | 0 | 0 | 0.0214 |
| Dial tone | 0 | 0 | 0.0192 |
| Speech | 0 | 0 | 0.0186 |
| Beep, bleep | 0 | 0 | 0.0138 |
| Busy signal | 0 | 0 | 0.0117 |
| Techno | 0 | 0 | 0.0064 |
| Pink noise | 0 | 0 | 0.0059 |
| Musical instrument | 0 | 0 | 0.0056 |
| Noise | 0 | 0 | 0.0054 |
| Boing | 0 | 0 | 0.0053 |
| Sampler | 0 | 0 | 0.0042 |
| Cacophony | 0 | 0 | 0.0041 |
| Echo | 0 | 0 | 0.0037 |
| Waterfall | 0 | 0 | 0.0032 |
| Reverberation | 0 | 0 | 0.0031 |
| Video game music | 0 | 0 | 0.0030 |
| Spray | 0 | 0 | 0.0030 |
| Ringtone | 0 | 0 | 0.0028 |
| Inside, small room | 0 | 0 | 0.0023 |
| Silence | 0 | 0 | 0.0023 |
| Keyboard (musical) | 0 | 0 | 0.0021 |
| Television | 0 | 0 | 0.0019 |
| Vehicle | 0 | 0 | 0.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.
Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.
Worked examples in the app
- Sounds defaultaud3_sounds · audio: path
- Sounds mean top3aud3_sounds · audio: path
- Scene highest windowaud3_scene · audio: path
- Scene mean windowaud3_scene · audio: path
- Degenerate all naaud3_sounds · audio: path
- Degenerate n1aud3_sounds · audio: path
- Degenerate n2aud3_sounds · audio: path
- Degenerate n3aud3_sounds · audio: path
In the guides
Where it sits in the decision guides
- Multimodal data exploration (text, image, video) · DS & ML Decision Guide · Describe — summarize and visualize
What you need
- Audio file pathcategorical · 1 column
- A column of audio file paths, such as the path column of an audio folder (Data → Add audio folder…). WAV, FLAC, MP3, M4A and OGG are read.
Choices you make
options
- Tags per filedefault 5
How many of the highest-scoring tags to list for each file.
- Score over windowsdefault max
How a long recording's 10-second windows combine into one score per tag.
- Highest window(default) — A tag counts if it is heard clearly in any window (good for finding events).
- Mean over windows — How much of the recording the tag covers (good for describing the whole file).
- Count a tag from scoredefault 0.2
A tag counts as present in a file when its score reaches this, for the most-common-tags table.
Advanced
- Seconds read per filedefault 60
Only the first part of each file is tagged; each 10 seconds take about 2–4 s on one CPU thread.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Clip-level tags, not eventsNot checked from data: state why it holds
AudioSet tags say what is heard somewhere in a 10-second window, not when; several tags can score high at once.
Scores are not probabilities you can trustNot checked from data: state why it holds
Compare scores across files rather than reading them as chances; the model learned from YouTube clips.
Sounds like AudioSet
Very short clips are padded with silence and tag poorly; unusual equipment or recording setups can mislead the model.
What it reports
- n_rows
- Files with a path that decode are analyzed; the rest are counted. Only the first part of each file is read.
- n_files
- Files with a path that decode are analyzed; the rest are counted. Only the first part of each file is read.
- n_tagged
- Files with a path that decode are analyzed; the rest are counted. Only the first part of each file is read.
- n_unreadable
- Files with a path that decode are analyzed; the rest are counted. Only the first part of each file is read.
- n_no_path
- Files with a path that decode are analyzed; the rest are counted. Only the first part of each file is read.
- audio_seconds
- Files with a path that decode are analyzed; the rest are counted. Only the first part of each file is read.
- n_windows
- A long file is cut into 10-second windows; a tag's file score is its highest window score, or the mean.
- top_tag
- Google's 527 sound classes (speech, music, dog, siren…); the tagger scores each one from 0 to 1 per file.
- top_tag_files
- Google's 527 sound classes (speech, music, dog, siren…); the tagger scores each one from 0 to 1 per file.
- n_distinct_top
- Google's 527 sound classes (speech, music, dog, siren…); the tagger scores each one from 0 to 1 per file.
- n_labels
- Google's 527 sound classes (speech, music, dog, siren…); the tagger scores each one from 0 to 1 per file.
- threshold
- A tag counts as present in a file when its score reaches this, for the most-common-tags table.
- pooling
- A long file is cut into 10-second windows; a tag's file score is its highest window score, or the mean.
- top_k
- Google's 527 sound classes (speech, music, dog, siren…); the tagger scores each one from 0 to 1 per file.
- mean_top_score
- Google's 527 sound classes (speech, music, dog, siren…); the tagger scores each one from 0 to 1 per file.
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses pandas, numpy, torch, safetensors, codesplash; R uses torch, jsonlite, nanoparquet, codesplashr.
Default traps between the two languages
- Both engines read the same decoded samples and run the same AST twin in float64 on one thread (torch in Python and R); tag scores agree to about 1e-14.
The exact script CodeSplash ran for example “Sounds default” · 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,
})
The exact script CodeSplash ran for example “Sounds default” · 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
))
Sources
- Gong, Y., Chung, Y.-A., & Glass, J. (2021). AST: Audio Spectrogram Transformer. Proceedings of Interspeech, 571–575.
- Gemmeke, J. F., Ellis, D. P. W., Freedman, D., et al. (2017). Audio Set: An ontology and human-labeled dataset for audio events. Proceedings of ICASSP, 776–780.
- Dosovitskiy, A., Beyer, L., Kolesnikov, A., et al. (2021). An image is worth 16x16 words: Transformers for image recognition at scale. ICLR.
- Povey, D., Ghoshal, A., Boulianne, G., et al. (2011). The Kaldi speech recognition toolkit. IEEE ASRU Workshop (the filterbank front end).
From the CodeSplash method registry · audio.tag v1.0.0.