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.
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
Analyze audio characteristics across music genres. Examine how danceability, energy, valence, tempo, and acousticness differ among Pop, Rap, Rock, Latin, R&B, and EDM.
Identify similarities and differences between genres. Determine which genres share similar audio profiles and which exhibit more distinctive musical characteristics.
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.
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.
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.
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.
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.
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.
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
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.
spotify <-
read.csv("spotify_songs.csv")
## '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 ...
## [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
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 |
duplicate_count <- sum(
duplicated(spotify$track_id)
)
head(duplicate_count)
## [1] 4477
# 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")
| 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.
# 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")
| danceability | energy | valence | tempo | acousticness |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 |
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 |
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 |
# 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")
| 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.
spotify_model %>%
select(
track_name,
danceability,
energy,
valence,
tempo,
acousticness
) %>%
head(6) %>%
kable(
digits = 2,
caption = "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 |
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"
)
| 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.
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:
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"
)
| 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 |
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()
)
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.
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.
# 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"
)
# 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.
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.
# 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"
)
| 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 |
# 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"
)
| 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.
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.
# 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"
)
| 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.
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.
# 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 Genres | Tracks | Percentage (%) |
|---|---|---|
| 1 | 26668 | 94.05 |
| 2 | 1422 | 5.01 |
| 3 | 195 | 0.69 |
| 4 | 63 | 0.22 |
| 5 | 7 | 0.02 |
# 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.
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.
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.
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.
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.
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.