ECON 4370 / 6370 Computing for Economics

Lecture 8: Taming the Data Zoo: Text as Data

Introduction

  • Text data is ubiquitous.

    • Think of the massive streams of tweets, blog posts, reviews, and other forms of communication that pass through the servers of online social media companies on a daily basis.

    • Financial firms regularly use data from social media and news to predict stock prices.

    • Political scientists examine politicians’ speech and proposed bills to study partisanship and the evolution of party agendas.

  • Plan for this part of course:

    • Tokenization/bag of words: simplifying text data into word counts, etc.

    • Basic topic models

    • Will get back to supervised learning later when necessary machinery is in place

Tokenization

Introduction

  • We’ll be focusing on data sets in which we have distinct documents (reviews, tweets, etc.), which play the role of an observation \(i\).

  • Our data set contains a corpus of \(n\) distinct documents. A corpus is simply a collection of written texts or documents that we want to analyze. For example, it could be a collection of movie reviews, news articles, tweets, or academic papers.

  • How do we form a data matrix \(X\) from these documents? In principle, there are many things we could try.

  • Language is incredibly complex. Sequences of words, their relative placements within a sentence or paragraph, accompanying punctuation, and even medium of communication combine to produce meaning.

  • Every sentence in the previous bulletpoint ends with a period, which hopefully caused you no stress. But in the context of online texting, the period conveys unique meaning. If someone responds to you ok., that is often perceived as anger, relative to just ok with no period.

  • Despite all this, much of text analysis ignores all this complexity and simply counts language tokens. These can be words or small combinations of words.

  • Tokenization seems to work well for relatively simple prediction tasks, which is what we’ll focus on mostly here. But, of course, we can’t just use word counts for tasks such as machine translation.

Bag of Words

  • The bag-of-words representation reduces a document to word counts (or 2-word or 3-word phrases), completely ignoring word order beyond short phrases.

  • Appealing for its computational simplicity.

  • Also, we sometimes only have a relatively small sample of documents, each with a large number of words. The more complex combinations of words you enumerate, the fewer observations you’ll have with those combinations.

  • We can motivate the bag-of-words representation from a model of document generation that randomly draws words with replacement from a vocabulary, a fixed pool of words.

  • Under this representation, the population model is characterized by probabilities for each word. Then in practice, it’s enough to summarize a piece of text as counts of individual words.

Example

The first two lines of Homer Simpson’s iconic “spider pig” song are

spider pig, spider pig

does whatever a spider pig does

can he swing from a web?

no, he can’t, he’s a pig

look out, he is a spider pig

which has the bag-of-words representation

a can can’t does from he he’s is
4 1 1 2 1 3 1 1
no look out pig spider swing web whatever
1 1 1 5 4 1 1 1

This is just a five-line document, which is just one observation, yet the representation is quite high-dimensional. If we add a second Homer quote, the dimension could well double.

Pruning

  • Should we include punctuation? Contractions? Suffixes? These are subjective choices.

  • The most basic algorithm will first remove overly common words (“stopwords” such as “a,” “the,” etc.) or rare words, isolated punctuation and numbers, and common suffixes like s and ing.

  • This pruning attempts to isolate the most important tokens for your prediction task.

  • If we’re doing prediction and have enough data, it’s preferable to err on the side of including more tokens, since we have techniques for dealing with high-dimensional data.

  • On the other hand, more pruning can be better if we have more complicated data and fewer observations (i.e. fewer documents).

  • Rare words are problematic to exclude because they likely are rich in meaning. However, by virtue of their rarity, they will likely appear in very few observations.

  • We generally pick some minimum number \(M\) and remove words that don’t appear in at least \(M\) document to determine rarity. If possible, redo your results for some values of \(M\) to check they don’t change much.

  • Stemming is the process of separating out word roots: e.g. the words “write,” “writes” and “writing” might all be coded as the same word.

    • Obviously this varies by language. A common choice stemming algorithm for English is the Porter stemmer
  • Some representations instead count \(n\)-grams: ordered groups of \(n\) word. This can help prediction, but it increases the dimension of the data, so again there’s a tradeoff.

  • For this class, we’ll use examples where the text data has already been pruned and processed into a bag-of-words represenation.

    • If you’re interested, you can look at the tm (text mining) package in R
    • More serious text processing is often done in other languages such as Python

An example

library(tidyverse)
library(dplyr)
library(tidytext)
library(SnowballC)  # for stemming

# Example: short FOMC excerpt
text_data <- tibble(
  line = 1:3,
  text = c(
    "The Committee seeks to achieve maximum employment and inflation at the rate of 2 percent over the longer run.",
    "The Committee judges that the risks to achieving its employment and inflation goals are balanced.",
    "The Committee will carefully monitor incoming information and adjust the stance of monetary policy as appropriate."
  )
)
# --- 0. Tokenize into words
tokens <- text_data %>%
  unnest_tokens(word, text)

tokens
# A tibble: 50 × 2
    line word      
   <int> <chr>     
 1     1 the       
 2     1 committee 
 3     1 seeks     
 4     1 to        
 5     1 achieve   
 6     1 maximum   
 7     1 employment
 8     1 and       
 9     1 inflation 
10     1 at        
# ℹ 40 more rows
## --- 1. Tokenize into bigrams (n = 2)
bigrams <- text_data %>%
  unnest_tokens(bigram, text, token = "ngrams", n = 2)

bigrams
# A tibble: 47 × 2
    line bigram            
   <int> <chr>             
 1     1 the committee     
 2     1 committee seeks   
 3     1 seeks to          
 4     1 to achieve        
 5     1 achieve maximum   
 6     1 maximum employment
 7     1 employment and    
 8     1 and inflation     
 9     1 inflation at      
