Our modeling goal is to “discover” topics in the lyrics of Spice Girls songs. Instead of a supervised or predictive model where our observations have labels, this is an unsupervised approach.

Explore data

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.3     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.3     ✔ tibble    3.2.1
## ✔ lubridate 1.9.2     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
lyrics <- read_csv("https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2021/2021-12-14/lyrics.csv")
## Rows: 1885 Columns: 9
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (6): artist_name, album_name, song_name, section_name, line, section_artist
## dbl (3): track_number, song_id, line_number
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.

How many albums and songs are there in this dataset?

lyrics %>% distinct(album_name)
## # A tibble: 3 × 1
##   album_name
##   <chr>     
## 1 Spice     
## 2 Spiceworld
## 3 Forever
lyrics %>% distinct(album_name, song_name)
## # A tibble: 31 × 2
##    album_name song_name                 
##    <chr>      <chr>                     
##  1 Spice      "Wannabe"                 
##  2 Spice      "Say You\x92ll Be There"  
##  3 Spice      "2 Become 1"              
##  4 Spice      "Love Thing"              
##  5 Spice      "Last Time Lover"         
##  6 Spice      "Mama"                    
##  7 Spice      "Who Do You Think You Are"
##  8 Spice      "Something Kinda Funny"   
##  9 Spice      "Naked"                   
## 10 Spice      "If U Can\x92t Dance"     
## # ℹ 21 more rows

Let’s start by tokenizing this text and removing a small set of stop words (as well as fixing that punctuation).

library(tidytext)

tidy_lyrics <-
  lyrics %>%
  mutate(song_name = str_replace_all(song_name, "\x92", "'")) %>%
  unnest_tokens(word, line) %>%
  anti_join(get_stopwords())
## Joining with `by = join_by(word)`

What are the most common words in these songs after removing stop words?

tidy_lyrics %>%
  count(word, sort = TRUE)
## # A tibble: 979 × 2
##    word      n
##    <chr> <int>
##  1 get     153
##  2 love    137
##  3 know    124
##  4 time    106
##  5 wanna   102
##  6 never   101
##  7 oh       88
##  8 yeah     88
##  9 la       85
## 10 got      82
## # ℹ 969 more rows

How about per song?

tidy_lyrics %>%
  count(song_name, word, sort = TRUE)
## # A tibble: 2,206 × 3
##    song_name                       word           n
##    <chr>                           <chr>      <int>
##  1 Saturday Night Divas            get           91
##  2 Spice Up Your Life              la            64
##  3 If U Can't Dance                dance         60
##  4 Holler                          holler        48
##  5 Never Give Up on the Good Times never         47
##  6 Move Over                       generation    41
##  7 Saturday Night Divas            deeper        41
##  8 Move Over                       yeah          39
##  9 Something Kinda Funny           got           39
## 10 Never Give Up on the Good Times give          38
## # ℹ 2,196 more rows

This gives us an idea of how many counts per words we have per song, for our modeling.

Train a topic model

To train a topic model with the stm package, we need to create a sparse matrix from our tidy dataframe of tokens.

lyrics_sparse <-
  tidy_lyrics %>%
  count(song_name, word) %>%
  cast_sparse(song_name, word, n)

dim(lyrics_sparse)
## [1]  31 979

This means there are 31 songs (i.e. documents) and different tokens (i.e. terms or words) in our dataset for modeling.

A topic model like this one models:

each document as a mixture of topics each topic as a mixture of words The most important parameter when training a topic modeling is K, the number of topics. This is like k in k-means in that it is a hyperparamter of the model and we must choose this value ahead of time. We could try multiple different values to find the best value for K, but this is a very small dataset so let’s just stick with K = 4.

library(stm)
## Warning: package 'stm' was built under R version 4.3.2
## stm v1.3.6.1 successfully loaded. See ?stm for help. 
##  Papers, resources, and other materials at structuraltopicmodel.com
set.seed(123)
topic_model <- stm(lyrics_sparse, K = 4, verbose = FALSE)

To get a quick view of the results, we can use summary().

