1. Introduction — Setting the Stage

1.1 Beyond Traditional Genre Boundaries

Music streaming platforms such as Spotify have transformed how people discover and experience music. With millions of songs available, listeners are no longer limited to traditional music genres. Personalized playlist, algorithm-driven recommendations, and social media trends have encouraged people to explore music across different styles and categories.

However, traditional genre labels such as Pop, Rap, Rock, Latin, R&B, and EDM may not fully capture the similarities between songs. For example, a Latin song and a Pop song might share similar levels of danceability, energy, and tempo despite belonging to different genres. This raises an important question: Can measurable audio characteristics reveal meaningful connections between songs that traditional genre classifications overlook?

This project investigates whether Spotify’s audio features can identify patterns and similarities across different music genres. Rather than relying exclusively on predefined genre labels, we aim to explore whether machine learning can uncover natural groupings of songs based on how they sound.

Understanding these relationships is relevant because music discovery plays an important role in the streaming experience. Identifying similarities across genres could provide useful insights into how songs are organized, how playlists are developed, and how listeners might discover music beyond their usual preferences.

1.2 What Are We Trying to Discover?

The primary objective of this project is to examine how Spotify’s measurable audio characteristics vary across music genres and determine whether unsupervised machine learning can identify meaningful groups of songs that extend beyond traditional genre classifications.

Specific Research Objectives

  1. Analyze audio characteristics across music genres. Examine how danceability, energy, valence, tempo, and acousticness differ among Pop, Rap, Rock, Latin, R&B, and EDM.

  2. Identify similarities and differences between genres. Determine which genres share similar audio profiles and which exhibit more distinctive musical characteristics.

  3. Discover hidden patterns using machine learning. Apply K-means clustering to group songs based on their audio features without using genre labels to form the clusters.

  4. Compare machine learning results with traditional genre classifications. Investigate whether the resulting clusters primarily contain songs from one genre or combine songs from multiple genres.

  5. Explore practical applications for music discovery. Evaluate how audio-based groupings could inform playlist organizations and provide a foundation for exploring alternative music recommendation strategies.

1.3 From Audio Features to Musical Insights

This study uses the Spotify Songs data set published through the TidyTuesday project on January 21, 2020. The data set was originally collected using the spotifyr package and contains information about songs, playlist genres, and measurable audio characteristics.

Our analysis focuses on six playlist genres: Pop, Rap, Rock, Latin, R&B, and EDM. The primary variables of interest include danceability, energy, valence, tempo, and acousticness.

The analysis was conducted in R and consisted of three main stages.

Stage 1: Data Preparation and Exploratory Data Analysis

Import and clean the dataset, examine missing values and duplicate observations, and calculate descriptive statistics. Visualizations such as boxplots, bar charts, and heatmaps helped compare audio characteristics across genres.

Stage 2: Machine Learning and Cluster Analysis

Use K-means clustering, an unsupervised machine learning technique that groups observations according to their similarities. Audio features were standardized before clustering to account for differences in measurement scales. We investigated an appropriate number of clusters and examine their characteristics to identify patterns in the data.

Stage 3: Interpretation and Genre Comparison

Compare the machine learning clusters with Spotify’s existing playlist genre classifications. This helped us evaluate whether audio-based groupings reflect traditional genre categories or reveal similarities across genre boundaries.

1.4 Why Musical Connections Matter

The results of this project could provide valuable insights for music streaming platforms, playlist curators, music marketers, and music listeners. For streaming platforms, understanding similarities between songs could help inform alternative approaches to organizing music libraries and developing playlists based on audio characteristics rather than genre classifications alone.

Playlist curators could potentially use these findings to identify songs from different genres that share similar musical qualities. For example, a workout playlist could include energetic songs from Pop, Latin, EDM, and Rap, even though they belong to different categories. Music marketers and artists could also benefit from understanding how musical characteristics vary across genres and where different styles overlap.

For listeners, the potential value lies in discovering music outside their familiar genres while maintaining similarities in musical characteristics they may enjoy. Although the data set doesn’t include individual listening preferences or recommendation outcomes, this analysis can provide an exploratory foundation for future research into audio-based music discovery.

Ultimately, this project aims to demonstrate how business analytics and machine learning can reveal patterns that are not immediately visible through traditional music classifications.

2. Packages Required — The Analytical Toolkit

To analyze the Spotify Songs data set, we used several R packages that support data preparation, exploratory data analysis, visualization, and machine learning.

These packages allowed us to examine the musical characteristics of songs across different genres, identify patterns within the dataset, and explore similarities using clustering techniques.

library(tidyverse)
library(janitor)
library(skimr)
library(knitr)
library(lubridate)
library(cluster)

tidyverse is used for data manipulation and visualization.

janitor helps examine data quality, clean variable names, and create frequency tables.

skimr provides details descriptive statistics and summaries of the data set.

knitr formats tables and generates the final R Markdown report.

lubridate is used for data manipulation specifically for dates and time.

cluster provides tools for evaluating clustering results, including silhouette analysis.

3. Data Preparation — Behind the Music

3.1 Where Does Our Data Come From?

The data used in this research was obtained from the Spotify Songs dataset, publicly available through the TidyTuesday project and published on January 21, 2020. The data was originally collected from Spotify’s Application Programming Interface (API) using the spotifyr R package, which provides access to song metadata and measurable audio characteristics.

The original data set is publicly available through the TidyTuesday GitHub repository

3.2 Understanding the Musical DNA

The original Spotify Songs dataset contains 32,833 observations and 23 variables, including song metadata, playlist information, genre classifications, and numerical audio features.

Each observation represents a track within a playlist entry rather than necessarily a unique song. The dataset encompasses six traditional playlist genres: EDM, Latin, Pop, R&B, Rap, and Rock.

For this research, five audio characteristics were selected as the primary variables of interest:

Danceability: A score from 0 to 1 describing how suitable a song is for dancing.

Energy: A score from 0 to 1 measuring musical intensity and activity.

Valence: A score from 0 to 1 representing the musical positivity of a song.

Tempo: The estimated speed of a song, measured in beats per minute.

Acousticness: A score from 0 to 1 representing confidence that a track is acoustic.

These variables were selected because they capture complementary dimensions of music, including rhythm, intensity, emotional tone, speed, and acoustic qualities.

The original data set also contains missing values in song metadata and repeated track IDs, indicating that some songs appear in multiple playlist entries. These characteristics require careful treatment to preserve meaningful genre relationships while preventing duplicate tracks from disproportionately influencing the machine learning analysis.

These considerations guided the data preparation and validation process before conducting exploratory data analysis and clustering.

3.3 From Raw Data to Reliable Insights

Importing the data:

spotify <- 
  read.csv("spotify_songs.csv")

View the structure of the data set:

## 'data.frame':    32833 obs. of  23 variables:
##  $ track_id                : chr  "6f807x0ima9a1j3VPbc7VN" "0r7CVbZTWZgbTCYdfa2P31" "1z1Hg7Vb0AhHDiEmnDE79l" "75FpbthrwQmzHlBJLuGdC7" ...
##  $ track_name              : chr  "I Don't Care (with Justin Bieber) - Loud Luxury Remix" "Memories - Dillon Francis Remix" "All the Time - Don Diablo Remix" "Call You Mine - Keanu Silva Remix" ...
##  $ track_artist            : chr  "Ed Sheeran" "Maroon 5" "Zara Larsson" "The Chainsmokers" ...
##  $ track_popularity        : int  66 67 70 60 69 67 62 69 68 67 ...
##  $ track_album_id          : chr  "2oCs0DGTsRO98Gh5ZSl2Cx" "63rPSO264uRjW1X5E6cWv6" "1HoSmj2eLcsrR0vE9gThr4" "1nqYsOef1yKKuGOVchbsk6" ...
##  $ track_album_name        : chr  "I Don't Care (with Justin Bieber) [Loud Luxury Remix]" "Memories (Dillon Francis Remix)" "All the Time (Don Diablo Remix)" "Call You Mine - The Remixes" ...
##  $ track_album_release_date: chr  "2019-06-14" "2019-12-13" "2019-07-05" "2019-07-19" ...
##  $ playlist_name           : chr  "Pop Remix" "Pop Remix" "Pop Remix" "Pop Remix" ...
##  $ playlist_id             : chr  "37i9dQZF1DXcZDD7cfEKhW" "37i9dQZF1DXcZDD7cfEKhW" "37i9dQZF1DXcZDD7cfEKhW" "37i9dQZF1DXcZDD7cfEKhW" ...
##  $ playlist_genre          : chr  "pop" "pop" "pop" "pop" ...
##  $ playlist_subgenre       : chr  "dance pop" "dance pop" "dance pop" "dance pop" ...
##  $ danceability            : num  0.748 0.726 0.675 0.718 0.65 0.675 0.449 0.542 0.594 0.642 ...
##  $ energy                  : num  0.916 0.815 0.931 0.93 0.833 0.919 0.856 0.903 0.935 0.818 ...
##  $ key                     : int  6 11 1 7 1 8 5 4 8 2 ...
##  $ loudness                : num  -2.63 -4.97 -3.43 -3.78 -4.67 ...
##  $ mode                    : int  1 1 0 1 1 1 0 0 1 1 ...
##  $ speechiness             : num  0.0583 0.0373 0.0742 0.102 0.0359 0.127 0.0623 0.0434 0.0565 0.032 ...
##  $ acousticness            : num  0.102 0.0724 0.0794 0.0287 0.0803 0.0799 0.187 0.0335 0.0249 0.0567 ...
##  $ instrumentalness        : num  0.00 4.21e-03 2.33e-05 9.43e-06 0.00 0.00 0.00 4.83e-06 3.97e-06 0.00 ...
##  $ liveness                : num  0.0653 0.357 0.11 0.204 0.0833 0.143 0.176 0.111 0.637 0.0919 ...
##  $ valence                 : num  0.518 0.693 0.613 0.277 0.725 0.585 0.152 0.367 0.366 0.59 ...
##  $ tempo                   : num  122 100 124 122 124 ...
##  $ duration_ms             : int  194754 162600 176616 169093 189052 163049 187675 207619 193187 253040 ...

