Comparing Clustering Algorithms on Large-Scale Spotify Data: Cluster Quality, Stability and Computational Efficiency

Introduction

The purpose of this article is to answer the following research question: How do different clustering algorithms compare in terms of cluster quality, stability and computational efficiency when applied to a large Spotify music dataset?

The experiment consisted of several stages: data preprocessing, determining the number of clusters, applying clustering algorithms, evaluating clustering quality, and analysing stability and computational efficiency.

To determine the number of clusters, several methods were used, including the Silhouette method, Gap Statistic, Within-Cluster Sum of Squares (WSS) and Bayesian Information Criterion (BIC). These methods will be discussed in more detail in later sections of the article.

Three clustering algorithms were selected for the analysis: K-means, CLARA and Gaussian Mixture Models (GMM). The general idea behind clustering is to divide observations into groups so that similar observations are assigned to the same cluster. Each of the selected algorithms uses a different approach to create clusters, which makes it possible to compare their results and performance.

Dataset and Preprocessing

The dataset used in this experiment was obtained from Kaggle (Pandya, n.d.). The main goal of the experiment was to group songs based on their audio features. The first step in data preprocessing was exploratory data analysis (EDA).

spotify=read.csv("dataset.csv")
head(spotify)
##   X               track_id                artists
## 1 0 5SuOikwiRyPMVoIQDJUgSV            Gen Hoshino
## 2 1 4qPNDBW1i3p13qLCt0Ki3A           Ben Woodward
## 3 2 1iJBSr7s7jYXzM8EGcbK5b Ingrid Michaelson;ZAYN
## 4 3 6lfxq3CG4xtTiEg7opyCyx           Kina Grannis
## 5 4 5vjLSffimiIP26QG5WcN2K       Chord Overstreet
## 6 5 01MVOl9KtVTNfFiBU9I7dc           Tyrone Wells
##                                               album_name
## 1                                                 Comedy
## 2                                       Ghost (Acoustic)
## 3                                         To Begin Again
## 4 Crazy Rich Asians (Original Motion Picture Soundtrack)
## 5                                                Hold On
## 6                                   Days I Will Remember
##                   track_name popularity duration_ms explicit danceability
## 1                     Comedy         73      230666    False        0.676
## 2           Ghost - Acoustic         55      149610    False        0.420
## 3             To Begin Again         57      210826    False        0.438
## 4 Can't Help Falling In Love         71      201933    False        0.266
## 5                    Hold On         82      198853    False        0.618
## 6       Days I Will Remember         58      214240    False        0.688
##   energy key loudness mode speechiness acousticness instrumentalness liveness
## 1 0.4610   1   -6.746    0      0.1430       0.0322         1.01e-06   0.3580
## 2 0.1660   1  -17.235    1      0.0763       0.9240         5.56e-06   0.1010
## 3 0.3590   0   -9.734    1      0.0557       0.2100         0.00e+00   0.1170
## 4 0.0596   0  -18.515    1      0.0363       0.9050         7.07e-05   0.1320
## 5 0.4430   2   -9.681    1      0.0526       0.4690         0.00e+00   0.0829
## 6 0.4810   6   -8.807    1      0.1050       0.2890         0.00e+00   0.1890
##   valence   tempo time_signature track_genre
## 1   0.715  87.917              4    acoustic
## 2   0.267  77.489              4    acoustic
## 3   0.120  76.332              4    acoustic
## 4   0.143 181.740              3    acoustic
## 5   0.167 119.949              4    acoustic
## 6   0.666  98.017              4    acoustic
summary(spotify)
##        X               track_id           artists           album_name    
##  Min.   :     0   Length   :114000   Length   :114000   Length   :114000  
##  1st Qu.: 28500   N.unique : 89741   N.unique : 31438   N.unique : 46590  
##  Median : 57000   N.blank  :     0   N.blank  :     1   N.blank  :     1  
##  Mean   : 57000   Min.nchar:    22   Min.nchar:     0   Min.nchar:     0  
##  3rd Qu.: 85499   Max.nchar:    22   Max.nchar:   513   Max.nchar:   243  
##  Max.   :113999                                                           
##      track_name       popularity      duration_ms           explicit     
##  Length   :114000   Min.   :  0.00   Min.   :      0   Length   :114000  
##  N.unique : 73609   1st Qu.: 17.00   1st Qu.: 174066   N.unique :     2  
##  N.blank  :     1   Median : 35.00   Median : 212906   N.blank  :     0  
##  Min.nchar:     0   Mean   : 33.24   Mean   : 228029   Min.nchar:     4  
##  Max.nchar:   511   3rd Qu.: 50.00   3rd Qu.: 261506   Max.nchar:     5  
##                     Max.   :100.00   Max.   :5237295                     
##   danceability        energy            key            loudness      
##  Min.   :0.0000   Min.   :0.0000   Min.   : 0.000   Min.   :-49.531  
##  1st Qu.:0.4560   1st Qu.:0.4720   1st Qu.: 2.000   1st Qu.:-10.013  
##  Median :0.5800   Median :0.6850   Median : 5.000   Median : -7.004  
##  Mean   :0.5668   Mean   :0.6414   Mean   : 5.309   Mean   : -8.259  
##  3rd Qu.:0.6950   3rd Qu.:0.8540   3rd Qu.: 8.000   3rd Qu.: -5.003  
##  Max.   :0.9850   Max.   :1.0000   Max.   :11.000   Max.   :  4.532  
##       mode         speechiness       acousticness    instrumentalness  
##  Min.   :0.0000   Min.   :0.00000   Min.   :0.0000   Min.   :0.00e+00  
##  1st Qu.:0.0000   1st Qu.:0.03590   1st Qu.:0.0169   1st Qu.:0.00e+00  
##  Median :1.0000   Median :0.04890   Median :0.1690   Median :4.16e-05  
##  Mean   :0.6376   Mean   :0.08465   Mean   :0.3149   Mean   :1.56e-01  
##  3rd Qu.:1.0000   3rd Qu.:0.08450   3rd Qu.:0.5980   3rd Qu.:4.90e-02  
##  Max.   :1.0000   Max.   :0.96500   Max.   :0.9960   Max.   :1.00e+00  
##     liveness         valence           tempo        time_signature 
##  Min.   :0.0000   Min.   :0.0000   Min.   :  0.00   Min.   :0.000  
##  1st Qu.:0.0980   1st Qu.:0.2600   1st Qu.: 99.22   1st Qu.:4.000  
##  Median :0.1320   Median :0.4640   Median :122.02   Median :4.000  
##  Mean   :0.2136   Mean   :0.4741   Mean   :122.15   Mean   :3.904  
##  3rd Qu.:0.2730   3rd Qu.:0.6830   3rd Qu.:140.07   3rd Qu.:4.000  
##  Max.   :1.0000   Max.   :0.9950   Max.   :243.37   Max.   :5.000  
##     track_genre    
##  Length   :114000  
##  N.unique :   114  
##  N.blank  :     0  
##  Min.nchar:     3  
##  Max.nchar:    17  
## 
str(spotify)
## 'data.frame':    114000 obs. of  21 variables:
##  $ X               : int  0 1 2 3 4 5 6 7 8 9 ...
##  $ track_id        : chr  "5SuOikwiRyPMVoIQDJUgSV" "4qPNDBW1i3p13qLCt0Ki3A" "1iJBSr7s7jYXzM8EGcbK5b" "6lfxq3CG4xtTiEg7opyCyx" ...
##  $ artists         : chr  "Gen Hoshino" "Ben Woodward" "Ingrid Michaelson;ZAYN" "Kina Grannis" ...
##  $ album_name      : chr  "Comedy" "Ghost (Acoustic)" "To Begin Again" "Crazy Rich Asians (Original Motion Picture Soundtrack)" ...
##  $ track_name      : chr  "Comedy" "Ghost - Acoustic" "To Begin Again" "Can't Help Falling In Love" ...
##  $ popularity      : int  73 55 57 71 82 58 74 80 74 56 ...
##  $ duration_ms     : int  230666 149610 210826 201933 198853 214240 229400 242946 189613 205594 ...
##  $ explicit        : chr  "False" "False" "False" "False" ...
##  $ danceability    : num  0.676 0.42 0.438 0.266 0.618 0.688 0.407 0.703 0.625 0.442 ...
##  $ energy          : num  0.461 0.166 0.359 0.0596 0.443 0.481 0.147 0.444 0.414 0.632 ...
##  $ key             : int  1 1 0 0 2 6 2 11 0 1 ...
##  $ loudness        : num  -6.75 -17.23 -9.73 -18.52 -9.68 ...
##  $ mode            : int  0 1 1 1 1 1 1 1 1 1 ...
##  $ speechiness     : num  0.143 0.0763 0.0557 0.0363 0.0526 0.105 0.0355 0.0417 0.0369 0.0295 ...
##  $ acousticness    : num  0.0322 0.924 0.21 0.905 0.469 0.289 0.857 0.559 0.294 0.426 ...
##  $ instrumentalness: num  1.01e-06 5.56e-06 0.00 7.07e-05 0.00 0.00 2.89e-06 0.00 0.00 4.19e-03 ...
##  $ liveness        : num  0.358 0.101 0.117 0.132 0.0829 0.189 0.0913 0.0973 0.151 0.0735 ...
##  $ valence         : num  0.715 0.267 0.12 0.143 0.167 0.666 0.0765 0.712 0.669 0.196 ...
##  $ tempo           : num  87.9 77.5 76.3 181.7 119.9 ...
##  $ time_signature  : int  4 4 4 3 4 4 3 4 4 4 ...
##  $ track_genre     : chr  "acoustic" "acoustic" "acoustic" "acoustic" ...
colSums(is.na(spotify))  
##                X         track_id          artists       album_name 
##                0                0                0                0 
##       track_name       popularity      duration_ms         explicit 
##                0                0                0                0 
##     danceability           energy              key         loudness 
##                0                0                0                0 
##             mode      speechiness     acousticness instrumentalness 
##                0                0                0                0 
##         liveness          valence            tempo   time_signature 
##                0                0                0                0 
##      track_genre 
##                0
dim(spotify) 
## [1] 114000     21