10     1 at the            
# ℹ 37 more rows
## --- 2. 2-gram pipeline that removes stopwords inside the n-gram
bigrams_clean <- text_data %>%
  unnest_tokens(bigram, text, token = "ngrams", n = 2) %>%
  separate(bigram, c("w1","w2"), sep = " ") %>%
  anti_join(stop_words, by = c("w1" = "word")) %>%
  anti_join(stop_words, by = c("w2" = "word")) %>%
  count(w1, w2, sort = TRUE) %>%
  unite(bigram, w1, w2, sep = " ")

bigrams_clean
# A tibble: 10 × 2
   bigram                   n
   <chr>                <int>
 1 2 percent                1
 2 achieve maximum          1
 3 carefully monitor        1
 4 committee judges         1
 5 committee seeks          1
 6 incoming information     1
 7 inflation goals          1
 8 maximum employment       1
 9 monetary policy          1
10 monitor incoming         1
## --- 3. Word tokenization + stemming
stemmed_words <- text_data %>%
  unnest_tokens(word, text) %>%
  mutate(stem = wordStem(word))   # apply stemming

stemmed_words
# A tibble: 50 × 3
    line word       stem    
   <int> <chr>      <chr>   
 1     1 the        the     
 2     1 committee  committe
 3     1 seeks      seek    
 4     1 to         to      
 5     1 achieve    achiev  
 6     1 maximum    maximum 
 7     1 employment employ  
 8     1 and        and     
 9     1 inflation  inflat  
10     1 at         at      
# ℹ 40 more rows
# Rebuild stemmed bigrams (filter stopwords first to avoid ‘the’/’and’ stems)
stem_bigrams <- text_data %>%
  unnest_tokens(word, text) %>%
  anti_join(stop_words, by = "word") %>%
  mutate(stem = wordStem(word)) %>%
  group_by(line) %>%
  summarise(text_stem = paste(stem, collapse = " "), .groups = "drop") %>%
  unnest_tokens(bigram, text_stem, token = "ngrams", n = 2) %>%
  count(bigram, sort = TRUE)

stem_bigrams
# A tibble: 23 × 2
   bigram                 n
   <chr>              <int>
 1 employ inflat          2
 2 2 percent              1
 3 achiev employ          1
 4 achiev maximum         1
 5 adjust stanc           1
 6 carefulli monitor      1
 7 committe carefulli     1
 8 committe judg          1
 9 committe seek          1
10 goal balanc            1
# ℹ 13 more rows

Text regression

  • The bag of words representation gives us a feature matrix \(X\) where row \(i\) gives word counts for document \(i\).

    • This is sometimes called a document-term matrix.
  • So, \(X_{ij}\) has the word count for word \(j\) (after stemming, including \(n\)-grams, etc.)

  • We may also do other pre-processing, such as dividing all word counts by the total number of words in a document (we can also include document length as a separate regressor)

  • Once we’re done with our pre-processing, we just plug \(X\) into our favorite learning algorithm.

  • Next, we’ll look at an example with political speech.

Application: political speech

  • We’ll use a data set on all speeches in 2005 for US House and Senate

  • The data is a subset of the data used in Gentzkow et al. (2019), who ask “how well can we predict political affiliation from speech?”

    • Their interpretation: if it’s easy to predict political affiliation from speech, then political speech is “more polarized”

    • Finding: polarized speech is higher than it used to be; the main increase was mainly in the 1990s

  • Whereas Gentzkow et al. (2019) look at polarization over time, we’ll just look at one year (2005).

  • This text has already been tokenized into tri-grams, stopwords have been removed, and words have been stemmed.

  • The data frame congress109Counts has word counts after this tokenization for each polititian.

    • Each row corresponds to a politician, eacch column corresponds to a word or \(n\)-gram.
library(textir)  # data is included with this package
Loading required package: distrom
Loading required package: Matrix

Attaching package: 'Matrix'
The following objects are masked from 'package:tidyr':

    expand, pack, unpack
Loading required package: gamlr
Loading required package: parallel

Attaching package: 'distrom'
The following object is masked from 'package:dplyr':

    collapse
data(congress109)

dim(congress109Counts)
[1]  529 1000
congress109Counts[1:5, 1:8]  # preview first 5 rows and 8 columns
5 x 8 sparse Matrix of class "dgCMatrix"
                 gifted.talented.student national.heritage.corridor
Chris Cannon                           .                          .
Michael Conaway                        .                          .
Spencer Bachus                         .                          .
Mac Thornberry                         .                          .
Randy Neugebauer                       .                          .
                 national.homeownership.month near.retirement.age
Chris Cannon                                .                   .
Michael Conaway                             .                   .
Spencer Bachus                              .                   .
Mac Thornberry                              .                   .
Randy Neugebauer                            .                   .
                 personal.injury.lawyer regional.training.cent
Chris Cannon                          .                      .
Michael Conaway                       .                      .
Spencer Bachus                        .                      .
Mac Thornberry                        .                      .
Randy Neugebauer                      .                      .
                 amnesty.illegal.alien arm.embargo.china
Chris Cannon                         .                 .
Michael Conaway                      .                 .
Spencer Bachus                       .                 .
Mac Thornberry                       .                 .
Randy Neugebauer                     .                 .
congress109Counts[c("Barack Obama", "John Boehner"), 995:998]
2 x 4 sparse Matrix of class "dgCMatrix"
             stem.cel natural.ga hurricane.katrina trade.agreement
Barack Obama        .          1                20               7
John Boehner        .          .                14               .
colnames(congress109Counts)[1:20]
 [1] "gifted.talented.student"       "national.heritage.corridor"   
 [3] "national.homeownership.month"  "near.retirement.age"          
 [5] "personal.injury.lawyer"        "regional.training.cent"       
 [7] "amnesty.illegal.alien"         "arm.embargo.china"            
 [9] "flag.protection.amendment"     "low.cost.reliable"            
[11] "assistant.secretary.commerce"  "human.right.body"             
[13] "indian.art.craft"              "nation.oil.food"              
[15] "using.adult.stem"              "valid.driver.license"         
[17] "weapon.grade.plutonium"        "marriage.protection.amendment"
[19] "people.middle.east"            "produce.stem.cel"             
  • Notice the effects of stemming: stem cell becomes ‘stem.cel’ and natural gas becomes ‘natural.ga’.

  • We also have a data frame congress109Ideology with other info for each polititian.