View the dimensions of the data set:

## [1] 32833    23

View the summary statistics of the data set:

##       track_id         track_name       track_artist   track_popularity
##  Length   :32833   Length   :32833   Length   :32833   Min.   :  0.00  
##  N.unique :28356   N.unique :23449   N.unique :10692   1st Qu.: 24.00  
##  N.blank  :    0   N.blank  :    0   N.blank  :    0   Median : 45.00  
##  Min.nchar:   22   Min.nchar:    1   Min.nchar:    2   Mean   : 42.48  
##  Max.nchar:   22   Max.nchar:  144   Max.nchar:   69   3rd Qu.: 62.00  
##                    NAs      :    5   NAs      :    5   Max.   :100.00  
##    track_album_id   track_album_name track_album_release_date   playlist_name  
##  Length   :32833   Length   :32833   Length   :32833          Length   :32833  
##  N.unique :22545   N.unique :19743   N.unique : 4530          N.unique :  449  
##  N.blank  :    0   N.blank  :    0   N.blank  :    0          N.blank  :    0  
##  Min.nchar:   22   Min.nchar:    1   Min.nchar:    4          Min.nchar:    6  
##  Max.nchar:   22   Max.nchar:  151   Max.nchar:   10          Max.nchar:  122  
##                    NAs      :    5                                             
##     playlist_id      playlist_genre  playlist_subgenre  danceability   
##  Length   :32833   Length   :32833   Length   :32833   Min.   :0.0000  
##  N.unique :  471   N.unique :    6   N.unique :   24   1st Qu.:0.5630  
##  N.blank  :    0   N.blank  :    0   N.blank  :    0   Median :0.6720  
##  Min.nchar:   22   Min.nchar:    3   Min.nchar:    4   Mean   :0.6548  
##  Max.nchar:   22   Max.nchar:    5   Max.nchar:   25   3rd Qu.:0.7610  
##                                                        Max.   :0.9830  
##      energy              key            loudness            mode       
##  Min.   :0.000175   Min.   : 0.000   Min.   :-46.448   Min.   :0.0000  
##  1st Qu.:0.581000   1st Qu.: 2.000   1st Qu.: -8.171   1st Qu.:0.0000  
##  Median :0.721000   Median : 6.000   Median : -6.166   Median :1.0000  
##  Mean   :0.698619   Mean   : 5.374   Mean   : -6.719   Mean   :0.5657  
##  3rd Qu.:0.840000   3rd Qu.: 9.000   3rd Qu.: -4.645   3rd Qu.:1.0000  
##  Max.   :1.000000   Max.   :11.000   Max.   :  1.275   Max.   :1.0000  
##   speechiness      acousticness    instrumentalness       liveness     
##  Min.   :0.0000   Min.   :0.0000   Min.   :0.0000000   Min.   :0.0000  
##  1st Qu.:0.0410   1st Qu.:0.0151   1st Qu.:0.0000000   1st Qu.:0.0927  
##  Median :0.0625   Median :0.0804   Median :0.0000161   Median :0.1270  
##  Mean   :0.1071   Mean   :0.1753   Mean   :0.0847472   Mean   :0.1902  
##  3rd Qu.:0.1320   3rd Qu.:0.2550   3rd Qu.:0.0048300   3rd Qu.:0.2480  
##  Max.   :0.9180   Max.   :0.9940   Max.   :0.9940000   Max.   :0.9960  
##     valence           tempo         duration_ms    
##  Min.   :0.0000   Min.   :  0.00   Min.   :  4000  
##  1st Qu.:0.3310   1st Qu.: 99.96   1st Qu.:187819  
##  Median :0.5120   Median :121.98   Median :216000  
##  Mean   :0.5106   Mean   :120.88   Mean   :225800  
##  3rd Qu.:0.6930   3rd Qu.:133.92   3rd Qu.:253585  
##  Max.   :0.9910   Max.   :239.44   Max.   :517810

Identifying Missing Information

missing_values <- spotify %>%
  summarise(across(
    everything(),
    ~ sum(is.na(.x))
  )) %>%
  pivot_longer(
    everything(),
    names_to = "variable",
    values_to = "missing_count"
  )

missing_values %>%
  filter(missing_count > 0) %>%
  kable()
variable missing_count
track_name 5
track_artist 5
track_album_name 5
  • There are 15 missing values; track_name, track_artist, and track_album_name - there are 5 in each column and we want to remove these.

Identifying Repeated Tracks

duplicate_count <- sum(
  duplicated(spotify$track_id)
)

head(duplicate_count) 
## [1] 4477

Refining the Data set

# Select the audio features used throughout the analysis
audio_features <- c(
  "danceability", "energy", "valence",
  "tempo", "acousticness"
)

bounded_features <- setdiff(audio_features, "tempo")

# Retain observations with valid audio characteristics
spotify_valid <- spotify %>%
  filter(
    !is.na(track_id),
    !is.na(playlist_genre),
    if_all(all_of(audio_features), ~ is.finite(.x)),
    if_all(all_of(bounded_features),
           ~ between(.x, 0, 1)),
    tempo > 0
  )

# Preserve unique track-genre combinations
spotify_genres <- spotify_valid %>%
  distinct(track_id, playlist_genre, .keep_all = TRUE)

# Preserve genre memberships for later comparison
genre_membership <- spotify_genres %>%
  select(track_id, playlist_genre)

# Create one observation per unique track
spotify_model <- spotify_valid %>%
  distinct(track_id, .keep_all = TRUE) %>%
  select(
    track_id, track_name, track_artist,
    all_of(audio_features)
  )

# Standardize features for K-means clustering
spotify_scaled <- spotify_model %>%
  select(all_of(audio_features)) %>%
  scale()

# Verify that each modeling observation is unique
stopifnot(
  anyDuplicated(spotify_model$track_id) == 0,
  all(is.finite(spotify_scaled))
)

# Summarize the data preparation process
tibble(
  Dataset = c(
    "Original playlist entries",
    "Valid playlist entries",
    "Unique track-genre combinations",
    "Unique tracks for modeling"
  ),
  Observations = c(
    nrow(spotify),
    nrow(spotify_valid),
    nrow(spotify_genres),
    nrow(spotify_model)
  )
) %>%
  kable(caption = "Data Preparation Results")
Data Preparation Results
Dataset Observations
Original playlist entries 32833
Valid playlist entries 32832
Unique track-genre combinations 30384
Unique tracks for modeling 28355

The original data set contains repeated track IDs because individual songs may appear in multiple playlists or genre categories. To prevent repeated observations from disproportionately influencing the analysis, we created two separate data sets.

The first data set contains 30,384 unique track-genre combinations and is used to compare musical characteristics across genres. The second data set contains 28,355 unique tracks and is used for machine learning.

Observations with invalid or missing audio characteristics were excluded. Missing song metadata was retained when the information required for the analysis was available.

The selected audio features were standardized before clustering to ensure that differences in measurement scales did not disproportionately influence the results.

Validating Audio Characteristics

# Define the selected audio features
audio_features <- c(
  "danceability",
  "energy",
  "valence",
  "tempo",
  "acousticness"
)