The initial analysis showed that the dataset contains 114,000 rows and 21 columns, with no missing values.

spotify_clust = dplyr::select(
  spotify,
  danceability,
  energy,
  loudness,
  speechiness,
  acousticness,
  instrumentalness,
  liveness,
  valence,
  tempo
)
head(spotify_clust)
##   danceability energy loudness speechiness acousticness instrumentalness
## 1        0.676 0.4610   -6.746      0.1430       0.0322         1.01e-06
## 2        0.420 0.1660  -17.235      0.0763       0.9240         5.56e-06
## 3        0.438 0.3590   -9.734      0.0557       0.2100         0.00e+00
## 4        0.266 0.0596  -18.515      0.0363       0.9050         7.07e-05
## 5        0.618 0.4430   -9.681      0.0526       0.4690         0.00e+00
## 6        0.688 0.4810   -8.807      0.1050       0.2890         0.00e+00
##   liveness valence   tempo
## 1   0.3580   0.715  87.917
## 2   0.1010   0.267  77.489
## 3   0.1170   0.120  76.332
## 4   0.1320   0.143 181.740
## 5   0.0829   0.167 119.949
## 6   0.1890   0.666  98.017

Since the aim of the experiment was to cluster songs based on their audio characteristics, nine numerical audio features were selected: danceability, energy, loudness, speechiness, acousticness, instrumentalness, liveness, valence, tempo. The remaining variables were excluded from the clustering process because they were not relevant to the selected analysis.

