By Tania Alwan
Upload a track, get back "lo-fi hip hop, 0.82" or "synthwave, 0.64". An AI music style finder looks like magic from the outside, but inside it is a fairly classic machine learning pipeline: turn audio into numbers, train a classifier on labelled examples, and output probabilities. This post walks through how that pipeline works, which datasets researchers use, where these systems break, and then builds a tiny style classifier with librosa so you can see the moving parts.
Spoiler: the toy gets a perfect score on its own data, and then falls apart the moment the audio changes. That is the most useful lesson in the whole post.
What an AI music style finder is trying to do
In research, this task is usually called music genre recognition (MGR) or genre classification, part of the wider field of music information retrieval (MIR). A style finder typically does one of two things:
- Single-label classification: pick one genre from a fixed list (rock, jazz, hip hop...)
- Multi-label tagging: score many tags at once, such as genre, mood, instrumentation or era, because real songs rarely fit one box
Either way, the output is a set of scores. A threshold or a "top 3" list turns those scores into what the user sees.
The datasets behind most genre research
Two public datasets come up again and again:
- GTZAN. Introduced by Tzanetakis and Cook in their 2002 paper "Musical genre classification of audio signals", it contains 1,000 half-minute excerpts labelled in ten categories. Bob Sturm's analysis, "The GTZAN dataset: Its contents, its faults, their effects on evaluation, and its future use", describes it as the most-used public dataset for evaluating music genre recognition, and catalogues its faults: repetitions, mislabelings and distortions.
- FMA (Free Music Archive). Defferrard et al. released a much larger dataset of 106,574 tracks from 16,341 artists, arranged in a hierarchical taxonomy of 161 genres, with full-length audio, metadata and pre-computed features, plus baselines for genre recognition.
The lesson from Sturm's work is worth remembering whenever you see a high accuracy number: a benchmark score is only as meaningful as the data behind it.
Features: what the model listens to
Classic style finders start from hand-crafted audio features computed over short frames (tens of milliseconds), then summarised over the clip:
- MFCCs (mel-frequency cepstral coefficients): a compact description of the spectral envelope, roughly "timbre"
- Spectral centroid: where the "centre of mass" of the spectrum sits; bright, distorted or cymbal-heavy music tends to score higher
- Zero-crossing rate: how often the waveform crosses zero, a rough proxy for noisiness
- Onset strength and tempo: how percussive the track is and how fast the beat is
- Chroma: energy per pitch class, useful for harmony and key
Summary statistics such as the mean and standard deviation over time turn a variable-length track into a fixed-length vector a classifier can use. The librosa library computes all of these in a few lines.
Classifiers: from random forests to deep networks
Broadly, there are two families:
- Feature + classifier. Extract features like the ones above, then train an SVM, k-nearest neighbours, a random forest or a small neural network. Fast, interpretable and easy to debug.
- Learned representations. Feed a (mel) spectrogram, or even the raw waveform, into a convolutional or transformer model and let it learn its own features. These end-to-end approaches need a lot of labelled audio, and the FMA authors cite the limited availability of large audio datasets as a hurdle for this kind of feature and end-to-end learning, which is one reason they built FMA.
Commercial "AI music style finder" tools rarely publish their models, training data or evaluation, so treat their confidence scores as rough hints rather than verdicts.
The limitations you should know about
- Genre is fuzzy. Labels are cultural, overlapping and change over time. Two experts can disagree about whether a track is "indie pop" or "bedroom pop", so a model trained on their labels inherits that disagreement.
- Datasets have faults. Repeated tracks, mislabelled excerpts and artist overlap between training and test sets can inflate accuracy. Sturm's GTZAN analysis is the classic example.
- Shortcuts. A model can learn cues that correlate with a label in the training data (recording quality, loudness, a particular studio sound) rather than anything musical.
- Channel effects. Compression, phone speakers, live recordings and EQ change exactly the features the model relies on. The toy below shows how dramatic that can be.
A toy AI music style finder in Python
The script generates its own synthetic "styles" so it runs without downloading any dataset: ambient (slow pad, no drums), dance (kick on every beat at 120 to 130 BPM plus a bright synth) and rock (slower kick plus a clipped, noisy "guitar"). It extracts MFCCs, spectral centroid, zero-crossing rate, onset strength and tempo with librosa, then trains a random forest.
This is a toy. It recognises the differences I built into the clips. It says nothing about real songs.
pip install librosa scikit-learn
import numpy as np
import librosa
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
SR = 22050
rng = np.random.default_rng(42)
STYLES = ["ambient", "dance", "rock"]
def toy_clip(style, dur=4.0):
"""Synthetic 'style' clips (NOT real music): each style differs in
tempo, percussion and timbre, the cues real classifiers also use."""
t = np.arange(int(SR * dur)) / SR
root = rng.uniform(110, 220)
if style == "ambient": # slow, soft pad, no drums
y = sum(np.sin(2 * np.pi * root * r * t) for r in (1, 1.5, 2))
y *= 0.5 + 0.5 * np.sin(2 * np.pi * 0.25 * t)
else:
bpm = rng.uniform(120, 130) if style == "dance" else rng.uniform(90, 110)
beat = 60 / bpm
y = np.zeros_like(t)
for start in np.arange(0, dur, beat): # kick drum on every beat
n = int(start * SR); m = min(len(t) - n, int(0.15 * SR))
y[n:n + m] += np.sin(2 * np.pi * 60 * t[:m]) * np.exp(-t[:m] * 30)
if style == "dance": # bright saw-like synth
y += 0.3 * sum(np.sin(2 * np.pi * root * k * t) / k for k in range(1, 15))
else: # "distorted guitar": clipped harmonics + noise
y += 0.4 * np.clip(3 * np.sin(2 * np.pi * root * t), -1, 1)
y += 0.05 * rng.standard_normal(t.size)
y += 0.01 * rng.standard_normal(t.size)
return (y / np.max(np.abs(y))).astype(np.float32)
def features(y):
mfcc = librosa.feature.mfcc(y=y, sr=SR, n_mfcc=13)
centroid = librosa.feature.spectral_centroid(y=y, sr=SR)
zcr = librosa.feature.zero_crossing_rate(y)
onset_env = librosa.onset.onset_strength(y=y, sr=SR)
tempo = librosa.feature.tempo(onset_envelope=onset_env, sr=SR)[0]
return np.r_[mfcc.mean(1), mfcc.std(1), centroid.mean() / 1000,
zcr.mean(), onset_env.mean(), tempo / 100]
labels = np.repeat(np.arange(3), 60)
X = np.array([features(toy_clip(STYLES[l])) for l in labels])
X_tr, X_te, y_tr, y_te = train_test_split(X, labels, test_size=0.3,
random_state=0, stratify=labels)
clf = RandomForestClassifier(n_estimators=200, random_state=0).fit(X_tr, y_tr)
print(f"test accuracy: {clf.score(X_te, y_te):.2f}")
print("confusion matrix (rows = true):")
print(confusion_matrix(y_te, clf.predict(X_te)))
# Same clips, but heard through a "phone speaker": low-pass at 3 kHz
def phone(y):
S = np.fft.rfft(y); f = np.fft.rfftfreq(y.size, 1 / SR)
S[f > 3000] = 0
return np.fft.irfft(S, n=y.size).astype(np.float32)
X_phone = np.array([features(phone(toy_clip(STYLES[l]))) for l in labels])
print(f"accuracy on low-passed clips: {clf.score(X_phone, labels):.2f}")
print("predicted styles on low-passed clips:",
dict(zip(STYLES, np.bincount(clf.predict(X_phone), minlength=3).tolist())))
I ran it with Python 3.13, librosa 1.0.1, NumPy 2.5.4 and scikit-learn 1.9.1. My run printed:
test accuracy: 1.00
confusion matrix (rows = true):
[[18 0 0]
[ 0 18 0]
[ 0 0 18]]
accuracy on low-passed clips: 0.33
predicted styles on low-passed clips: {'ambient': 0, 'dance': 180, 'rock': 0}
Your numbers may differ slightly with other library versions. The first two results look perfect, because the three toy styles are easy to separate. The last two lines are the interesting part: the same clips, simply low-passed at 3 kHz as if played through a small speaker, drop to 0.33 accuracy, which is chance level for three classes, and every single clip is labelled "dance". Nothing about the rhythm or the harmony changed; only the timbre did. That is the channel-effect problem from the section above, in miniature.
Things worth trying:
- Print
clf.feature_importances_to see which features the forest leans on - Add low-passed clips to the training set (data augmentation) and test again on a different filter
- Replace the synthetic clips with a real dataset such as the small FMA subset, and you will quickly see why real genre recognition is much harder
Takeaways
- An AI music style finder is a classifier (or tagger) that maps audio features to genre or style scores
- Features range from MFCCs, spectral centroid and tempo to learned spectrogram representations; models range from random forests to deep networks
- Benchmarks such as GTZAN have known faults, and models can be fooled by recording conditions, so treat any single style score as a hint
If you are analysing tracks rather than labelling them, style is usually only one of the things you want to know. Tools such as the Voicestars BPM and key finder or librosa itself can estimate tempo and key, which are often more useful than a genre label when you are building a playlist, a DJ set or a cover version.
Disclosure: this article was written in partnership with Voicestars.
Top comments (0)