# Check for missing values in the selected audio features
spotify %>%
  summarise(across(
    all_of(audio_features),
    ~ sum(is.na(.x))
  )) %>%
  kable(caption = "Missing Values in Audio Features")
Missing Values in Audio Features
danceability energy valence tempo acousticness
0 0 0 0 0

Ensuring Valid Audio Feature Ranges

bounded_features <- setdiff(
  audio_features, "tempo"
)
bounded_features
## [1] "danceability" "energy"       "valence"      "acousticness"
spotify %>%
  summarise(across(
    all_of(bounded_features),
    ~ sum(.x < 0 | .x > 1, na.rm = TRUE)
  )) %>%
  kable()
danceability energy valence acousticness
0 0 0 0

Checking the Rhythm: Tempo Validation

spotify %>%
  filter(tempo <= 0 | is.na(tempo)) %>%
  select(track_id, track_name, tempo) %>%
  kable()
track_id track_name tempo
51w6nRCU68klqNfYaaVP2j Hi, How’re You Doin’? 0

Final Data Quality Verification

# Verify the cleaned data sets
stopifnot(
  anyDuplicated(spotify_model$track_id) == 0,
  all(is.finite(spotify_scaled))
)

# Display final data set sizes
tibble(
  Dataset = c(
    "Original Dataset",
    "Genre Comparison Dataset",
    "Clustering Dataset"
  ),
  Observations = c(
    nrow(spotify),
    nrow(spotify_genres),
    nrow(spotify_model)
  )
) %>%
  kable(caption = "Final Data Preparation Results")
Final Data Preparation Results
Dataset Observations
Original Dataset 32833
Genre Comparison Dataset 30384
Clustering Dataset 28355

After validating the selected audio features, we created two separate datasets to address the different objectives of our analysis.

The first data set, spotify_genres, preserves unique track-genre combinations and will be used to compare musical characteristics across genres.

The second data set, spotify_model, contains one observation per unique track to prevent repeated songs from influencing the clustering algorithm.

Finally, the selected audio features were standardized to ensure that variables measured on different scales, particularly tempo, do not disproportionately influence the K-means clustering results.

3.4 The Music Behind Our Analysis

spotify_model %>%
  select(
    track_name,
    danceability,
    energy,
    valence,
    tempo,
    acousticness
  ) %>%
  head(6) %>%
  kable(
    digits = 2,
    caption = "Preview of the Cleaned Spotify Dataset"
  )
Preview of the Cleaned Spotify Dataset
track_name danceability energy valence tempo acousticness
I Don’t Care (with Justin Bieber) - Loud Luxury Remix 0.75 0.92 0.52 122.04 0.10
Memories - Dillon Francis Remix 0.73 0.81 0.69 99.97 0.07
All the Time - Don Diablo Remix 0.68 0.93 0.61 124.01 0.08
Call You Mine - Keanu Silva Remix 0.72 0.93 0.28 121.96 0.03
Someone You Loved - Future Humans Remix 0.65 0.83 0.72 123.98 0.08
Beautiful People (feat. Khalid) - Jack Wins Remix 0.68 0.92 0.58 124.98 0.08

3.5 A First Look at the Musical Landscape

summary_table <- spotify_model %>%
  summarise(across(
    all_of(audio_features),
    list(
      mean = ~ mean(.x, na.rm = TRUE),
      median = ~ median(.x, na.rm = TRUE),
      sd = ~ sd(.x, na.rm = TRUE)
    )
  )) %>%
  pivot_longer(
    everything(),
    names_to = c("variable", ".value"),
    names_pattern = "(.+)_(mean|median|sd)"
  )

summary_table %>%
  kable(
    digits = 3,
    caption = "Descriptive Statistics of Spotify Audio Features"
  )
Descriptive Statistics of Spotify Audio Features
variable mean median sd
danceability 0.653 0.670 0.146
energy 0.698 0.722 0.183
valence 0.510 0.512 0.234
tempo 120.960 121.993 26.945
acousticness 0.177 0.080 0.223

The descriptive statistics indicate that the songs in the dataset generally exhibit moderately high danceability and energy levels.

Across the 28,355 unique tracks, average danceability is approximately 0.653, while average energy is 0.698.

The mean valence score of 0.510 suggests that the data set contains a mixture of songs with positive and negative musical characteristics, with the overall average near the midpoint of the scale.

The average tempo is approximately 121 beats per minute, although considerable variation exists across songs.

Acousticness has a mean of 0.177 and a median of 0.080, indicating that many songs have relatively low acousticness scores, while some songs have substantially higher values.

These initial findings provide a foundation for investigating how musical characteristics differ across genres. In the next stage, we will examine whether combinations of these features reveal distinct groups of songs that may extend beyond traditional genre classifications.

4. Exploratory Data Analysis — Exploring the Musical Landscape

The exploratory data analysis investigates the relationships between musical genres and their underlying audio characteristics. Rather than relying exclusively on traditional genre classifications, this analysis examines whether songs share measurable similarities across different musical categories.

Through descriptive statistics, comparative visualizations, correlation analysis, and genre overlap analysis, we aim to identify patterns that may not be immediately apparent from conventional genre labels. These findings will provide the foundation for the subsequent unsupervised machine learning analysis.

The exploratory analysis addresses two central questions:

  1. How do audio characteristics differ across traditional music genres?
  2. Which genres share similar audio profiles despite having different classifications?

4.1 What Makes Each Music Genre Unique?

We begin by examining how the five selected audio characteristics vary across the six music genres. Comparing danceability, energy, valence, tempo, and acousticness allows us to identify distinctive musical profiles while also exploring potential similarities between genres that are traditionally considered different.

genre_summary <- spotify_genres %>%
  group_by(playlist_genre) %>%
  summarise(
    Tracks = n(),
    across(all_of(audio_features), mean),
    .groups = "drop"
  )

genre_summary %>%
  kable(
    digits = 3,
    col.names = c(
      "Genre", "Tracks", "Danceability",
      "Energy", "Valence", "Tempo",
      "Acousticness"
    ),
    caption = "Average Audio Characteristics by Music Genre"
  )
Average Audio Characteristics by Music Genre
Genre Tracks Danceability Energy Valence Tempo Acousticness
edm 5537 0.658 0.799 0.406 125.649 0.085
latin 4641 0.711 0.708 0.600 118.610 0.211
pop 5132 0.638 0.701 0.502 120.963 0.172
r&b 5138 0.670 0.593 0.532 114.306 0.259
rap 5486 0.716 0.650 0.505 120.694 0.196
rock 4450 0.520 0.733 0.535 125.093 0.147

Average danceability by genre

ggplot(
  genre_summary,
  aes(
    x = reorder(playlist_genre, danceability),
    y = danceability
  )
) +
  geom_col(fill = "#1DB954", width = 0.65) +
  geom_text(
    aes(label = round(danceability, 3)),
    hjust = -0.2,
    size = 3.5
  ) +
  coord_flip() +
  scale_y_continuous(limits = c(0, 1)) +
  labs(
    title = "Which Genres Are the Most Danceable?",
    subtitle = "Average danceability across six Spotify genres",
    x = NULL,
    y = "Average Danceability",
    caption = "Source: Spotify Songs Dataset"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(face = "bold", size = 15),
    panel.grid.major.y = element_blank()
  )

Distribution of danceability by genre

ggplot(
  spotify_genres,
  aes(
    x = reorder(playlist_genre, danceability, median),
    y = danceability,
    fill = playlist_genre
  )
) +
  geom_boxplot(alpha = 0.8, outlier.alpha = 0.2) +
  scale_fill_brewer(palette = "Set2") +
  coord_flip() +
  labs(
    title = "Beyond the Average: Danceability Across Genres",
    subtitle = "Examining variability and overlap between genres",
    x = NULL,
    y = "Danceability",
    caption = "Source: Spotify Songs Dataset"
  ) +
  theme_minimal() +
  theme(
    legend.position = "none",
    plot.title = element_text(face = "bold", size = 15),
    panel.grid.major.y = element_blank()
  )

The results reveal both distinctive musical characteristics and unexpected similarities across genres. Rap and Latin music exhibit the highest average danceability scores, suggesting that these traditionally distinct genres share similar rhythmic characteristics. Rock, in contrast, demonstrates the lowest average danceability.

EDM exhibits the highest average energy and the lowest acousticness, reflecting its predominantly electronic and energetic musical characteristics. R&B demonstrates the lowest average energy and the highest acousticness among the six genres. Latin music also exhibits the highest average valence, suggesting a more positive musical tone.

These preliminary findings suggest that traditional genre classifications may not fully capture the underlying similarities between songs. In particular, the comparable danceability scores of Rap and Latin music provide an initial indication that musical connections may extend beyond conventional genre boundaries.