The selected audio features describe different characteristics of a song:

  • danceability - how suitable a track is for dancing,

  • energy - represents a perceptual measure of intensity and activity,

  • loudness - the overall loudness of a track in decibels,

  • speechiness - the presence of spoken words in a track,

  • acousticness - likelihood the track is acoustic,

  • instrumentalness - whether a track contains no vocals,

  • liveness - the presence of an audience in the recording,

  • valence - the musical positiveness conveyed by a track,

  • tempo - the overall estimated tempo of a track in beats per minute.

Since the selected features have different value ranges, normalization was performed before clustering. This helps prevent variables with larger ranges from having a greater influence on the clustering results than the other variables.

spotify_normal = clusterSim::data.Normalization(spotify_clust, type="n1",normalization="column")
summary(spotify_normal)
##   danceability          energy           loudness        speechiness       
##  Min.   :-3.26607   Min.   :-2.5499   Min.   :-8.2063   Min.   :-0.800626  
##  1st Qu.:-0.63846   1st Qu.:-0.6734   1st Qu.:-0.3488   1st Qu.:-0.461090  
##  Median : 0.07606   Median : 0.1734   Median : 0.2495   Median :-0.338138  
##  Mean   : 0.00000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.000000  
##  3rd Qu.: 0.73872   3rd Qu.: 0.8453   3rd Qu.: 0.6474   3rd Qu.:-0.001439  
##  Max.   : 2.40979   Max.   : 1.4257   Max.   : 2.5433   Max.   : 8.326191  
##   acousticness     instrumentalness     liveness          valence        
##  Min.   :-0.9470   Min.   :-0.5041   Min.   :-1.1217   Min.   :-1.82854  
##  1st Qu.:-0.8962   1st Qu.:-0.5041   1st Qu.:-0.6070   1st Qu.:-0.82569  
##  Median :-0.4388   Median :-0.5040   Median :-0.4284   Median :-0.03883  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.00000  
##  3rd Qu.: 0.8513   3rd Qu.:-0.3458   3rd Qu.: 0.3123   3rd Qu.: 0.80587  
##  Max.   : 2.0483   Max.   : 2.7263   Max.   : 4.1310   Max.   : 2.00929  
##      tempo          
##  Min.   :-4.074556  
##  1st Qu.:-0.764859  
##  Median :-0.004364  
##  Mean   : 0.000000  
##  3rd Qu.: 0.597873  
##  Max.   : 4.043744

Cluster Tendency

An important step at the beginning of an experiment like this is checking whether the dataset has a tendency to form clusters. The Hopkins statistic was used for this purpose (Hopkins & Skellam, 1954). However, an error occurred during the calculation because the dataset was too large and RStudio ran out of memory. To overcome this problem, a sample of 2,000 rows was created and used for the calculations.