head(congress109Ideology)
                             name party state chamber  repshare   cs1    cs2
Chris Cannon         Chris Cannon     R    UT       H 0.7900621 0.534 -0.124
Michael Conaway   Michael Conaway     R    TX       H 0.7836028 0.484  0.051
Spencer Bachus     Spencer Bachus     R    AL       H 0.7812933 0.369 -0.013
Mac Thornberry     Mac Thornberry     R    TX       H 0.7776520 0.493  0.002
Randy Neugebauer Randy Neugebauer     R    TX       H 0.7746633 0.506  0.070
Nathan Deal           Nathan Deal     R    GA       H 0.7707892 0.474  0.058
Description of variables in congress109Ideology dataset
Variable Meaning
name Full name of the legislator (House or Senate member).
party Political party affiliation (R = Republican, D = Democrat, I = Independent).
state Two-letter U.S. state abbreviation where the legislator was elected.
chamber Which chamber of Congress: H = House of Representatives, S = Senate.
repshare Share of the legislator’s roll call votes aligned with their party’s position. Higher values → more consistent party-line voting.
cs1 First ideological dimension from roll-call scaling. Typically the liberal–conservative spectrum.
cs2 Second ideological dimension. Captures secondary cleavages (regional or intra-party differences).

Examples

  • Chris Cannon (Republican, Utah, House)
    • repshare = 0.79: Voted with Republicans about 79% of the time.
    • cs1 = 0.534: Conservative position on the main left–right axis.
    • cs2 = -0.124: Slightly negative on the secondary dimension.
  • Nathan Deal (Republican, Georgia, House)
    • repshare = 0.77: Voted with Republicans ~77% of the time.
    • cs1 = 0.474: Conservative ideology.
    • cs2 = 0.058: Small positive secondary position.

Regression analysis

  • Our outcome of interest is congress109Ideology$repshare, the proportion of the two-party vote (Dem and GOP, excluding independents and third parties) obtained by George W. Bush in the 2004 presidential election for each member’s constituency (district for representatives, states for senators).

    • We interpret congress109Ideology$repshare as a continuous measure of political affiliation: a high (low) score means the politician is catering to heavily Republican (Democratic) constituents
  • First, let’s look at the covariance of the frequency of each word with repshare.

# Compute covariance between each word count and repshare across politicians. If it's negative, that means it's said more by Democrats.
assocs <- drop(cov(congress109Ideology$repshare, as.matrix(congress109Counts)))
assocs <- assocs[order(abs(assocs), decreasing=TRUE)] # sort by magnitude
assocs[1:50]
          american.people          african.american               civil.right 
              -0.62686861               -0.33678852               -0.20076422 
        hurricane.katrina                  stem.cel                  war.iraq 
              -0.17228137                0.15646747               -0.15540889 
                rosa.park          million.american                natural.ga 
              -0.14974451               -0.14041272                0.14000991 
          trade.agreement              class.action           private.account 
              -0.13730639                0.12862830               -0.12461472 
               head.start              middle.class               credit.card 
              -0.11587371               -0.11236465               -0.10976908 
             minimum.wage                low.income         domestic.violence 
              -0.10859081               -0.10470700               -0.09496169 
           billion.dollar               black.caucu congressional.black.caucu 
              -0.09404417               -0.09268283               -0.09185012 
                tax.break         prescription.drug             illegal.alien 
              -0.08208338               -0.07860893                0.07670792 
         central.american          natural.disaster              student.loan 
              -0.07610460               -0.07345754               -0.07271414 
                death.tax               bottom.line          republican.party 
               0.07181972               -0.06811937               -0.06642580 
               budget.cut       democrat.republican            embryonic.stem 
              -0.06392312               -0.06258250                0.06180245 
       embryonic.stem.cel                 cia.agent        affordable.housing 
               0.06175049               -0.06150128               -0.06058599 
        medic.malpractice                troop.home                 fre.trade 
              -0.05806386               -0.05699048               -0.05668593 
            child.support                tax.relief                child.left 
              -0.05594121                0.05458478               -0.05450073 
               gulf.coast               oil.compani                  iraq.war 
              -0.05288772               -0.05286051               -0.05226705 
                check.bal                war.terror             start.talking 
              -0.05222663                0.05159353               -0.05076612 
           nuclear.weapon            right.movement 
              -0.05044970               -0.05009969 
  • We can visualize this using a word cloud.
set.seed(0)
library(wordcloud2) # new package

assocs_df <- data.frame(names(assocs), abs(assocs)) # wordcloud2 takes a dataframe
wordcloud2(assocs_df, shape='circle', rotateRatio=0, color=ifelse(as.vector(assocs[1:50]) > 0, 'red', 'blue'))

  • Gentzkow and Shapiro (2010) use this type of correlation to measure media slant: if a newspaper uses language that matches Republican (Democratic) polititians, it is slanted right (left).

  • Now let’s try linear regression with the top 20 words (we will come back to this example when learn how to do regression analysis with high-dimensional covariates)

# Select the top 20 words with the largest absolute covariance (as in assocs)
top_words <- names(assocs)[1:20]
x <- as.matrix(congress109Counts[, top_words])
y <- congress109Ideology$repshare

lm_slant <- lm(y ~ ., data = data.frame(x))
summary(lm_slant)

Call:
lm(formula = y ~ ., data = data.frame(x))

Residuals:
     Min       1Q   Median       3Q      Max 
-0.42010 -0.06807  0.01216  0.08289  0.34588 

Coefficients:
                    Estimate Std. Error t value Pr(>|t|)    