4.2 Which Music Genres Are More Similar Than Expected?

While individual audio characteristics provide valuable insights into musical differences, analyzing multiple features simultaneously offers a more comprehensive understanding of genre similarities. To investigate hidden connections between genres, we compare standardized audio profiles across the six musical categories.

Standardization ensures that all five audio features contribute on a comparable scale, regardless of their original units of measurement. A heatmap and a Euclidean distance matrix are used to identify genres that share similar musical characteristics despite belonging to different traditional classifications.

Standardized audio profiles

# Combine standardized audio features with track IDs
standardized_tracks <- as_tibble(spotify_scaled) %>%
  mutate(track_id = spotify_model$track_id)

# Calculate standardized audio profiles by genre
genre_profiles <- standardized_tracks %>%
  inner_join(genre_membership, by = "track_id") %>%
  group_by(playlist_genre) %>%
  summarise(
    across(all_of(audio_features), mean),
    .groups = "drop"
  )

# Reshape data for visualization
genre_heatmap <- genre_profiles %>%
  pivot_longer(
    cols = all_of(audio_features),
    names_to = "Feature",
    values_to = "Score"
  )

Create the Heatmap

# Visualize standardized genre profiles
ggplot(
  genre_heatmap,
  aes(x = Feature, y = playlist_genre, fill = Score)
) +
  geom_tile(color = "white", linewidth = 1) +
  geom_text(
    aes(label = sprintf("%.2f", Score)),
    size = 4
  ) +
  scale_fill_gradient2(
    low = "#4575B4",
    mid = "white",
    high = "#1DB954",
    midpoint = 0,
    name = "Z-score"
  ) +
  labs(
    title = "The Musical DNA of Spotify Genres",
    subtitle = "Standardized audio profiles across six music genres",
    x = NULL,
    y = NULL,
    caption = "Source: Spotify Songs Dataset"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(face = "bold", size = 15),
    panel.grid = element_blank(),
    axis.text.x = element_text(angle = 30, hjust = 1)
  )

The standardized audio profiles reveal that musical genres exhibit both similarities and differences relative to the overall dataset average. Rap and Latin music share above-average danceability, while EDM and Rock demonstrate above-average energy and tempo. R&B stands out for its above-average acousticness and below-average energy, whereas Pop maintains a relatively neutral profile across all five audio characteristics.

These findings suggest that genres traditionally classified as different can share common musical attributes. However, similarity in individual audio features does not necessarily indicate overall musical similarity. Therefore, further analysis using Euclidean distance is necessary to determine which genres are most closely related across all five standardized features.

Genre Similarity Distance Matrix

To quantify the similarities observed in the standardized audio profiles, we calculate the Euclidean distance between each pair of music genres. Smaller distances indicate greater similarity across the five selected audio characteristics, while larger distances indicate greater differences in their overall musical profiles.

Euclidean distance Matrix

# Convert genre profiles into a numeric matrix
profile_matrix <- genre_profiles %>%
  column_to_rownames("playlist_genre") %>%
  as.matrix()

# Calculate Euclidean distances between genres
genre_distances <- as.matrix(
  dist(profile_matrix, method = "euclidean")
)

# Display the genre similarity matrix
genre_distances %>%
  kable(
    digits = 3,
    caption = "Euclidean Distances Between Music Genres"
  )
Euclidean Distances Between Music Genres
edm latin pop r&b rap rock
edm 0.000 1.207 0.810 1.533 1.132 1.184
latin 1.207 0.000 0.682 0.790 0.526 1.395
pop 0.810 0.682 0.000 0.792 0.614 0.859
r&b 1.533 0.790 0.792 0.000 0.589 1.434
rap 1.132 0.526 0.614 0.589 0.000 1.451
rock 1.184 1.395 0.859 1.434 1.451 0.000

Top Five Musical Connections

# Extract unique genre pairs and their distances
genre_connections <- as.data.frame(
  as.table(genre_distances)
) %>%
  as_tibble() %>%
  rename(
    Genre_1 = Var1,
    Genre_2 = Var2,
    Distance = Freq
  ) %>%
  filter(
    as.character(Genre_1) < as.character(Genre_2)
  ) %>%
  arrange(Distance)

# Display the five most similar genre pairs
genre_connections %>%
  slice_head(n = 5) %>%
  kable(
    digits = 3,
    caption = "Top Five Musical Connections Between Genres"
  )
Top Five Musical Connections Between Genres
Genre_1 Genre_2 Distance
latin rap 0.526
r&b rap 0.589
pop rap 0.614
latin pop 0.682
latin r&b 0.790

The Euclidean distance analysis identifies Latin and Rap as the most similar genre pair, with a distance of approximately 0.526, followed by R&B and Rap (0.589) and Pop and Rap (0.614).

Interestingly, Rap appears in the three strongest musical connections, suggesting that its average audio characteristics share common elements with several other genres. In contrast, EDM and R&B demonstrate the greatest distance (1.533), reflecting substantial differences in their overall audio profiles, particularly in energy and acousticness.

These findings support the central premise of our research: traditional genre classifications do not necessarily capture all underlying musical similarities. The presence of measurable connections between different genres provides motivation for applying unsupervised machine learning to explore alternative ways of grouping songs based on their audio characteristics.

However, these comparisons are based on average genre profiles and do not imply that every song within two similar genres shares the same musical characteristics.

4.4 Can a Song Belong to More Than One Genre?

Traditional music classifications often assign songs to specific genres. However, the evolution of contemporary music and the combination of different musical influences may challenge these conventional boundaries.

To investigate this phenomenon, we examine whether individual tracks appear across multiple playlist genre classifications within the Spotify dataset. By identifying the extent of genre overlap, this analysis evaluates whether traditional genre labels provide a complete representation of musical identity and establishes further motivation for exploring alternative, feature-based classification methods through unsupervised machine learning.

Single-Genre vs. Multi-Genre Tracks

# Calculate the number of distinct genres per track
genre_overlap <- genre_membership %>%
  group_by(track_id) %>%
  summarise(
    number_of_genres = n_distinct(playlist_genre),
    .groups = "drop"
  )

# Classify tracks based on genre membership
overlap_summary <- genre_overlap %>%
  mutate(
    classification = if_else(
      number_of_genres > 1,
      "Multiple Genres",
      "Single Genre"
    )
  ) %>%
  count(classification, name = "Tracks") %>%
  mutate(
    Percentage = 100 * Tracks / sum(Tracks)
  )

# Display summary table
overlap_summary %>%
  kable(
    digits = 2,
    col.names = c("Classification", "Tracks", "Percentage (%)"),
    caption = "Distribution of Tracks Across Genre Classifications"
  )
Distribution of Tracks Across Genre Classifications
Classification Tracks Percentage (%)
Multiple Genres 1687 5.95
Single Genre 26668 94.05
# Visualize single-genre and multi-genre tracks
ggplot(
  overlap_summary,
  aes(
    x = classification,
    y = Percentage,
    fill = classification
  )
) +
  geom_col(width = 0.6) +
  geom_text(
    aes(label = sprintf("%.2f%%", Percentage)),
    vjust = -0.5,
    size = 5,
    fontface = "bold"
  ) +
  scale_fill_manual(
    values = c(
      "Single Genre" = "#191414",
      "Multiple Genres" = "#1DB954"
    )
  ) +
  scale_y_continuous(limits = c(0, 105)) +
  labs(
    title = "Beyond Traditional Genre Boundaries",
    subtitle = "Percentage of tracks associated with one or multiple genres",
    x = NULL,
    y = "Percentage of Tracks (%)",
    caption = "Source: Spotify Songs Dataset | 28,355 unique tracks"
  ) +
  theme_minimal() +
  theme(
    legend.position = "none",
    plot.title = element_text(face = "bold", size = 15),
    panel.grid.major.x = element_blank(),
    panel.grid.minor = element_blank()
  )

The analysis reveals that 94.05% of the tracks are associated with a single playlist genre, while 5.95%, representing 1,687 unique songs, appear across multiple genre classifications.

Although multi-genre tracks represent a relatively small proportion of the dataset, their presence demonstrates that playlist genre boundaries are not always mutually exclusive. This overlap suggests that traditional genre labels may not fully capture the diversity of musical characteristics present in individual songs.

However, these results reflect playlist genre membership within the available dataset rather than definitive artistic genre classifications. A track appearing under a single genre does not necessarily mean that it lacks characteristics associated with other genres.

How Many Genres Can One Song Belong To?

To further investigate the complexity of musical classification, we examine the distribution of tracks according to the number of distinct playlist genres in which they appear. This analysis provides a more detailed understanding of genre overlap and identifies whether certain songs extend beyond two traditional genre categories.