set.seed(123)

spotify_sample <- spotify_normal[
  sample(nrow(spotify_normal), 2000),
]

hopkins::hopkins(spotify_sample, m=100)
## [1] 0.999992

A graphical representation was also created using the get_clust_tendency() function.

factoextra::get_clust_tendency(
  spotify_sample,
  n=100,
  graph=TRUE,
  gradient=list(low="red",mid="white",high="blue"),
  seed=123
) 
## $hopkins_stat
## [1] 0.9988229
## 
## $plot

Both calculations returned Hopkins values close to 1 (0.999992 and 0.9988229). This shows a strong tendency of the dataset to form clusters. The graph also shows organised figures, with blue stripes appearing against a red background.

Determining the Number of Clusters

A sample of the data was used in this part of the experiment because of the complexity and time required for the calculations. A sample of 10,000 observations was selected to make the analysis more manageable while still using a relatively large part of the dataset.

set.seed(123)
spotify_sample3 <- spotify_normal[
  sample(nrow(spotify_normal), 10000),
]

Before applying the clustering algorithms, the number of clusters needed to be estimated. Several methods were tested for different possible numbers of clusters. It is important to mention that the methods did not always indicate the same number of clusters. Therefore, their results were compared to select different configurations for further analysis.

Silhouette method

The Silhouette method is used to evaluate how well observations fit into their assigned clusters. It considers both how close an observation is to other observations in the same cluster and how far it is from observations in other clusters. The average Silhouette value can be calculated for different numbers of clusters. A higher value indicates better separation between clusters, so the number of clusters with the highest average Silhouette value is usually preferred (Rousseeuw, 1987).

Gap Statistic

The method compares empirical pattern with uniform distribution. It uses the within-cluster dispersion to make this comparison between them. A larger Gap value indicates a stronger clustering structure compared to the reference data (Tibshirani et al., 2001). However, the final number of clusters can also depend on the selection rule used, which takes the standard error into account.

Within-Cluster Sum of Squares (WSS) / Elbow Method

WSS measures the variation within clusters. It is calculated for different numbers of clusters and presented on a graph. The aim is to find a point on a curve where adding more clusters brings smaller improvements. This point is known as the elbow and can be used as an indication of a suitable number of clusters.

Bayesian Information Criterion (BIC)

The Bayesian Information Criterion (BIC) was used only for the GMM model in this experiment. It helps compare models with different numbers of components and different covariance structures. The higher BIC value the better model (Schwarz, 1978).

K-means

WSS

The graph shows a visible slowing down of the WSS decrease around k=8.

set.seed(123)
wss_kmeans=fviz_nbclust(
  spotify_sample3,
  FUNcluster=kmeans,
  method="wss",
  k.max=20,
  nstart=10,
  iter.max=100
) + theme_classic()

SILHOUETTE

Based on the graph, the highest average Silhouette value was obtained for k=2. Therefore, this method indicates two clusters as the most suitable option.

set.seed(123)
silhouette_kmeans=fviz_nbclust(
  spotify_sample3,
  FUNcluster=kmeans,
  method="silhouette",
  k.max=20,
  nstart=10,
  iter.max=100
) + theme_classic()

GAP STATISTIC

According to the Gap Statistic and the firstSEmax selection rule, the suggested number of clusters was k=16.

gap_kmeans <- factoextra::fviz_nbclust(
  spotify_sample3,
  FUNcluster=kmeans,
  method="gap_stat",
  k.max=20,
  nstart=10,
  iter.max=100,
  nboot=50
) + theme_classic()

Based on these results, three configurations were selected for further analysis: k=2, k=8 and k=16.

CLARA

WSS

The graph suggests that the elbow appears around k=13.

set.seed(123)
wss_clara <- factoextra::fviz_nbclust(
  spotify_sample3,
  FUNcluster = cluster::clara,
  method = "wss",
  k.max = 20,
  samples = 5,
  sampsize = 1000
) + theme_classic()

SILHOUETTE

Similarly to K-means, the highest average Silhouette value was obtained for k=2.

set.seed(123)
silhouette_clara <- factoextra::fviz_nbclust(
  spotify_sample3,
  FUNcluster = cluster::clara,
  method = "silhouette",
  k.max = 20,
  samples = 5,
  sampsize = 1000
) + theme_classic()

GAP STATISTIC

The Gap Statistic, using the firstSEmax selection rule, suggested k=14. This result is close to the value indicated by the WSS graph.

set.seed(123)
gap_clara <- factoextra::fviz_nbclust(
  spotify_sample3,
  FUNcluster=cluster::clara,
  method="gap_stat",
  k.max=20,
  nboot=50
) + theme_classic()

Based on these results, three configurations of CLARA were selected for further analysis: k=2, k=13 and k=14.

