Clustering Music Tracks
Introduction: Why Cluster Tracks?
Welcome back! So far, you have learned how to represent music tracks and user preferences as vectors, and how to use cosine similarity to recommend tracks to users. In this lesson, we will take a new step: grouping similar tracks together using a technique called clustering.
Clustering helps us organize our music library by finding groups of tracks that are similar to each other. This is useful for many reasons. For example, you can use clusters to create playlists, suggest new genres to users, or simply explore your music collection in a more structured way. In this lesson, you will learn how to use the KMeans algorithm to cluster tracks based on their embeddings.
Recap: Data and Embedding Setup
Before we start clustering, let’s quickly remind ourselves how we get the data and embeddings for our tracks. You have already seen how to load track data and generate embeddings in previous lessons. Here is a short code block that shows the basic setup:
This code gives us two important things:
track_idsandtrack_embeddings_matrix: These are the unique IDs for each track and their corresponding embedding vectors.tracks_df: This is a DataFrame containing all the details about each track.
We will use these as the starting point for clustering.
To confirm everything is wired up correctly, we run some isolated tests on our clustering system (you’ll see these in the practice inside the src/tests/test_clustering.py). Here's the initial diagnostic output:
What Are Clusters
Clustering is a type of unsupervised learning, where we don’t start with any labels or categories. Instead, we ask the algorithm to find natural groupings in the data — that is, clusters.
Think of a cluster as a “cloud” of similar items in a multidimensional space. Each track is represented as a point in this space (based on its embedding), and clustering algorithms try to group nearby points together. The assumption is: if points are close, they’re likely to be similar in meaningful ways (e.g., mood, tempo, instrumentation).
Unlike classification, where we already know categories (like genre) and assign items to them, clustering figures out the categories for us. It answers: "What kinds of groups naturally exist in my data?"
For example, without knowing any genres up front, clustering might still discover groups like “slow instrumental tracks,” “fast electronic tracks,” or “melancholic acoustic songs” — purely based on numerical similarities.
This makes clustering especially useful for:
- Exploring datasets you don’t fully understand yet
- Discovering unexpected patterns
- Creating structure from messy or unlabeled data
KMeans is one of the simplest and most widely used clustering methods, which is why we start with it here.