Distribution of genre membership

# Count tracks by number of associated genres
genre_count_summary <- genre_overlap %>%
  count(number_of_genres, name = "Tracks") %>%
  mutate(
    Percentage = 100 * Tracks / sum(Tracks)
  ) %>%
  arrange(number_of_genres)

# Display genre membership distribution
genre_count_summary %>%
  kable(
    digits = 2,
    col.names = c(
      "Number of Genres",
      "Tracks",
      "Percentage (%)"
    ),
    caption = "Number of Distinct Genres Associated with Each Track"
  )
Number of Distinct Genres Associated with Each Track
Number of Genres Tracks Percentage (%)
1 26668 94.05
2 1422 5.01
3 195 0.69
4 63 0.22
5 7 0.02

Visualize multi-genre tracks

# Focus on tracks associated with multiple genres
ggplot(
  genre_count_summary %>%
    filter(number_of_genres > 1),
  aes(x = factor(number_of_genres), y = Tracks)
) +
  geom_col(
    fill = "#1DB954",
    width = 0.6
  ) +
  geom_text(
    aes(label = scales::comma(Tracks)),
    vjust = -0.5,
    size = 4,
    fontface = "bold"
  ) +
  scale_y_continuous(
    labels = scales::comma,
    expand = expansion(mult = c(0, 0.15))
  ) +
  labs(
    title = "How Many Genres Can One Song Belong To?",
    subtitle = "Distribution of tracks with multiple genre memberships",
    x = "Number of Distinct Genres",
    y = "Number of Tracks",
    caption = "Source: Spotify Songs Dataset | Multi-genre tracks only"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(face = "bold", size = 15),
    panel.grid.major.x = element_blank(),
    panel.grid.minor = element_blank()
  )

The distribution of multi-genre tracks provides additional evidence that musical classifications are not always exclusive. The presence of songs across different playlist genres highlights the complexity of assigning music to predefined categories.

From a business analytics perspective, this overlap presents an opportunity for music streaming platforms to explore recommendation strategies that extend beyond conventional genre labels. Grouping songs according to their underlying audio characteristics could potentially support more diverse music discovery experiences and personalized playlist recommendations.

5. Unsupervised Machine Learning — Discovering Hidden Musical Groups

Following the exploratory data analysis, this section applies unsupervised machine learning to investigate whether songs can be grouped according to their underlying audio characteristics rather than their traditional genre classifications.

K-means clustering is selected as the primary analytical technique because of its ability to identify groups of observations based on similarities across multiple numerical variables. The model incorporates five standardized audio features: danceability, energy, valence, tempo, and acousticness.

Importantly, existing genre labels are excluded from the clustering process to allow the algorithm to identify patterns independently of conventional musical classifications. The resulting clusters are subsequently evaluated, visualized, and compared with existing playlist genres to determine whether meaningful alternative musical groupings can be identified.

From a business analytics perspective, this approach could provide valuable insights for music streaming platforms seeking to enhance personalized recommendations, playlist generation, and cross-genre music discovery.

5.1 How Many Musical Groups Naturally Emerge?

Determining an appropriate number of clusters is an essential step in K-means clustering. Rather than assuming that the optimal number of clusters corresponds to the six existing music genres, this analysis evaluates multiple clustering solutions to identify a suitable grouping structure based on the audio characteristics of the songs.

The Elbow Method and Silhouette Analysis are employed to evaluate clustering solutions ranging from two to eight clusters. The Elbow Method examines within-cluster variation, while Silhouette Analysis evaluates how closely observations resemble their assigned clusters relative to neighboring clusters.

Using both techniques provides a systematic approach to model selection and reduces reliance on arbitrary assumptions regarding the number of musical groups.

Elbow Method

# Ensure reproducibility
set.seed(42)

# Define candidate numbers of clusters
k_values <- 2:8

# Fit K-means models using all standardized tracks
kmeans_models <- lapply(
  k_values,
  function(k) {
    kmeans(
      spotify_scaled,
      centers = k,
      nstart = 25,
      iter.max = 100
    )
  }
)
## Warning: Quick-TRANSfer stage steps exceeded maximum (= 1417750)
## Warning: Quick-TRANSfer stage steps exceeded maximum (= 1417750)
## Warning: Quick-TRANSfer stage steps exceeded maximum (= 1417750)
## Warning: Quick-TRANSfer stage steps exceeded maximum (= 1417750)
## Warning: Quick-TRANSfer stage steps exceeded maximum (= 1417750)
## Warning: Quick-TRANSfer stage steps exceeded maximum (= 1417750)
## Warning: Quick-TRANSfer stage steps exceeded maximum (= 1417750)
## Warning: Quick-TRANSfer stage steps exceeded maximum (= 1417750)
## Warning: Quick-TRANSfer stage steps exceeded maximum (= 1417750)
## Warning: Quick-TRANSfer stage steps exceeded maximum (= 1417750)
## Warning: Quick-TRANSfer stage steps exceeded maximum (= 1417750)
# Extract within-cluster sum of squares
cluster_evaluation <- tibble(
  k = k_values,
  WSS = sapply(
    kmeans_models,
    function(model) model$tot.withinss
  )
)
# Visualize within-cluster variation
ggplot(
  cluster_evaluation,
  aes(x = k, y = WSS)
) +
  geom_line(
    color = "#1DB954",
    linewidth = 1.2
  ) +
  geom_point(
    color = "#191414",
    size = 3
  ) +
  scale_x_continuous(breaks = k_values) +
  scale_y_continuous(labels = scales::comma) +
  labs(
    title = "Finding the Optimal Number of Musical Groups",
    subtitle = "Elbow Method for K-means clustering",
    x = "Number of Clusters (K)",
    y = "Within-Cluster Sum of Squares",
    caption = "Source: Spotify Songs Dataset"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(face = "bold", size = 15),
    panel.grid.minor = element_blank()
  )

The Elbow Method illustrates the relationship between the number of clusters and within-cluster variation. As the number of clusters increases, the total within-cluster sum of squares decreases, reflecting greater similarity among observations within each group.

However, increasing the number of clusters also increases model complexity. The objective is therefore to identify a point at which additional clusters provide diminishing improvements in within-cluster cohesion. Because the elbow may not be clearly defined, Silhouette Analysis is also conducted to provide a complementary quantitative evaluation of clustering quality.

Silhouette Analysis

To complement the Elbow Method, Silhouette Analysis is used to evaluate the cohesion and separation of the identified clusters. Silhouette scores range from −1 to 1, with higher values indicating that observations are more similar to their assigned cluster than to neighboring clusters.

This method provides a quantitative measure of clustering quality and supports the selection of an appropriate number of musical groups.

# Create a reproducible evaluation sample
set.seed(42)

sample_index <- sample(
  seq_len(nrow(spotify_scaled)),
  size = min(3000, nrow(spotify_scaled))
)

# Calculate distances between sampled tracks
sample_distances <- dist(
  spotify_scaled[sample_index, , drop = FALSE]
)

# Calculate average silhouette scores
cluster_evaluation <- cluster_evaluation %>%
  mutate(
    Silhouette = sapply(
      kmeans_models,
      function(model) {
        mean(
          cluster::silhouette(
            model$cluster[sample_index],
            sample_distances
          )[, 3]
        )
      }
    )
  )

# Display model evaluation results
cluster_evaluation %>%
  kable(
    digits = 3,
    col.names = c(
      "Number of Clusters",
      "Within-Cluster Sum of Squares",
      "Average Silhouette Score"
    ),
    caption = "Evaluation of K-means Clustering Solutions"
  )
Evaluation of K-means Clustering Solutions
Number of Clusters Within-Cluster Sum of Squares Average Silhouette Score
2 111590.00 0.259
3 89030.49 0.220
4 78549.16 0.213
5 70755.99 0.198
6 66061.59 0.195
7 61876.90 0.192
8 57777.61 0.194

All K-means clustering models are trained using the complete cleaned dataset of 28,355 unique tracks. However, because Silhouette Analysis requires pairwise distance calculations, a reproducible random sample of 3,000 observations is used to approximate clustering quality and reduce computational requirements. The same sample is applied across all candidate models to ensure consistency in model comparison.

# Identify the model with the highest silhouette score
best_k <- cluster_evaluation$k[
  which.max(cluster_evaluation$Silhouette)
]