GMM

For GMM, different covariance structures and numbers of components were tested using the Mclust() function. Based on the BIC results, the VEV covariance structure was selected for further analysis. The initial search indicated that 32 components provided the best BIC value. An additional search over a wider range of component numbers showed that 39 components was another promising configuration. Both configurations were selected for further comparison.

set.seed(123)
gmm_vev_extended <- mclust::Mclust(
  spotify_sample3,
  G = 20:40,
  modelNames = "VEV"
)

Clustering Algorithms

The models were fitted on the full normalized dataset. The configurations were selected based on the earlier analysis of the number of clusters. During model fitting, the computational time was also recorded. These measurements will be used later to compare the computational efficiency of the algorithms.

K-means

K-means is a centroid-based clustering algorithm (MacQueen, 1967). It starts by selecting a predefined number of centroids, which represent the clusters. For each observation in the dataset, the distance to every centroid is calculated, and the observation is assigned to the cluster with the closest centroid. After this assignment, the centroids are updated based on the observations belonging to the cluster represented by them. This process is repeated until the clusters are stabilized or another stopping condition is reached.

K-means was selected for this experiment because it is relatively computationally efficient, quite simple and can be applied to large datasets.

#K-means k=2
set.seed(123)
kmeans_time1 <- system.time(
  kmeans_model1 <- kmeans(
    spotify_normal,
    centers=2,
    nstart=25
  )
)[["elapsed"]]

#K-means k=8
set.seed(123)
kmeans_time2 <- system.time(
  kmeans_model2 <- kmeans(
    spotify_normal,
    centers=8,
    nstart=25
  )
)[["elapsed"]]

#K-means k=16
set.seed(123)
kmeans_time3 <- system.time(
  kmeans_model3 <- kmeans(
    spotify_normal,
    centers=16,
    nstart=25
  )
)[["elapsed"]]

CLARA

CLARA (Clustering Large Applications) is a clustering algorithm based on medoids (Kaufman & Rousseeuw, 1990), which are actual observations from the dataset. Instead of performing the clustering process on the entire dataset, CLARA uses multiple samples of the data to find a set of medoids. Each observation is assigned to its closest medoid. This sampling approach makes CLARA more suitable for larger datasets.

#CLARA k=2
set.seed(123)
clara_time1 <- system.time(
  clara_model1 <- clara(
    spotify_normal,
    k=2,
    samples=5,
    sampsize=1000
  )
)[["elapsed"]]

#CLARA k=13
set.seed(123)
clara_time2 <- system.time(
  clara_model2 <- clara(
    spotify_normal,
    k=13,
    samples=5,
    sampsize=1000
  )
)[["elapsed"]]

#CLARA k=14
set.seed(123)
clara_time3 <- system.time(
  clara_model3 <- clara(
    spotify_normal,
    k=14,
    samples=5,
    sampsize=1000
  )
)[["elapsed"]]

GMM

Gaussian Mixture Models (GMM) are probabilistic clustering methods that assume the data can be represented as a mixture of normal distributions (Scrucca et al., 2016). Each component represents a part of the data with its own estimated parameters. For each observation, the model estimates the probabilities of belonging to the different components. In this experiment, observations were assigned to the component with the highest posterior probability, resulting in a hard clustering solution.

# GMM VEV - 32 components
set.seed(123)
gmm_time2 <- system.time(
  gmm_model2 <- mclust::Mclust(
    spotify_normal,
    G=32,
    modelNames="VEV"
  )
)[["elapsed"]]

# GMM VEV - 39 components
set.seed(123)
gmm_time3 <- system.time(
  gmm_model3 <- mclust::Mclust(
    spotify_normal,
    G=39,
    modelNames="VEV"
  )
)[["elapsed"]]

Computational Efficiency

During model fitting, the elapsed time required to complete each configuration was recorded. The table below presents the computational time of all tested configurations. The measurements were taken on the same dataset and computer, allowing for a direct comparison of the recorded fitting times.

##   Algorithm Configuration Runtime
## 1   K-means           k=2   1.167
## 2   K-means           k=8   7.222
## 3   K-means          k=16  10.988
## 4     CLARA           k=2   0.129
## 5     CLARA          k=13   0.592
## 6     CLARA          k=14   0.602
## 7       GMM      VEV G=32 196.708
## 8       GMM      VEV G=39 323.726

CLARA was the fastest algorithm across all three tested configurations. K-means also showed relatively short computational times, which increased with the number of clusters. In contrast, both GMM configurations were considerably more computationally expensive, with the model containing 39 components requiring the longest fitting time.

Cluster Quality

Three metrics were selected to evaluate cluster quality: Silhouette, Calinski-Harabasz and Davies-Bouldin.