(Intercept)        5.318e-01  6.469e-03  82.215  < 2e-16 ***
american.people    2.338e-04  3.840e-04   0.609  0.54288    
african.american  -3.779e-03  1.191e-03  -3.173  0.00160 ** 
civil.right       -4.270e-04  1.557e-03  -0.274  0.78393    
hurricane.katrina  1.294e-03  1.003e-03   1.290  0.19772    
stem.cel           3.832e-04  2.917e-04   1.314  0.18958    
war.iraq          -2.530e-03  1.172e-03  -2.158  0.03139 *  
rosa.park         -2.600e-03  1.714e-03  -1.517  0.12995    
million.american  -2.919e-03  2.089e-03  -1.398  0.16283    
natural.ga         5.246e-04  2.822e-04   1.859  0.06356 .  
trade.agreement    9.971e-06  2.004e-04   0.050  0.96034    
class.action       1.631e-03  5.624e-04   2.900  0.00390 ** 
private.account   -3.327e-03  1.402e-03  -2.373  0.01799 *  
head.start        -1.953e-03  1.064e-03  -1.836  0.06692 .  
middle.class      -4.154e-03  1.559e-03  -2.665  0.00795 ** 
credit.card        5.257e-04  7.012e-04   0.750  0.45376    
minimum.wage       1.190e-03  5.385e-04   2.210  0.02758 *  
low.income        -8.555e-04  1.071e-03  -0.799  0.42462    
domestic.violence -8.010e-04  9.129e-04  -0.877  0.38069    
billion.dollar     2.407e-03  1.823e-03   1.320  0.18746    
black.caucu       -6.322e-03  2.939e-03  -2.151  0.03192 *  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.1219 on 508 degrees of freedom
Multiple R-squared:  0.2172,    Adjusted R-squared:  0.1864 
F-statistic: 7.048 on 20 and 508 DF,  p-value: < 2.2e-16
  • The linear regression results show which words are most predictive of political ideology. Words with positive coefficients are associated with Republican districts, while words with negative coefficients are associated with Democratic districts.

  • We can consider various transformations of the raw counts X. It is common to instead use proportions, where we divide counts by document lengths. That way it doesn’t matter how long a politician rambles.

x_prop <- x/rowSums(x)
lm_slant_prop <- lm(y ~ ., data = data.frame(x_prop))
summary(lm_slant_prop)

Call:
lm(formula = y ~ ., data = data.frame(x_prop))

Residuals:
     Min       1Q   Median       3Q      Max 
-0.38441 -0.07028  0.01116  0.08167  0.39155 

Coefficients: (1 not defined because of singularities)
                  Estimate Std. Error t value Pr(>|t|)    
(Intercept)        0.13698    0.10742   1.275 0.202868    
american.people    0.41411    0.10941   3.785 0.000173 ***
african.american   0.18579    0.12451   1.492 0.136305    
civil.right        0.31554    0.12146   2.598 0.009667 ** 
hurricane.katrina  0.40886    0.11387   3.591 0.000364 ***
stem.cel           0.42780    0.11207   3.817 0.000152 ***
war.iraq           0.29366    0.12708   2.311 0.021262 *  
rosa.park          0.22163    0.13641   1.625 0.104870    
million.american   0.36768    0.11464   3.207 0.001429 ** 
natural.ga         0.50379    0.11391   4.423 1.21e-05 ***
trade.agreement    0.40347    0.11204   3.601 0.000350 ***
class.action       0.57595    0.11742   4.905 1.28e-06 ***
private.account    0.01385    0.17445   0.079 0.936762    
head.start         0.34614    0.11888   2.912 0.003760 ** 
middle.class       0.32120    0.12004   2.676 0.007710 ** 
credit.card        0.38180    0.15674   2.436 0.015216 *  
minimum.wage       0.19145    0.14482   1.322 0.186808    
low.income         0.35662    0.12431   2.869 0.004302 ** 
domestic.violence  0.33197    0.11840   2.804 0.005253 ** 
billion.dollar     0.33903    0.11775   2.879 0.004165 ** 
black.caucu             NA         NA      NA       NA    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.1262 on 482 degrees of freedom
  (27 observations deleted due to missingness)
Multiple R-squared:  0.1747,    Adjusted R-squared:  0.1422 
F-statistic: 5.372 on 19 and 482 DF,  p-value: 5.994e-12
  • Another common transformation is to change each entry of X into an indicator for whether the entry is positive. That way, X tracks whether a word was ever used in the document.
# Using indicators instead for linear regression.
lm_slant_ind <- lm(y ~ ., data = data.frame(x > 0))
summary(lm_slant_ind)

Call:
lm(formula = y ~ ., data = data.frame(x > 0))

Residuals:
     Min       1Q   Median       3Q      Max 
-0.42935 -0.05881  0.01230  0.07241  0.39006 

Coefficients:
                       Estimate Std. Error t value Pr(>|t|)    
(Intercept)            0.562963   0.011326  49.706  < 2e-16 ***
american.peopleTRUE    0.003398   0.013818   0.246  0.80587    
african.americanTRUE  -0.005585   0.013360  -0.418  0.67606    
civil.rightTRUE       -0.039254   0.013724  -2.860  0.00441 ** 
hurricane.katrinaTRUE -0.009985   0.012374  -0.807  0.42009    
stem.celTRUE           0.004553   0.012490   0.365  0.71561    
war.iraqTRUE          -0.026021   0.012438  -2.092  0.03693 *  
rosa.parkTRUE         -0.013864   0.015987  -0.867  0.38626    
million.americanTRUE  -0.027441   0.012118  -2.265  0.02396 *  
natural.gaTRUE         0.035522   0.012398   2.865  0.00434 ** 
trade.agreementTRUE    0.011536   0.011756   0.981  0.32693    
class.actionTRUE       0.069804   0.014070   4.961 9.58e-07 ***
private.accountTRUE   -0.009173   0.016934  -0.542  0.58827    
head.startTRUE        -0.023025   0.014013  -1.643  0.10097    
middle.classTRUE      -0.042472   0.013383  -3.174  0.00160 ** 
credit.cardTRUE        0.037038   0.014673   2.524  0.01190 *  
minimum.wageTRUE      -0.019226   0.016424  -1.171  0.24232    
low.incomeTRUE         0.003743   0.013194   0.284  0.77674    
domestic.violenceTRUE -0.025776   0.014875  -1.733  0.08373 .  
billion.dollarTRUE    -0.009229   0.012265  -0.752  0.45213    
black.caucuTRUE       -0.124106   0.019183  -6.470 2.31e-10 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.1142 on 508 degrees of freedom
Multiple R-squared:  0.3128,    Adjusted R-squared:  0.2858 
F-statistic: 11.56 on 20 and 508 DF,  p-value: < 2.2e-16
  • Let’s compare the R-squared for all three specifications:
cat("R-squared, levels:", round(summary(lm_slant)$r.squared, 4), "\n")
R-squared, levels: 0.2172 
cat("R-squared, proportions:", round(summary(lm_slant_prop)$r.squared, 4), "\n")
R-squared, proportions: 0.1747 
cat("R-squared, indicators:", round(summary(lm_slant_ind)$r.squared, 4), "\n")
R-squared, indicators: 0.3128 
  • Let’s try throwing in all of the predictors:
lm_slant_all <- lm(y ~ ., data = data.frame(cbind(x, x_prop, x > 0)))
summary(lm_slant_all)

Call:
lm(formula = y ~ ., data = data.frame(cbind(x, x_prop, x > 0)))

Residuals:
     Min       1Q   Median       3Q      Max 
-0.40637 -0.05514  0.00584  0.06386  0.39823 

Coefficients: (1 not defined because of singularities)
                      Estimate Std. Error t value Pr(>|t|)    
(Intercept)          4.258e-01  1.164e-01   3.659 0.000284 ***
american.people      1.469e-04  4.390e-04   0.335 0.737974    
african.american    -1.989e-03  1.326e-03  -1.500 0.134364    
civil.right          1.928e-04  1.718e-03   0.112 0.910691    
hurricane.katrina    1.498e-03  1.089e-03   1.375 0.169887    
stem.cel             2.994e-04  3.081e-04   0.972 0.331806    
war.iraq            -1.950e-03  1.261e-03  -1.546 0.122714    
rosa.park           -1.497e-03  2.187e-03  -0.685 0.493968    
million.american    -2.910e-03  2.218e-03  -1.312 0.190208    
natural.ga           3.087e-04  3.153e-04   0.979 0.327965    
trade.agreement      8.678e-05  2.108e-04   0.412 0.680794    
class.action         8.432e-04  6.954e-04   1.212 0.225976    
private.account     -1.447e-03  1.709e-03  -0.847 0.397441    
head.start          -5.519e-04  1.371e-03  -0.403 0.687423    
middle.class        -2.614e-03  1.927e-03  -1.356 0.175771    
credit.card         -5.007e-04  9.026e-04  -0.555 0.579326    
minimum.wage         1.625e-03  7.233e-04   2.246 0.025175 *  
low.income          -1.590e-04  1.205e-03  -0.132 0.895035    
domestic.violence    9.794e-04  1.103e-03   0.888 0.374891    
billion.dollar       3.133e-03  2.049e-03   1.529 0.126944    
black.caucu         -9.528e-04  3.142e-03  -0.303 0.761860    
american.people.1    1.549e-01  1.210e-01   1.280 0.201145    
african.american.1   2.542e-02  1.329e-01   0.191 0.848459    
civil.right.1        1.256e-01  1.364e-01   0.921 0.357417    
hurricane.katrina.1  1.366e-01  1.250e-01   1.093 0.274979    
stem.cel.1           1.916e-01  1.242e-01   1.543 0.123553    
war.iraq.1           1.675e-01  1.414e-01   1.184 0.236958    
rosa.park.1          7.766e-02  1.594e-01   0.487 0.626442    
million.american.1   1.968e-01  1.270e-01   1.550 0.121874    
natural.ga.1         1.889e-01  1.253e-01   1.507 0.132479    
trade.agreement.1    1.400e-01  1.251e-01   1.119 0.263642    
class.action.1       1.317e-01  1.378e-01   0.956 0.339706    
private.account.1    6.829e-02  2.265e-01   0.302 0.763140    
head.start.1         1.770e-01  1.341e-01   1.321 0.187337    
middle.class.1       2.202e-01  1.332e-01   1.653 0.099048 .  
credit.card.1        3.281e-01  2.122e-01   1.546 0.122757    
minimum.wage.1      -9.562e-02  1.890e-01  -0.506 0.613183    
low.income.1         1.188e-01  1.420e-01   0.837 0.402944    
domestic.violence.1  1.206e-01  1.346e-01   0.896 0.370858    
billion.dollar.1     1.862e-02  1.311e-01   0.142 0.887178    
black.caucu.1               NA         NA      NA       NA    
american.people.2   -1.924e-03  1.947e-02  -0.099 0.921300    
african.american.2   1.440e-02  1.647e-02   0.874 0.382355    
civil.right.2       -3.314e-02  1.728e-02  -1.918 0.055762 .  
hurricane.katrina.2 -1.064e-02  1.636e-02  -0.650 0.515713    
stem.cel.2          -2.067e-02  1.824e-02  -1.133 0.257671    
war.iraq.2          -2.347e-02  1.608e-02  -1.459 0.145215    
rosa.park.2          7.490e-03  2.187e-02   0.342 0.732215    
million.american.2  -4.069e-02  1.654e-02  -2.460 0.014274 *  
natural.ga.2         1.575e-02  1.636e-02   0.963 0.336251    
trade.agreement.2    3.962e-03  1.612e-02   0.246 0.805987    
class.action.2       5.682e-02  2.066e-02   2.751 0.006186 ** 
private.account.2    6.013e-03  2.414e-02   0.249 0.803395    
head.start.2        -1.979e-02  2.033e-02  -0.974 0.330702    
middle.class.2      -4.066e-02  1.688e-02  -2.409 0.016406 *  
credit.card.2        1.038e-02  2.092e-02   0.496 0.620179    
minimum.wage.2      -8.524e-03  2.182e-02  -0.391 0.696297    
low.income.2         7.360e-03  1.721e-02   0.428 0.669014    
domestic.violence.2 -2.741e-02  2.037e-02  -1.345 0.179170    
billion.dollar.2     7.073e-03  1.622e-02   0.436 0.663021    
black.caucu.2       -8.157e-02  2.605e-02  -3.132 0.001854 ** 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.1141 on 442 degrees of freedom
  (27 observations deleted due to missingness)