# Visualize silhouette scores
ggplot(
  cluster_evaluation,
  aes(x = k, y = Silhouette)
) +
  geom_line(
    color = "#1DB954",
    linewidth = 1.2
  ) +
  geom_point(
    color = "#191414",
    size = 3
  ) +
  geom_vline(
    xintercept = best_k,
    linetype = "dashed",
    color = "#4575B4"
  ) +
  geom_text(
    aes(label = sprintf("%.3f", Silhouette)),
    vjust = -1,
    size = 3.5
  ) +
  scale_x_continuous(breaks = k_values) +
  scale_y_continuous(
    expand = expansion(mult = c(0.1, 0.2))
  ) +
  labs(
    title = "How Well Are Musical Groups Separated?",
    subtitle = "Average silhouette scores across clustering solutions",
    x = "Number of Clusters (K)",
    y = "Average Silhouette Score",
    caption = "Source: Spotify Songs Dataset"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(face = "bold", size = 15),
    panel.grid.minor = element_blank()
  )

# Display the selected clustering solution
cluster_evaluation %>%
  filter(k == best_k) %>%
  kable(
    digits = 3,
    col.names = c(
      "Selected Number of Clusters",
      "Within-Cluster Sum of Squares",
      "Average Silhouette Score"
    ),
    caption = "Selected K-means Clustering Solution"
  )
Selected K-means Clustering Solution
Selected Number of Clusters Within-Cluster Sum of Squares Average Silhouette Score
2 111590 0.259

The Silhouette Analysis identifies two clusters as the most suitable configuration among the evaluated clustering solutions, achieving an average silhouette score of 0.259 and a within-cluster sum of squares of 111,590.

Interestingly, the selected number of clusters differs from the six traditional playlist genres represented in the dataset. This suggests that the underlying structure of the selected audio characteristics may not directly correspond to conventional genre classifications.

However, the relatively low silhouette score indicates weak separation between the identified clusters, suggesting considerable overlap in musical characteristics. Rather than representing clearly defined categories, songs may exist along a continuous spectrum of audio features.

These results are particularly relevant to the research question, as they highlight both the potential and the limitations of using unsupervised machine learning to identify alternative musical groupings. The two-cluster solution is therefore selected for further investigation, with the objective of understanding the distinctive audio characteristics of each group and examining their relationships with traditional music genres.z

5.2 What Defines the Hidden Musical Groups?

Following the evaluation of multiple clustering solutions, the two-cluster K-means model is selected for further investigation. The objective of this section is to characterize the identified musical groups by examining their average danceability, energy, valence, tempo, and acousticness.

By comparing the audio profiles of each cluster, we aim to identify the musical characteristics that distinguish these groups and determine whether they represent interpretable listening experiences beyond traditional genre classifications.

Although the silhouette score indicates weak cluster separation, examining the characteristics of each group can provide valuable insights into broader patterns of musical similarity.

Discovering the Two Musical Groups

# Retrieve the selected K-means model
final_model <- kmeans_models[[
  which(k_values == best_k)
]]

# Assign each track to its corresponding cluster
spotify_clustered <- spotify_model %>%
  mutate(
    cluster = factor(final_model$cluster)
  )

# Calculate cluster sizes and percentages
cluster_sizes <- spotify_clustered %>%
  count(cluster, name = "Tracks") %>%
  mutate(
    Percentage = 100 * Tracks / sum(Tracks)
  )

# Display cluster distribution
cluster_sizes %>%
  kable(
    digits = 2,
    col.names = c("Cluster", "Tracks", "Percentage (%)"),
    caption = "Distribution of Tracks Across Musical Clusters"
  )
Distribution of Tracks Across Musical Clusters
Cluster Tracks Percentage (%)
1 21671 76.43
2 6684 23.57
# Visualize the distribution of tracks across clusters
ggplot(
  cluster_sizes,
  aes(x = cluster, y = Percentage, fill = cluster)
) +
  geom_col(width = 0.6) +
  geom_text(
    aes(
      label = paste0(
        scales::comma(Tracks),
        "\n",
        sprintf("%.2f%%", Percentage)
      )
    ),
    vjust = -0.4,
    size = 4,
    fontface = "bold"
  ) +
  scale_fill_manual(
    values = c("#1DB954", "#4575B4")
  ) +
  scale_y_continuous(limits = c(0, 110)) +
  labs(
    title = "Discovering the Two Musical Groups",
    subtitle = "Distribution of tracks identified through K-means clustering",
    x = "Musical Cluster",
    y = "Percentage of Tracks (%)",
    caption = "Source: Spotify Songs Dataset | 28,355 unique tracks"
  ) +
  theme_minimal() +
  theme(
    legend.position = "none",
    plot.title = element_text(face = "bold", size = 15),
    panel.grid.major.x = element_blank(),
    panel.grid.minor = element_blank()
  )

The K-means clustering analysis reveals an uneven distribution of tracks across the two identified musical groups. Cluster 1 contains 21,671 tracks, representing 76.43% of the dataset, while Cluster 2 contains 6,684 tracks, accounting for the remaining 23.57%.

This distribution indicates that the combination of audio characteristics represented by Cluster 1 is more prevalent within the dataset. However, the unequal distribution does not necessarily indicate a limitation of the model, as K-means clustering does not require groups to contain equal numbers of observations.

Although the distribution provides an initial understanding of the musical structure identified by the algorithm, cluster size alone does not explain the musical identity of each group. Therefore, further analysis is conducted to examine the average audio characteristics of each cluster and identify the features that contribute to their differentiation.

Calculate Musical Profiles

# Calculate average audio characteristics by cluster
cluster_profiles <- spotify_clustered %>%
  group_by(cluster) %>%
  summarise(
    Tracks = n(),
    across(all_of(audio_features), mean),
    .groups = "drop"
  )

# Display musical profiles
cluster_profiles %>%
  kable(
    digits = 3,
    col.names = c(
      "Cluster",
      "Tracks",
      "Danceability",
      "Energy",
      "Valence",
      "Tempo",
      "Acousticness"
    ),
    caption = "Average Audio Characteristics of Musical Clusters"
  )
Average Audio Characteristics of Musical Clusters
Cluster Tracks Danceability Energy Valence Tempo Acousticness
1 21671 0.658 0.765 0.534 123.754 0.085
2 6684 0.638 0.481 0.433 111.902 0.478

Assign descriptive cluster names

# Assign descriptive names based on cluster characteristics
spotify_clustered <- spotify_clustered %>%
  mutate(
    cluster_name = case_when(
      cluster == "1" ~ "Energy",
      cluster == "2" ~ "Acoustic"
    )
  )

# Display the final musical cluster profiles
spotify_clustered %>%
  group_by(cluster_name) %>%
  summarise(
    Tracks = n(),
    across(all_of(audio_features), mean),
    .groups = "drop"
  ) %>%
  kable(
    digits = 3,
    col.names = c(
      "Musical Group",
      "Tracks",
      "Danceability",
      "Energy",
      "Valence",
      "Tempo",
      "Acousticness"
    ),
    caption = "Final Musical Cluster Profiles"
  )
Final Musical Cluster Profiles
Musical Group Tracks Danceability Energy Valence Tempo Acousticness
Acoustic 6684 0.638 0.481 0.433 111.902 0.478
Energy 21671 0.658 0.765 0.534 123.754 0.085

The K-means clustering analysis identifies two interpretable musical profiles, named Energy and Acoustic, based on their distinctive audio characteristics.

The Energy cluster represents 76.43% of the dataset and is characterized by higher average energy (0.765), faster tempo (123.754 BPM), higher valence (0.534), and relatively low acousticness (0.085). In contrast, the Acoustic cluster represents 23.57% of the dataset and exhibits greater acousticness (0.478), lower energy (0.481), and slower tempo (111.902 BPM).

Interestingly, danceability remains relatively similar across both groups, with average values of 0.658 and 0.638, respectively. This suggests that energy and acousticness are more important distinguishing characteristics than danceability. These findings are consistent with the negative relationship between energy and acousticness identified during the exploratory data analysis.

From a business analytics perspective, these musical profiles could support personalized playlist generation based on listening experiences rather than traditional genre classifications. The Energy cluster could inform workout and social playlists, while the Acoustic cluster could support relaxation and quieter listening experiences.

Nevertheless, the average silhouette score of 0.259 indicates weak cluster separation. Therefore, these groups should be interpreted as broad musical tendencies rather than clearly separated musical categories. Their proposed business applications represent potential opportunities rather than verified listener preferences.

5.3 Mapping the Hidden Musical Landscape

To further investigate the structure of the musical groups identified through K-means clustering, Principal Component Analysis (PCA) is applied to reduce the dimensionality of the five standardized audio features.

PCA transforms the original variables into a set of uncorrelated principal components that capture different proportions of the overall variability in the dataset. By visualizing the first two principal components, we can examine the distribution, separation, and potential overlap between the Energy and Acoustic clusters.