Before calculating the metrics, an additional step was necessary. Since calculating the distance matrix for the full dataset caused errors in RStudio, a sample of 10,000 observations was used for the evaluation (the same sample as in the determining the number of clusters). The cluster assignments obtained from models fitted on the full dataset were extracted for the observations included in this sample. This allowed the quality metrics to be calculated on the same sample for all models.

The extraction of cluster assignments was performed for every model in a similar way, as shown in the code below.

# Indices of observations in the sample
sample_indices <- match(
  rownames(spotify_sample3),
  rownames(spotify_normal)
)
# Extract cluster assignments for the sample
clusters_kmeans2 <- kmeans_model1$cluster[sample_indices]

Silhouette

The Silhouette metric evaluates how well observations fit within their assigned clusters compared to other clusters. Its values range from -1 to 1, with higher values indicating better clustering results. Values around 1 indicate well separated clusters, while values closer to 0 suggest that clusters overlap. Negative values may indicate that observations have been assigned to the wrong cluster (Rousseeuw, 1987).

For every model, the average Silhouette value was calculated in a similar way, as shown in the code below.

sil_kmeans2 <- mean(cluster::silhouette(clusters_kmeans2, distance_matrix)[, "sil_width"])

The results for every model are shown in the table below:

##   Algorithm Configuration  Silhouette
## 1   K-means           k=2  0.26195209
## 2   K-means           k=8  0.19693640
## 3   K-means          k=16  0.15168565
## 4     CLARA           k=2  0.23332390
## 5     CLARA          k=13  0.11778528
## 6     CLARA          k=14  0.12673039
## 7       GMM     VEV, G=32 -0.05332976
## 8       GMM     VEV, G=39 -0.05894200

The highest Silhouette value was obtained by K-means with 2 clusters, followed by CLARA with 2 clusters. However, the values were relatively low across the models, suggesting that the clusters were not strongly separated.

Calinski-Harabasz

The Calinski-Harabasz metric evaluates the relationship between the dispersion of observations between clusters and within clusters (Caliński & Harabasz, 1974). Higher values indicate better defined clusters.

The calculation for each model was performed in a similar way, as shown below.

ch_kmeans2 <- intCriteria(as.matrix(spotify_sample3), as.integer(clusters_kmeans2), "Calinski_Harabasz")

The results for every model are shown in the table below:

##   Algorithm Configuration Calinski_Harabasz
## 1   K-means           k=2         2742.2277
## 2   K-means           k=8         1751.5116
## 3   K-means          k=16         1297.5926
## 4     CLARA           k=2         2611.1597
## 5     CLARA          k=13         1308.6636
## 6     CLARA          k=14         1233.5853
## 7       GMM     VEV, G=32          317.7495
## 8       GMM     VEV, G=39          283.2492

The highest Calinski-Harabasz value was obtained by K-means with 2 clusters, followed by CLARA with 2 clusters. This is consistent with the results obtained using the Silhouette metric.

Davies–Bouldin

The Davies-Bouldin metric evaluates cluster separation in relation to cluster dispersion (Davies & Bouldin, 1979). Unlike the previous two metrics, lower values indicate better clustering results.

The calculation for each model was performed in a similar way, as shown below.

db_kmeans2 <- intCriteria(as.matrix(spotify_sample3), as.integer(clusters_kmeans2), "Davies_Bouldin")

The results for every model are shown in the table below:

##   Algorithm Configuration Davies_Bouldin
## 1   K-means           k=2       1.578040
## 2   K-means           k=8       1.358465
## 3   K-means          k=16       1.530347
## 4     CLARA           k=2       1.738438
## 5     CLARA          k=13       1.630477
## 6     CLARA          k=14       1.710371
## 7       GMM     VEV, G=32       4.144855
## 8       GMM     VEV, G=39       4.658565

In terms of the Davies-Bouldin metric, the best result was obtained by K-means with 8 clusters. This differs from the results of the previous two metrics, which favoured K-means with 2 clusters.

Cluster Stability

Cluster stability was evaluated using the Adjusted Rand Index (ARI) (Hubert & Arabie, 1985). This measure compares two clustering results and takes into account the possibility of random agreement. Values close to 1 indicate strong similarity between the clustering solutions, whereas values around 0 suggest that their agreement is no better than what could be expected by chance.

Each model configuration was evaluated using five subsamples, each containing 80% of the observations from the original sample of 10,000 observations. The individual algorithm configurations were refitted on each subsample. The cluster assignments were then compared for observations that appeared in both subsamples. The mean ARI value was calculated across all ten comparisons for each configuration.

The results of this analysis are shown in the table below:

##   Algorithm Configuration       ARI
## 1   K-means           k=2 0.9837522
## 2   K-means           k=8 0.8253142
## 3   K-means          k=16 0.7454753
## 4     CLARA           k=2 0.6993610
## 5     CLARA          k=13 0.4219099
## 6     CLARA          k=14 0.4037905
## 7       GMM      VEV G=32 0.3760430
## 8       GMM      VEV G=39 0.3490015