Multiple R-squared:  0.3807,    Adjusted R-squared:  0.298 
F-statistic: 4.605 on 59 and 442 DF,  p-value: < 2.2e-16
cat("R-squared, all predictors:", round(summary(lm_slant_all)$r.squared, 4), "\n")
R-squared, all predictors: 0.3807 
  • The R-squared values show how well each specification explains the variation in political ideology. The results help us understand which transformation of the word counts works best for predicting political affiliation.

Topic Models

Introduction

  • Factor models are commonly used with text data. Documents are built from several underlying “topics,” which correspond to latent factors that can be recovered using PCA.

  • A concrete use of this is fitting the factor model to a massive set of documents, most of which are usually unlabeled. Then the factors can be used for supervised learning on the subset of labeled documents.

  • Another application is collaborative filtering: predicting user behavior and recommendations based on other users. As an example of this, we might estimate a topic model on product reviews, and then use this to recommend products with high loadings of the same topics.

  • Problem: PCA is actually slow to compute on large datasets, although approximate algorithms are available.

  • Furthermore, the factor model underlying it actually only makes sense for continuous data, not so much for count data.

  • A preferred method these days is “topic modeling” or “latent Dirichlet allocation.” This model takes the bag-of-words representation literally and directly estimates it.

Bag of Words

  • Recall that in the bag-of-words model, a document is generated by randomly drawing words with replacement from a vocabulary.

  • Say we want to generate a document of length \(n\) made of only two words, A and B. If the probability of drawing A is \(p\), then the count of A is distributed Binomial\((n,p)\) and the count of B is Binomial\((n,1-p)\).

  • If we now include more than two words in the bag, we get a vector of word counts that follows a multinomial distribution. This has two parameters:

    • \(n\) (document length)

    • a vector \(\theta\) whose components are probabilities that sum to 1 (the \(k\)th component is the probability of word \(k\)).

  • A topic model further complicates this process by positing the existence of \(K\) latent topics.