This analysis provides a visual complement to the Silhouette Analysis and helps evaluate whether the identified musical groups represent clearly separated categories or broader patterns within a continuous musical landscape.

Understanding the Principal Components

# Apply PCA to standardized audio characteristics
pca_model <- prcomp(
  spotify_scaled,
  center = FALSE,
  scale. = FALSE
)

# Calculate the percentage of explained variance
explained_variance <- 100 *
  pca_model$sdev^2 /
  sum(pca_model$sdev^2)

# Create a summary of explained variance
pca_variance <- tibble(
  Component = paste0("PC", seq_along(explained_variance)),
  Explained_Variance = explained_variance,
  Cumulative_Variance = cumsum(explained_variance)
)

# Display explained variance
pca_variance %>%
  kable(
    digits = 2,
    col.names = c(
      "Principal Component",
      "Explained Variance (%)",
      "Cumulative Variance (%)"
    ),
    caption = "Variance Explained by Principal Components"
  )
Variance Explained by Principal Components
Principal Component Explained Variance (%) Cumulative Variance (%)
PC1 32.51 32.51
PC2 27.82 60.34
PC3 18.21 78.55
PC4 13.51 92.06
PC5 7.94 100.00
# Visualize variance explained by each component
ggplot(
  pca_variance,
  aes(x = Component, y = Explained_Variance)
) +
  geom_col(
    fill = "#1DB954",
    width = 0.6
  ) +
  geom_text(
    aes(
      label = sprintf("%.2f%%", Explained_Variance)
    ),
    vjust = -0.5,
    size = 4,
    fontface = "bold"
  ) +
  scale_y_continuous(
    expand = expansion(mult = c(0, 0.15))
  ) +
  labs(
    title = "How Much Information Does Each Component Capture?",
    subtitle = "Percentage of variance explained by principal components",
    x = "Principal Component",
    y = "Explained Variance (%)",
    caption = "Source: Spotify Songs Dataset"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(face = "bold", size = 15),
    panel.grid.major.x = element_blank(),
    panel.grid.minor = element_blank()
  )

The explained variance analysis reveals that the first principal component (PC1) accounts for 32.51% of the total variability in the dataset, while the second principal component (PC2) explains an additional 27.82%. Together, the first two principal components capture approximately 60.34% of the variability across the five standardized audio characteristics.

Although the remaining three components account for approximately 39.66% of the total variability, retaining the first two components provides a practical balance between information preservation and visual interpretability.

This dimensionality reduction enables the visualization of the Energy and Acoustic clusters within a two-dimensional space. However, because some information is lost during this transformation, the resulting visualization should be interpreted as a partial representation of the original musical structure rather than a complete reflection of the five-dimensional clustering solution.

Mapping the Hidden Musical Landscape

Using the first two principal components, the identified musical clusters are visualized within a two-dimensional space. Each observation represents an individual track, while colors distinguish the Energy and Acoustic clusters.

This visualization allows us to examine the spatial distribution of the musical groups, identify potential areas of overlap, and evaluate whether the visual structure is consistent with the relatively weak cluster separation observed during Silhouette Analysis.

# Extract the first two principal components
pca_data <- as_tibble(
  pca_model$x[, 1:2]
) %>%
  mutate(
    cluster_name = spotify_clustered$cluster_name
  )
# Visualize the musical clusters in two dimensions
ggplot(
  pca_data,
  aes(
    x = PC1,
    y = PC2,
    color = cluster_name
  )
) +
  geom_point(
    alpha = 0.15,
    size = 0.8
  ) +
  scale_color_manual(
    values = c(
      "Energy" = "#1DB954",
      "Acoustic" = "#4575B4"
    ),
    name = "Musical Cluster"
  ) +
  labs(
    title = "Mapping the Hidden Musical Landscape",
    subtitle = "PCA visualization of Energy and Acoustic clusters",
    x = paste0(
      "PC1 (",
      round(explained_variance[1], 2),
      "%)"
    ),
    y = paste0(
      "PC2 (",
      round(explained_variance[2], 2),
      "%)"
    ),
    caption = "Source: Spotify Songs Dataset | 28,355 unique tracks"
  ) +
  guides(
    color = guide_legend(
      override.aes = list(alpha = 1, size = 3)
    )
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(face = "bold", size = 15),
    legend.position = "bottom",
    panel.grid.minor = element_blank()
  )

5.4 Can Machine Learning Break Genre Boundaries?

Following the identification and visualization of the Energy and Acoustic clusters, the final stage of the machine learning analysis examines their relationship with traditional music genres.

Because genre labels were excluded from the K-means clustering process, comparing the resulting clusters with existing playlist classifications allows us to investigate whether songs from different genres share similar underlying audio characteristics.

This analysis evaluates the extent to which feature-based musical groupings extend beyond conventional genre boundaries and explores their potential implications for music recommendation systems, personalized playlists, and cross-genre music discovery.

Where Do Traditional Genres Fit?

# Connect musical clusters with traditional playlist genres
cluster_genres <- spotify_clustered %>%
  select(track_id, cluster_name) %>%
  inner_join(
    genre_membership,
    by = "track_id"
  )

# Calculate cluster distribution within each genre
cluster_distribution <- cluster_genres %>%
  count(
    playlist_genre,
    cluster_name,
    name = "Tracks"
  ) %>%
  group_by(playlist_genre) %>%
  mutate(
    Percentage = 100 * Tracks / sum(Tracks)
  ) %>%
  ungroup()
# Compare cluster membership across traditional genres
cluster_distribution %>%
  select(
    playlist_genre,
    cluster_name,
    Percentage
  ) %>%
  pivot_wider(
    names_from = cluster_name,
    values_from = Percentage,
    values_fill = 0
  ) %>%
  select(playlist_genre, Energy, Acoustic) %>%
  kable(
    digits = 2,
    col.names = c(
      "Traditional Genre",
      "Energy (%)",
      "Acoustic (%)"
    ),
    caption = "Distribution of Musical Clusters Across Traditional Genres"
  )
Distribution of Musical Clusters Across Traditional Genres
Traditional Genre Energy (%) Acoustic (%)
edm 92.00 8.00
latin 77.81 22.19
pop 77.69 22.31
r&b 57.98 42.02
rap 73.41 26.59
rock 79.15 20.85
# Visualize cluster membership within traditional genres
ggplot(
  cluster_distribution,
  aes(
    x = toupper(playlist_genre),
    y = Percentage,
    fill = cluster_name
  )
) +
  geom_col(width = 0.7) +
  geom_text(
    aes(
      label = sprintf("%.1f%%", Percentage)
    ),
    position = position_stack(vjust = 0.5),
    color = "white",
    size = 4,
    fontface = "bold"
  ) +
  coord_flip() +
  scale_fill_manual(
    values = c(
      "Energy" = "#1DB954",
      "Acoustic" = "#4575B4"
    ),
    name = "Musical Cluster"
  ) +
  scale_y_continuous(
    breaks = seq(0, 100, 25),
    labels = scales::label_percent(scale = 1)
  ) +
  labs(
    title = "Beyond Traditional Genre Boundaries",
    subtitle = "Distribution of Energy and Acoustic clusters across genres",
    x = NULL,
    y = "Percentage of Tracks",
    caption = "Source: Spotify Songs Dataset"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(face = "bold", size = 15),
    legend.position = "bottom",
    panel.grid.major.y = element_blank(),
    panel.grid.minor = element_blank()
  )

The distribution of the Energy and Acoustic clusters across traditional music genres reveals meaningful patterns that extend beyond conventional genre classifications. All six genres are represented in both clusters, suggesting that different genres can share similar underlying audio characteristics.

EDM exhibits the strongest association with the Energy cluster, with 92.0% of its tracks assigned to this group. In contrast, R&B has the highest representation in the Acoustic cluster, accounting for 42.0% of its tracks. These findings are consistent with the differences in energy and acousticness identified during the exploratory data analysis.

Another particularly interesting finding is the similarity between Latin and Pop. Approximately 77.8% of Latin tracks and 77.7% of Pop tracks belong to the Energy cluster, demonstrating nearly identical cluster distributions despite their different traditional classifications. Rock also exhibits a comparable distribution, with 79.1% of its tracks assigned to the Energy cluster.

These results suggest that traditional genre labels do not fully capture the similarities that exist across music. Because genre classifications were excluded from the clustering process, the identified patterns provide an alternative perspective on musical similarity based exclusively on audio characteristics.

From a business analytics perspective, music streaming platforms could leverage these similarities to develop cross-genre recommendations and personalized playlists based on musical characteristics rather than relying exclusively on genre preferences.