summary(topic_model)
## A topic model with 4 topics, 31 documents and a 979 word dictionary.
## Topic 1 Top Words:
##       Highest Prob: get, wanna, time, right, night, deeper, come 
##       FREX: deeper, saturday, comin, get, lover, fun, night 
##       Lift: another, blameless, breaking, clean, damsel, disgrace, fixed 
##       Score: deeper, saturday, get, wanna, lover, arms, comin 
## Topic 2 Top Words:
##       Highest Prob: dance, yeah, love, know, generation, next, baby 
##       FREX: next, naked, denying, foolin, nobody, wants, lead 
##       Lift: check, foolin, forevermore, nobody, trying, whatcha, chico 
##       Score: next, dance, naked, generation, colour, denying, foolin 
## Topic 3 Top Words:
##       Highest Prob: got, love, holler, make, oh, play, yeah 
##       FREX: holler, kinda, swing, funny, yay, trust, loving 
##       Lift: driving, guaranteed, 2000, anyone, anything, bottom, fantasy 
##       Score: holler, swing, kinda, funny, yay, ashamed, loving 
## Topic 4 Top Words:
##       Highest Prob: la, never, give, time, know, love, way 
##       FREX: times, swear, la, bring, promise, viva, tried 
##       Lift: able, certain, love's, rely, affection, shy, replace 
##       Score: la, times, aha, swear, chicas, front, havin

Explore topic model results

To explore more deeply, we can tidy() the topic model results to get a dataframe that we can compute on. There are two possible outputs for this topic model, the “beta” matrix of topic-word probabilities and the “gamma” matrix of document-topic probabilities. Let’s start with the first.

word_topics <- tidy(topic_model, matrix = "beta")
word_topics
## # A tibble: 3,916 × 3
##    topic term        beta
##    <int> <chr>      <dbl>
##  1     1 achieve 1.41e- 3
##  2     2 achieve 2.12e- 4
##  3     3 achieve 5.61e- 9
##  4     4 achieve 3.76e-15
##  5     1 baby    8.22e- 3
##  6     2 baby    1.83e- 2
##  7     3 baby    2.24e- 6
##  8     4 baby    4.32e- 3
##  9     1 back    1.87e- 2
## 10     2 back    5.99e- 4
## # ℹ 3,906 more rows

Since this is a tidy dataframe, we can manipulate it how we like, include making a visualization showing the highest probability words from each topic.

word_topics %>%
  group_by(topic) %>%
  slice_max(beta, n = 10) %>%
  ungroup() %>%
  mutate(topic = paste("Topic", topic)) %>%
  ggplot(aes(beta, reorder_within(term, beta, topic), fill = topic)) +
  geom_col(show.legend = FALSE) +
  facet_wrap(vars(topic), scales = "free_y") +
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_reordered() +
  labs(x = expression(beta), y = NULL)

What about the other matrix? We also need to pass in the document_names.

song_topics <- tidy(topic_model,
  matrix = "gamma",
  document_names = rownames(lyrics_sparse)
)
song_topics
## # A tibble: 124 × 3
##    document                   topic    gamma
##    <chr>                      <int>    <dbl>
##  1 2 Become 1                     1 0.370   
##  2 Denying                        1 0.00165 
##  3 Do It                          1 0.994   
##  4 Get Down With Me               1 0.479   
##  5 Goodbye                        1 0.000666
##  6 Holler                         1 0.00168 
##  7 If U Can't Dance               1 0.000879
##  8 If You Wanna Have Some Fun     1 0.954   
##  9 Last Time Lover                1 0.997   
## 10 Let Love Lead the Way          1 0.00149 
## # ℹ 114 more rows

Remember that each document (song) was modeled as a mixture of topics. How did that turn out?

song_topics %>%
  mutate(
    song_name = fct_reorder(document, gamma),
    topic = factor(topic)
  ) %>%
  ggplot(aes(gamma, topic, fill = topic)) +
  geom_col(show.legend = FALSE) +
  facet_wrap(vars(song_name), ncol = 4) +
  scale_x_continuous(expand = c(0, 0)) +
  labs(x = expression(gamma), y = "Topic")

The songs near the top of this plot are mostly one topic, while the songs near the bottom are more a mix.

There is a TON more you can do with topic models. For example, we can take the trained topic model and, using some supplementary metadata on our documents, estimate regressions for the proportion of each document about a topic with the metadata as the predictors. For example, let’s estimate regressions for our four topics with the album name as the predictor. This asks the question, “Do the topics in Spice Girls songs change across albums?”

