spotify-genre-analysis: Can a Cluster Beat a Genre Label?

A notebook-built experiment that turns Spotify’s audio features into machine-made groupings, then asks whether genre is acoustic truth or just metadata with better branding.

8 min read • View on GitHub • More from divyasmurti-cmd

A wide split scene shows the same records being sorted two ways. On one side, handwritten genre labels are pinned onto albums by a person. On the other, a machine pulls the albums into clustered groups using measured features and plotted axes. The image explains the article’s core question: whether genre labels describe sound, or merely organize it.
Genre names describe the shelf. Feature clusters describe the signal.
Key Takeaways

The first clue is not the model. It is the mismatch.

Spotify gives you genre labels. The notebook asks whether those labels line up with the audio itself. That is the interesting tension in divyasmurti-cmd/spotify-genre-analysis: genre as a social category versus genre as a pattern in features like danceability, energy, valence, and tempo.

That framing matters because it changes the project from a tutorial into a test. If songs with different tags still land near each other in feature space, then genre is doing more naming than explaining. If they separate cleanly, then the labels may be better at describing sound than they first appear.

This notebook is what exploratory ML really looks like

The repository is not polished. It reads like a live analysis that was pushed before the edges were sanded down, which makes it more honest than tidy demo code.

# The notebook's style is exploratory, not production packaged.
df = pd.read_csv(path)
df = df.fillna(df.mean(numeric_only=True))
features = df[["danceability", "energy", "loudness", "speechiness",
               "acousticness", "instrumentalness", "liveness",
               "valence", "tempo"]]
scaled = StandardScaler().fit_transform(features)

That roughness is part of the point. Real data science usually starts as a stack of cells, not a clean application. The notebook format lets the author inspect, revise, and rerun each step while the question is still being shaped.

The pipeline turns vibe into coordinates

The notebook does not skip straight to clustering. It normalizes, compresses, and then compares structure against labels.

The data flow is straightforward. The notebook loads a dataset of 32,833 tracks, fills numeric gaps, scales the features, and then uses PCA and K-Means to discover groupings. `StandardScaler` is essential here because tempo and loudness live on very different numeric scales from speechiness or valence. Without normalization, distance-based clustering would mostly follow the biggest numbers.

from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import silhouette_score

X_scaled = StandardScaler().fit_transform(X)
X_pca = PCA(n_components=2).fit_transform(X_scaled)
clusters = KMeans(n_clusters=k, random_state=42).fit_predict(X_scaled)

The real experiment is K-Means versus genre labels

This is the center of the repo. K-Means asks what natural groups exist in the feature space. Logistic regression asks whether the same features can predict Spotify’s genre labels. Those are not the same question, and the difference is the whole story.

MethodInputOutputStrengthWeaknessWhat it reveals about music data
Spotify genre labelsMetadata and human curationNamed categoriesEasy to browse and explainCan mix culture, marketing, and soundGenre is useful as a label system
K-Means clusteringScaled audio featuresUnsupervised song groupsFinds structure without labelsNeeds a cluster countSongs can share vibe even when names differ
Logistic regressionScaled audio features plus labelsPredicted genre classesTests label predictabilityAssumes the labels are learnable from featuresGenre may be only partly audible
A close-up notebook page turns into a topographic map. Columns for danceability, energy, valence, and tempo descend into compact clusters linked by fine lines. In one corner, a hardcoded file path and an execution error remain visible. The image explains how exploratory analysis converts raw measurements into structure, while keeping the messiness of the notebook in view.
The analysis is not born clean. It is cleaned into shape.

That comparison is where the project becomes analytically interesting. Genre labels explain how music is named. Clusters explain how music behaves in a feature space. Neither fully replaces the other, which is why the notebook feels more like an argument than a demo.

Why silhouette score matters here

`silhouette_score` is the notebook’s attempt to keep the cluster count honest. Instead of picking an arbitrary number of groups, the author can measure how well points sit inside a cluster versus how far they sit from the next one.

scores = []
for k in range(2, 11):
    labels = KMeans(n_clusters=k, random_state=42).fit_predict(X_scaled)
    scores.append((k, silhouette_score(X_scaled, labels)))

That is the right instinct for this problem. If the goal is to test whether genre has an acoustic shape, then the cluster count should come from separation in the data, not from a guess that conveniently matches the number of labels.

What this repo suggests about Spotify-like recommendation logic

This is not Spotify’s recommender, and it should not be read that way. But the repo points at a plausible upstream step in recommendation systems: group tracks by measured similarity, then surface neighbors that feel coherent even if their labels differ.

LayerWhat it doesWhy it helps discovery
Feature clusteringGroups songs by audio similarityFinds tracks that may feel alike before anyone names them
Genre labelsAssigns human categoriesMakes browsing and search easier
Prediction modelsLearn label patterns from featuresShows how much of the label can be recovered from sound

The caution matters. Clustering can support discovery, but it does not explain taste by itself. A recommendation system has to mix behavioral signals, content features, and feedback loops. This notebook only explores one slice of that stack.

The project is rough, and that is the lesson

The messiness is not a flaw to excuse. It is the lesson. A lot of real ML work lives in the gap between a notebook that proves a hypothesis and software that other people can trust.

In that sense, the repo is useful precisely because it is unfinished. It shows how a small experiment asks a big question: when you strip away the playlist label and let the numbers talk, what kind of music do they think they are hearing?