Topic Model

  • A topic is a probability vector \(\theta_k = (\theta_{k1}, \dots, \theta_{kd})\), where \(\theta_{kj}\) is the probability under topic \(k\) of drawing word \(j\) from the bag.

  • If \(n_i\) is the length of document \(i\), then a draw from a Multinomial\((n_i,\theta_k)\) yields the vector of word counts for \(i\).

  • Note that \(\theta_k\) is typically very high-dimensional, having the same length as any vector of word counts.

  • For each document \(i\), the proportion of words of topic \(k\) is \(\omega_{ik}\).

  • For each document \(i\) with length \(n_i\), we imagine it being generated as follows:

    • For each of the \(n_i\) words, pick a random topic, where the \(k\)th topic has probability \(\omega_{ik}\) of being drawn. -Then given the topic \(k\), pick a random word, where each word \(j\) has probability \(\theta_{kj}\) of being drawn.
  • Under the previous fictitious process, for each document \(i\), we get a vector of word counts \(X_i\) that is distributed \[\text{Multinomial}(n_i, \omega_{i1}\theta_1 + \dots + \omega_{iK}\theta_K),\] where \(\sum_{k=1}^K \omega_{ik}=1\) and \(\sum_{j=1}^d \theta_{kj}=1\) for all \(j=1,\dots,K\).

  • Since \(n_i\) is the document length, \(\sum_{j=1}^d X_{ij} = n_i\).

  • Note that \(X_i/n_i\) gives word proportions. The topic model says that expected word proportions for a document \(i\) with topic probabilities \(\omega_i=(\omega_{i1},\ldots,\omega_{iK})'\) is \[\omega_{i1}\theta_1 + \dots + \omega_{iK}\theta_K,\] which is similar to the PCA factor model \[Z_{i1}\varphi_1 + \dots + Z_{iK}\varphi_K\]

  • To complete the model, we need a probability distribution for the latent topic probability vector \(\omega\). We use a Dirichlet distribution (hence the name “latent Dirichlet allocation”).

    • We won’t cover the Diriclet distribution here, but basically it’s a simple way of getting a probability distribution over vectors \(\omega\) with positive elements that add up to one.
  • Unlike PCA, the “factors” \(\omega_{ik}\) are directly interpretable as topic probabilities and the “loadings” \(\theta_k\) are word probabilities.

  • Both are also constrained to be probabilities and hence must sum to 1, unlike in PCA.

  • Like PCA, interpreting the factors and loadings is still subjective and messy.

  • In principle, we can estimate the topic model using maximum likelihood, since the model directly specifies a likelihood for any set of independent documents. However this is computationally costly and even harder than computing PCA.

  • Fortunately many alternative algorithms are available. We’ll use the maptpx package, which uses a MAP (maximum a posteriori) estimator. This is similar to maximum likelihood, but it’s maximizing a Bayesian objective function after putting a prior on \(\theta\) (we won’t cover Bayesian estimation here).

Application: restaurant reviews

  • We’ll use data from the (now defunct) online platform we8there, a precursor to Yelp, Google reviews, etc.

  • The data is part of the textir library, which we’ve already loaded.

  • The data set has word counts for about 2.6k bigrams in 6k reviews.

data(we8there)
x <- we8thereCounts 
dim(x)
[1] 6166 2640
  • Let’s look at the first review (row 1):
x[1,x[1,]!=0] 
 even though larg portion  mouth water     red sauc    babi back     back rib 
           1            1            1            1            1            1 
chocol mouss veri satisfi 
           1            1 
  • Looks like a positive review of a rib restaurant.

  • We’ll use the topics() function in the maptpx package.

  • To use this package, you need to convert your data from a standard mtrix to a “slam” simple_triplet_matrix format. This is basically another implementation of the sparse matrix format we discussed in a previous lecture.

  • The option K gives the number of topics. We can input a vector for K, and the ‘topics’ function will try each choice in the vector and use the Bayes factor (an AIC-like criterion) to choose from this vector.

library(maptpx) # new package
Loading required package: slam
x <- as.simple_triplet_matrix(we8thereCounts) 
tpcs <- topics(x,K=5*(1:5))

Estimating on a 6166 document collection.
Fit and Bayes Factor Estimation for K = 5 ... 25
log posterior increase: 2853.9, 327.1, 85.3, 36.7, 25.9, 19.9, 13.8, 11.6, 9.6, 11.4, 20.3, 7.1, 3.9, 8.3, 4, 5.9, 2.4, 3.8, 4.8, 5.3, 3.8, 4.5, 4, 3.8, 2.1, 2, 4.8, 4.5, 2.5, 4.3, 7, 4.9, 9.3, 2.9, 9.9, 3.8, 6.2, 7.3, 3.8, 6, 7.9, 7.4, 7.2, 4, 5.6, 8, 14.3, 11.5, 17.6, 14.8, 14.1, 14.4, 9.5, 7.1, 5.4, 5.8, 2.4, 2.5, 1.5, 1.1, 1.9, 2.9, 2.8, 3.1, 1, 0.8, 0.4, 1.9, 1.3, 0.8, 0.8, 1.1, 1, 2.2, 1, 0.7, 0.4, 0.4, 0.4, 2, 0.4, 0.7, 0.2, 0.3, 2.2, 0.4, 0.3, 0.1, 0.2, done.
log BF( 5 ) = 79521.94
log posterior increase: 4625.8, 195.9, 52.7, 24.8, 17.9, 11.7, 6.1, 7.7, 3.7, 2.4, 0.9, 1.5, 1.8, 1.9, 0.6, 0.3, 0.6, 0.4, 1.3, 0.3, 0.9, 0.9, 0.5, 0.1, done.
log BF( 10 ) = 87499.52
log posterior increase: 3464.9, 164, 50.9, 28.1, 15.2, 8.4, 5.3, 5.9, 1.9, 3.3, 1.7, 4, 1.3, 3.6, 2.8, 2.8, 3, 1.1, 0.9, 1.2, 0.6, 1.1, 0.5, 0.4, 1.3, 0.7, 0.9, 1.4, 0.4, 1.9, 0.7, 0.2, 0.4, 0.4, 0.1, done.
log BF( 15 ) = 3575.35
log posterior increase: 2342.3, 125.5, 32.5, 15.6, 7.5, 21.4, 7.7, 5.2, 2.5, 2.7, 1, 1.3, 3.2, 1.3, 1.6, 6.3, 2.7, 0.7, 1.7, 0.9, 0.4, 2.2, 0.2, 0.5, 0.4, 0.2, done.
log BF( 20 ) = -65922.01
  • The summary() function tells us which \(K\) was selected, along with a summary of the words associated with each topic.

  • Rather than ordering words by the probability \(\theta_{kj}\) of word \(j\) in topic \(k\), the summary() function uses the lift: the ratio of \(\theta_{kj}\) to the overall sample probability of word \(j\) in the corpus (count of word \(j\) divided by word count in all documents).

  • Thus, lift tells you how much more likely the word is to occur in topic k, relative to its typical occurrence across all topics

  • This is typically more informative than the raw \(\theta_{kj}\)s: we want to find words that are uniquely associated with topic \(j\). If we just look at large \(\theta_{kj}\)s, we’ll just end up with common words.

  • Let’s look at our estimated topic model.

summary(tpcs)

Top 5 phrases by topic-over-null term lift (and usage %):

[1] 'food great', 'great food', 'great servic', 'veri good', 'food veri' (14.5) 
[2] 'italian food', 'best italian', 'high recommend', 'list extens', 'wait staff' (11.6) 
[3] 'over minut', 'never go', 'go back', 'arriv after', 'flag down' (10.5) 
[4] 'enough share', 'open daili', 'highlight menu', 'until pm', 'select includ' (10.3) 
[5] 'never return', 'don wast', 'wast time', 'one worst', 'here sever' (9.4) 
[6] 'good work', 'best kept', 'out world', 'just right', 'great experi' (9.2) 
[7] 'take out', 'can get', 'home cook', 'everi time', 'worth wait' (9.1) 
[8] 'ice cream', 'veri pleasant', 'thai food', 'breakfast lunch', 'year ago' (8.9) 
[9] 'food good', 'chees steak', 'fast food', 'food place', 'good select' (8.6) 
[10] 'wasn whole', 'came chip', 'got littl', 'over drink', 'took seat' (7.9) 

Log Bayes factor and estimated dispersion, by number of topics:

             5       10      15        20
logBF 79521.94 87499.52 3575.35 -65922.01
Disp      7.09     4.97    3.96      3.34

Selected the K = 10 topic model
  • The default is to report the 5 words with highest lift, but we can change this option:
summary(tpcs, n=10) # top n words for each topic ordered by lift.

Top 10 phrases by topic-over-null term lift (and usage %):

[1] 'food great', 'great food', 'great servic', 'veri good', 'food veri', 'food excel', 'veri nice', 'excel servic', 'excel food', 'great place' (14.5) 
[2] 'italian food', 'best italian', 'high recommend', 'list extens', 'wait staff', 'mexican food', 'staff friend', 'food wonder', 'authent mexican', 'outstand servic' (11.6) 
[3] 'over minut', 'never go', 'go back', 'arriv after', 'flag down', 'anoth minut', 'ask manag', 'after minut', 'wait over', 'wait anoth' (10.5) 
[4] 'enough share', 'open daili', 'highlight menu', 'until pm', 'select includ', 'fresh veget', 'monday through', 'pm friday', 'dinner buffet', 'serv over' (10.3) 
[5] 'never return', 'don wast', 'wast time', 'one worst', 'here sever', 'sever time', 'custom servic', 'small portion', 'food bland', 'servic poor' (9.4) 
[6] 'good work', 'best kept', 'out world', 'just right', 'great experi', 'kept secret', 'best restaur', 'real treat', 'make reserv', 'best place' (9.2) 
[7] 'take out', 'can get', 'home cook', 'everi time', 'worth wait', 'las vega', 'good valu', 'babi back', 'hand down', 'just good' (9.1) 
[8] 'ice cream', 'veri pleasant', 'thai food', 'breakfast lunch', 'year ago', 'thai restaur', 'pleasant experi', 'indian restaur', 'indian food', 'chicken tikka' (8.9) 
[9] 'food good', 'chees steak', 'fast food', 'food place', 'good select', 'place hang', 'food pretti', 'taco bell', 'hole wall', 'portion size' (8.6) 
[10] 'wasn whole', 'came chip', 'got littl', 'over drink', 'took seat', 'toast bun', 'came pile', 'east lans', 'fri out', 'bill just' (7.9) 

Log Bayes factor and estimated dispersion, by number of topics:

             5       10      15        20
logBF 79521.94 87499.52 3575.35 -65922.01
Disp      7.09     4.97    3.96      3.34

Selected the K = 10 topic model
  • How to interpret these topics? Let’s try to interpret the words with top lift (of course, this is subjective)
    • First factor is general positive feedback.
    • Second is a bit harder to interpret, partly involving type of food (restricted to italian/mexican) but also service.
    • Third is negative feedback, primarily about having to wait.
    • Four is a combination of service hours and also perhaps seasonal or daily specials.
    • Five is general negative feedback.
  • The summary() function orders by lift, but we can also look at the raw orderings of the words with the largest \(\theta_{kj}\) for each factor \(k\):
print(rownames(tpcs$theta)[order(tpcs$theta[,1], decreasing=TRUE)[1:10]])
 [1] "veri good"    "great food"   "food great"   "great place"  "veri friend" 
 [6] "veri nice"    "great servic" "food excel"   "food servic"  "servic great"
print(rownames(tpcs$theta)[order(tpcs$theta[,2], decreasing=TRUE)[1:10]])
 [1] "dine experi"     "high recommend"  "wait staff"      "wine list"      
 [5] "mexican food"    "italian food"    "italian restaur" "fine dine"      
 [9] "staff friend"    "make feel"      
print(rownames(tpcs$theta)[order(tpcs$theta[,3], decreasing=TRUE)[1:10]])
 [1] "go back"     "first time"  "even though" "come back"   "came out"   
 [6] "year old"    "never go"    "come out"    "brought out" "drink order"
print(rownames(tpcs$theta)[order(tpcs$theta[,4], decreasing=TRUE)[1:10]])
 [1] "salad bar"     "mash potato"   "crab cake"     "restaur locat"
 [5] "main cours"    "qualiti food"  "soup salad"    "wide varieti" 
 [9] "don miss"      "reason price" 
  • For the first few topics, we get similar results. But we get different results for other ones, such as topic number 9:
print(rownames(tpcs$theta)[order(tpcs$theta[,9], decreasing=TRUE)[1:10]])
 [1] "food good"   "pretti good" "fast food"   "new york"    "too much"   
 [6] "just like"   "last time"   "fill up"     "hang out"    "sit down"   
  • The words “cheesesteak” and “taco bell” don’t appear as top phrases for topic 9 under the raw ordering, but they’re ranked near the top according to lift (reported by summary() above). Using lift instead of the raw \(\theta\) values gives these phrases greater weight since they are less common in the overall corpus.

  • In addition to looking at the phrase probabilities for each topic, we can look at which observations (i.e. restaurants) have largee probabilities \(\omega_{ik}\) for a given topic \(k\).

  • Here, we don’t have the identities of the restaurants or the full reviews, but we do have ratings data from the we8there website, which accompanied these reviews. These are in the we8thereRatings data frame:

head(we8thereRatings)
   Food Service Value Atmosphere Overall
1     5       5     5          5       5
2     5       5     5          5       5
5     5       5     4          4       5
11    5       5     5          5       5
12    5       5     5          4       5
13    5       5     5          5       5
summary(we8thereRatings$Overall)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  1.000   3.000   5.000   3.945   5.000   5.000 
  • We’ll focus on overall ratings. We’ll plot the estimated topic probabilities \(\omega_{ik}\) against the ratings from review \(i\).
par(mfrow=c(2,2))
boxplot(tpcs$omega[,1] ~ we8thereRatings$Overall, col="gold", xlab="overall rating", ylab="topic 1 score")
boxplot(tpcs$omega[,2] ~ we8thereRatings$Overall, col="pink", xlab="overall rating", ylab="topic 2 score")
boxplot(tpcs$omega[,3] ~ we8thereRatings$Overall, col="orange", xlab="overall rating", ylab="topic 3 score")
boxplot(tpcs$omega[,4] ~ we8thereRatings$Overall, col="lavender", xlab="overall rating", ylab="topic 4 score")

  • The first two topics are positively associated with ratings, while the fourth is negative, which accords with the bottom-up exercise.

  • Three is a bit ambiguous, where we see an overall rating of 4, rather than 5 or 1, being most associated with topic four

  • We can think of this exercise as using topics to predict ratings. If predicting ratings is our main task, we can throw all of the factors into a regression.

References

Gentzkow, Matthew, and Jesse M Shapiro. 2010. “What Drives Media Slant? Evidence from US Daily Newspapers.” Econometrica 78 (1): 35–71.
Gentzkow, Matthew, Jesse M Shapiro, and Matt Taddy. 2019. “Measuring Group Differences in High-Dimensional Choices: Method and Application to Congressional Speech.” Econometrica 87 (4): 1307–40.