effects <-
  estimateEffect(
    1:4 ~ album_name,
    topic_model,
    tidy_lyrics %>% distinct(song_name, album_name) %>% arrange(song_name)
  )

Again, to get a quick view of the results, we can use summary(), but to dive deeper, we will want to use tidy().

summary(effects)
## 
## Call:
## estimateEffect(formula = 1:4 ~ album_name, stmobj = topic_model, 
##     metadata = tidy_lyrics %>% distinct(song_name, album_name) %>% 
##         arrange(song_name))
## 
## 
## Topic 1:
## 
## Coefficients:
##                      Estimate Std. Error t value Pr(>|t|)
## (Intercept)           0.21970    0.13072   1.681    0.104
## album_nameSpice       0.04679    0.18936   0.247    0.807
## album_nameSpiceworld  0.07222    0.18657   0.387    0.702
## 
## 
## Topic 2:
## 
## Coefficients:
##                      Estimate Std. Error t value Pr(>|t|)
## (Intercept)            0.1574     0.1321   1.191    0.244
## album_nameSpice        0.1510     0.1912   0.789    0.436
## album_nameSpiceworld   0.1374     0.1857   0.740    0.466
## 
## 
## Topic 3:
## 
## Coefficients:
##                      Estimate Std. Error t value Pr(>|t|)  
## (Intercept)           0.23183    0.11143   2.081   0.0467 *
## album_nameSpice       0.08604    0.15806   0.544   0.5905  
## album_nameSpiceworld -0.21939    0.15581  -1.408   0.1701  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## 
## Topic 4:
## 
## Coefficients:
##                       Estimate Std. Error t value Pr(>|t|)   
## (Intercept)           0.391290   0.138792   2.819  0.00874 **
## album_nameSpice      -0.281995   0.196504  -1.435  0.16235   
## album_nameSpiceworld  0.007429   0.192449   0.039  0.96948   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
tidy(effects)
## # A tibble: 12 × 6
##    topic term                 estimate std.error statistic p.value
##    <int> <chr>                   <dbl>     <dbl>     <dbl>   <dbl>
##  1     1 (Intercept)           0.218       0.131    1.66   0.107  
##  2     1 album_nameSpice       0.0469      0.189    0.248  0.806  
##  3     1 album_nameSpiceworld  0.0729      0.189    0.387  0.702  
##  4     2 (Intercept)           0.158       0.132    1.20   0.241  
##  5     2 album_nameSpice       0.150       0.190    0.791  0.435  
##  6     2 album_nameSpiceworld  0.139       0.186    0.748  0.461  
##  7     3 (Intercept)           0.232       0.110    2.10   0.0445 
##  8     3 album_nameSpice       0.0834      0.156    0.533  0.598  
##  9     3 album_nameSpiceworld -0.221       0.154   -1.43   0.163  
## 10     4 (Intercept)           0.390       0.138    2.82   0.00871
## 11     4 album_nameSpice      -0.282       0.191   -1.48   0.151  
## 12     4 album_nameSpiceworld  0.00951     0.192    0.0496 0.961

Looks like there is no statistical evidence of change in the lyrical content of the Spice Girls songs across these three albums!

Questions

1.1 Our modeling goal is to “discover” topics in the lyrics of Spice Girls songs.

1.2 The dataset has: the artist name, album name, track number, song name, song ID, section name, line number, line of lyrics, and section artist. This dataset is used to examine the lyrical content of songs.

1.3 The key variables used in the analysis are album_name, song_name, and word. Album_name and song_name are chr variables. A Word is taken from the specific line of lyrics.

2.1 The dataset is transformed by removing duplicate entries in the albums and songs. Replacing certain characters in song names for consistency. Tokenizing lyrics into individual words. Removing stopwords to focus on more meaningful words. The transformed data is now usable by the model.

3.1 The model used in the analysis is a Structural Topic Model (STM), a machine learning technique that is capable of discovering the hidden thematic structure within a large collection of documents.

3.2 The selection of the optimal value for ‘k’, the number of topics, is set to 4 as this dataset is small. However, the choice of ‘k’ is normally found by cross-validation or evaluating model fit.

4.1 The analysis revealed that four distinct topics can be found within the song lyrics. The STM provided a list of words most associated with each topic.