K-means with 2 clusters achieved the highest stability among all tested configurations. K-means with 8 clusters also showed a relatively high level of agreement between the clustering results. Stability decreased as the number of clusters increased for the tested K-means configurations. CLARA and GMM obtained lower ARI values, suggesting that their cluster assignments were more sensitive to changes in the sampled observations.

Cluster Interpretation

Three configurations were selected for the final stage of the analysis: K-means with 2 clusters, K-means with 8 clusters and CLARA with 2 clusters. The aim was to examine the characteristics of the clusters created by these models and see whether they could be associated with particular types of music.

For each configuration, the cluster sizes and percentage shares were calculated, together with the mean values of the audio features. The track_genre variable was also used to examine the genres assigned to each cluster. For this purpose, the ten most frequent genres in each cluster were identified.

The mean of each variable in the normalized dataset is approximately 0. Therefore, positive values indicate values above the overall mean, while negative values indicate values below the overall mean.

K-means with 2 clusters

This configuration performed best in terms of the Silhouette and Calinski-Harabasz metrics. It also achieved the highest ARI value, indicating the greatest stability among the tested configurations. The cluster sizes were relatively uneven, with 75.39% of observations assigned to cluster 1 and 24.61% to cluster 2.

The mean values of the audio features are presented below:

The two clusters differ considerably in their mean audio feature values. Cluster 1 has above average values for danceability, energy, loudness, speechiness, liveness, valence and tempo, while acousticness and instrumentalness are below average. This suggests that this cluster contains music that is generally more energetic, danceable and louder.

Cluster 2 shows the opposite pattern for most of these features. It has lower values for danceability, energy, loudness, valence and tempo, while acousticness and instrumentalness are above average. This suggests a more relaxed and less energetic profile.

The most frequent genres in each cluster are presented below:

The genre distribution provides additional insight into the clusters. Cluster 1 includes genres such as hardstyle, reggaeton, house, party and drum-and-bass among its most frequent genres. Cluster 2 is more associated with genres such as sleep, classical, new-age, ambient and romance. These results are consistent with the differences in the audio feature profiles and suggest that K-means with 2 clusters separated tracks into two broadly different musical profiles.

K-means with 8 clusters

This configuration was selected because it achieved the lowest Davies-Bouldin value among the tested models. It also showed relatively high stability, with an ARI of 0.8253. The cluster sizes were as follows: 6.51%, 19.51%, 6.46%, 21.73%, 0.83%, 28.84%, 5.97% and 10.15%. One of the clusters, cluster 5, was particularly small, containing only 0.83% of the observations.

The mean values of the audio features are presented below:

The eight clusters show different combinations of audio feature values, which makes it possible to identify more specific profiles than in the two cluster solution. The genre distributions are presented below:

Looking at the most frequent genres, several clusters can be associated with different musical styles. Cluster 1 is associated with genres such as pagode, sertanejo and samba. Cluster 2 includes genres such as romance, honky-tonk and tango. Cluster 3 contains mostly calmer genres, including new-age, sleep, classical and ambient. Cluster 4 is associated with heavier genres such as metalcore, heavy-metal and grunge.

Cluster 5 is particularly interesting because it is very small and is mostly associated with the comedy genre. Cluster 6 includes genres such as salsa, latino, reggaeton and reggae, which are also reflected in its above average danceability and valence. Cluster 7 has a notably high speechiness value and includes genres such as j-dance and dancehall among its most frequent genres. Finally, cluster 8 has a very high instrumentalness value and includes genres such as minimal-techno, detroit-techno and techno.

Overall, K-means with 8 clusters provides more detailed musical profiles than the two cluster solution. Although the clusters are not equally sized, some of them show quite distinctive combinations of audio features and genres.

CLARA with 2 clusters

CLARA with 2 clusters was selected mainly because of its very short computational time and relatively high Silhouette and Calinski-Harabasz values compared to the other tested configurations. The cluster sizes were 68.30% and 31.70%, respectively. As in the K-means solution with 2 clusters, the first cluster was larger, although the distribution was slightly more balanced.

The mean values of the audio features are presented below:

The two clusters show clearly different mean values for most of the audio features. Cluster 1 has above average danceability, energy, loudness, valence and tempo, while acousticness is below average. Cluster 2 shows the opposite pattern for most of these features, with higher acousticness and lower energy, loudness, danceability, valence and tempo. This suggests that the two clusters represent different musical profiles, with the first being generally more energetic and the second more relaxed.

The most frequent genres in each cluster are presented below:

CLARA divided the tracks into two similar musical profiles to those obtained with K-means with 2 clusters. Cluster 1 includes genres such as hardstyle, party, drum-and-bass, happy and progressive-house among its most frequent genres. Cluster 2 is associated with genres such as sleep, classical, romance, tango, new-age and ambient. These genre distributions are consistent with the differences in the mean audio features of the two clusters.