However, the average silhouette score of 0.259 indicates relatively weak cluster separation. Therefore, the identified groups should be interpreted as broad musical tendencies rather than definitive musical categories. Feature-based clustering could complement traditional genre classifications rather than replace them entirely.

5.5 What Has Machine Learning Revealed?

Overall, the machine learning analysis suggests that unsupervised learning can reveal broad musical connections beyond traditional genre boundaries. The identification of the Energy and Acoustic clusters, together with the representation of all six genres within both groups, highlights the potential of audio-based approaches to understanding musical similarity.

Although the clustering structure exhibits relatively weak separation, the results provide meaningful insights into the complexity of musical classification and demonstrate potential opportunities for personalized recommendations, alternative playlist generation, and cross-genre music discovery.

6. Summary and Conclusion — From Discovery to Opportunity

6.1 Revisiting Our Research Question

Traditional music genres provide a widely recognized framework for organizing and classifying songs. However, these classifications may not fully capture the complexity of musical characteristics or the similarities that exist between songs from different genres.

The primary objective of this research was to investigate whether audio characteristics could reveal hidden connections between traditionally distinct music genres and whether unsupervised machine learning could identify alternative musical groupings independently of existing genre classifications.

From a business analytics perspective, this research explored the potential of feature-based musical classification to support personalized recommendations, playlist generation, and cross-genre music discovery within music streaming platforms.

6.2 From Data to Discovery

This research utilized the Spotify Songs Dataset, originally containing 32,833 playlist entries and 23 variables. Following data preparation, validation, and duplicate removal, a final dataset of 28,355 unique tracks was obtained for the machine learning analysis.

Five audio characteristics were selected: danceability, energy, valence, tempo, and acousticness. The analysis incorporated six traditional playlist genres: EDM, Latin, Pop, R&B, Rap, and Rock.

Exploratory data analysis was conducted through descriptive statistics, data visualization, correlation analysis, standardized genre comparisons, Euclidean distances, and genre overlap analysis.

Subsequently, K-means clustering was applied to the standardized audio characteristics without incorporating existing genre labels. The Elbow Method and Silhouette Analysis were used to evaluate different clustering configurations, while Principal Component Analysis (PCA) supported the visualization and interpretation of the identified musical groups. Finally, the resulting clusters were compared with traditional playlist genres to investigate cross-genre musical similarities.

6.3 What Did the Music Reveal?

The exploratory data analysis revealed meaningful similarities and differences across traditional music genres. Based on standardized audio profiles, Latin and Rap exhibited the greatest similarity, while EDM and R&B demonstrated the greatest distance among the evaluated genre pairs.

The correlation analysis identified a moderate negative relationship between energy and acousticness (−0.546), suggesting that more energetic songs tend to exhibit lower acousticness. Additionally, danceability and valence demonstrated a positive correlation of approximately 0.334. The genre overlap analysis also revealed that 1,687 unique tracks, representing 5.95% of the cleaned dataset, appeared across multiple playlist genres.

The unsupervised machine learning analysis identified two clusters as the most suitable configuration among the evaluated solutions. These clusters were named Energy and Acoustic according to their distinguishing audio characteristics.

The Energy cluster contained 21,671 tracks, representing 76.43% of the dataset, and was characterized by higher energy, faster tempo, and lower acousticness. The Acoustic cluster contained 6,684 tracks, representing 23.57% of the dataset, and exhibited greater acousticness, lower energy, and slower tempo.

Principal Component Analysis revealed that the first two principal components captured 60.34% of the total variability across the five standardized audio characteristics.

Most importantly, all six traditional genres were represented within both musical clusters. EDM exhibited the highest association with the Energy cluster (92.0%), while R&B demonstrated the highest representation in the Acoustic cluster (42.0%). Latin and Pop exhibited nearly identical cluster distributions, further highlighting broad musical similarities across traditional genre boundaries.

Nevertheless, the average silhouette score of 0.259 indicated relatively weak cluster separation. This suggests that music may be better understood as a continuous spectrum of audio characteristics rather than a collection of clearly separated categories.

6.4 Turning Musical Insights into Business Opportunities

The findings of this research present several potential opportunities for music streaming platforms such as Spotify. By incorporating audio-based musical profiles into recommendation systems, platforms could complement traditional genre classifications with a more flexible approach to music discovery.

For example, the Energy cluster could support the development of playlists designed for workouts, social gatherings, and other high-energy activities, while the Acoustic cluster could inform playlists intended for relaxation and quieter listening experiences.

Furthermore, the representation of all six genres within both clusters highlights the potential for cross-genre recommendations. Users who typically listen to a particular genre could discover songs from different genres that share similar audio characteristics, potentially expanding their musical preferences.

From a strategic perspective, this approach could support greater personalization, music discovery, and exposure to a more diverse range of artists. These capabilities could potentially contribute to improved customer engagement, satisfaction, and retention.

However, these business benefits represent potential applications rather than demonstrated outcomes, as the dataset does not contain information about individual listening behavior, customer satisfaction, or subscription retention.

6.5 Beyond Our Findings: Limitations and Future Opportunities

Despite the meaningful insights obtained throughout this research, several limitations should be acknowledged.

First, the analysis relied on a historical Spotify dataset published in 2020, which may not fully represent current musical trends, emerging genres, or contemporary listening preferences.

Second, only five audio characteristics were incorporated into the clustering model. Although these variables capture important dimensions of music, additional characteristics such as instrumentalness, speechiness, loudness, lyrical content, and cultural influences could provide a more comprehensive representation of musical identity.

Third, K-means clustering assigns each observation to a single cluster and may not adequately capture complex or overlapping musical structures. The relatively low silhouette score of 0.259 indicates weak cluster separation, limiting the interpretation of the identified groups as distinct musical categories.

Additionally, the silhouette scores were estimated using a random sample of 3,000 tracks to reduce computational requirements, while the first two principal components retained only 60.34% of the total variability. Consequently, the two-dimensional visualization does not fully represent the original five-dimensional musical structure.

Another limitation concerns the use of playlist genre labels, which may not necessarily reflect definitive artistic genre classifications. Furthermore, the absence of listener behavior data prevents the direct evaluation of the proposed recommendation strategies.

Future research could incorporate more recent datasets, additional audio characteristics, lyrical analysis, and listener behavior data. Alternative clustering techniques, such as hierarchical clustering, DBSCAN, and Gaussian Mixture Models, could also be explored to determine whether more flexible approaches provide a better representation of musical similarities and overlapping genre boundaries.

Finally, future studies could evaluate the effectiveness of audio-based recommendation strategies through user experiments, examining their impact on music discovery, listening engagement, and customer satisfaction.

7. Beyond the Playlist: Different Genres, Shared Musical Characteristics

Ultimately, this research demonstrates that musical similarities can extend beyond the boundaries of traditional genre classifications. Although unsupervised machine learning did not identify strongly separated musical categories, it revealed interpretable patterns that connect songs from different genres through their underlying audio characteristics.

Rather than replacing traditional genres, feature-based musical groupings offer a complementary perspective on how music can be organized, discovered, and experienced. By looking beyond conventional playlist classifications, data analytics and machine learning provide opportunities to explore music not only through the genres to which it belongs, but also through the characteristics that connect it.

# Prepare traditional genre positions
final_genres <- tibble(
  Genre = c("EDM", "Latin", "Pop", "R&B", "Rap", "Rock"),
  x = seq(1, 11, length.out = 6),
  y = 8
)

# Prepare musical cluster positions and statistics
final_clusters <- spotify_clustered %>%
  count(cluster_name, name = "Tracks") %>%
  mutate(
    Percentage = 100 * Tracks / sum(Tracks),
    x = if_else(cluster_name == "Energy", 3, 9),
    y = 3.8,
    Label = sprintf("%.2f%%", Percentage),
    Track_Label = paste(scales::comma(Tracks), "tracks"),
    Description = if_else(
      cluster_name == "Energy",
      "Higher energy | Faster tempo",
      "More acoustic | Slower tempo"
    )
  )

# Create connections using observed genre memberships
final_connections <- cluster_distribution %>%
  filter(Tracks > 0) %>%
  mutate(
    Genre = case_when(
      playlist_genre == "edm" ~ "EDM",
      playlist_genre == "r&b" ~ "R&B",
      TRUE ~ stringr::str_to_title(playlist_genre)
    )
  ) %>%
  left_join(
    final_genres %>% select(Genre, x),
    by = "Genre"
  ) %>%
  mutate(
    xend = if_else(cluster_name == "Energy", 3, 9)
  )

Music is not defined exclusively by its genre. Although the identified musical clusters exhibit weak separation, the underlying audio characteristics reveal connections across traditional classifications, offering a complementary approach to personalized recommendations and music discovery.