Final Comparison and Conclusions

The aim of this study was to compare K-means, CLARA and Gaussian Mixture Models (GMM) in terms of clustering quality, stability and computational efficiency using a large-scale Spotify dataset.

For the final comparison, three models were selected: K-means with 2 clusters, K-means with 8 clusters and CLARA with 2 clusters. These were the same configurations selected for the cluster interpretation section.

The results indicate that K-means with two clusters provided the strongest overall performance according to the internal validation metrics. It achieved the highest Silhouette coefficient (0.262) and Calinski-Harabasz index (2742.23), as well as the highest stability measured by the ARI (0.984). Its computational time was also relatively low, at 1.17 seconds when fitted to the full dataset.

The interpretation of the resulting clusters revealed a broad division between more energetic and danceable tracks and quieter, more acoustic tracks. A similar structure was identified by CLARA with two clusters, suggesting that both algorithms captured comparable broad patterns in the audio features.

However, the two algorithms differed in computational efficiency. CLARA was the fastest method, requiring approximately 0.13 seconds to fit the two-cluster configuration. Although its clustering quality and stability were lower than those of K-means, its performance suggests that CLARA can be a practical alternative when computational efficiency is particularly important.

K-means with eight clusters provided a more detailed representation of the dataset. Its clusters showed more specific audio feature and genre-related profiles, including ambient and classical music, metal, Latin music, electronic music and comedy-related tracks. This configuration achieved the lowest Davies-Bouldin index (1.358) among the tested models. However, its lower Silhouette value and stability indicate that this more detailed division came at the cost of weaker overall cluster separation and consistency.

GMM configurations with 32 and 39 components required considerably more computational time and achieved weaker results according to the internal validation metrics used in this study. Therefore, they were not selected for the final cluster interpretation.

Although K-means with two clusters performed best according to most of the validation metrics, K-means with eight clusters was selected as the final model for cluster interpretation. This decision was based on the aim of the study, which was not only to evaluate clustering performance but also to explore whether the dataset could be divided into more specific musical profiles. The eight cluster solution provided more detailed profiles of the audio features, which could then be explored in relation to the genre labels. Therefore, it was considered a better compromise between cluster quality and the level of detail provided by the clustering results.

AI Usage Statement

ChatGPT was used as a supporting tool during the preparation of this project. It helped with code explanations, improving the clarity of the written text and correcting grammatical errors. All data analysis, model selection and evaluation were conducted and reviewed by the author.

References

Caliński, T., & Harabasz, J. (1974). A dendrite method for cluster analysis. Communications in Statistics, 3(1), 1–27. https://doi.org/10.1080/03610927408827101

Davies, D. L., & Bouldin, D. W. (1979). A cluster separation measure. IEEE Transactions on Pattern Analysis and Machine Intelligence, PAMI-1(2), 224–227. https://doi.org/10.1109/TPAMI.1979.4766909

Hubert, L., & Arabie, P. (1985). Comparing partitions. Journal of Classification, 2, 193–218. https://doi.org/10.1007/BF01908075

Kaufman, L., & Rousseeuw, P. J. (1990). Finding groups in data: An introduction to cluster analysis. John Wiley & Sons. https://doi.org/10.1002/9780470316801

Rousseeuw, P. J. (1987). Silhouettes: A graphical aid to the interpretation and validation of cluster analysis. Journal of Computational and Applied Mathematics, 20, 53–65. https://doi.org/10.1016/0377-0427(87)90125-7

Scrucca, L., Fop, M., Murphy, T. B., & Raftery, A. E. (2016). mclust 5: Clustering, classification and density estimation using Gaussian finite mixture models. The R Journal, 8(1), 289–317. https://doi.org/10.32614/RJ-2016-021

Tibshirani, R., Walther, G., & Hastie, T. (2001). Estimating the number of clusters in a data set via the gap statistic. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 63(2), 411–423. https://doi.org/10.1111/1467-9868.00293

Schwarz, G. (1978). Estimating the dimension of a model. The Annals of Statistics, 6(2), 461–464. https://doi.org/10.1214/aos/1176344136

Hopkins, B., & Skellam, J. G. (1954). A new method for determining the type of distribution of plant individuals. Annals of Botany, 18(2), 213–227. https://doi.org/10.1093/oxfordjournals.aob.a083391

MacQueen, J. (1967). Some methods for classification and analysis of multivariate observations. In Proceedings of the Fifth Berkeley Symposium on Mathematical Statistics and Probability (Vol. 1, pp. 281–297).

Maharshi Pandya. (n.d.). Spotify tracks dataset [Data set]. Kaggle. https://www.kaggle.com/datasets/maharshipandya/-spotify-tracks-dataset