-
Notifications
You must be signed in to change notification settings - Fork 1
/
MLNLP.Rmd
201 lines (152 loc) · 5.11 KB
/
MLNLP.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
---
title: "IntroNLP"
author: "Aishat Sadiq"
date: "`r Sys.Date()`"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# Introduction to Natural Language Processing
```{r Data Prep}
#devtools::install_github("ccss-rs/NAMEOFREPO")
set.seed(31415)
## install.packages("tidyverse")
library(tidyverse)
# library(help = "tidyverse")
# ?tidyverse
## install.packages("tidytext")
## install.packages("topicmodels")
## install.packages("superheat")
## install.packages("ggrepel")
## install.packages("spacyr")
## install.packages("tm")
## install.packages("SnowballC")
## install.packages("stm")
## install.packages("textdata")
## install.packages("wordcloud")
library(tidytext)
library(topicmodels)
library(superheat)
library(ggrepel)
library(spacyr) # lem stem
library(tm) # TermDocumentMatrix
library(SnowballC) # Porter stemming
# library(lda)
library(stm) # Structural Topic Modeling
library(textdata)
library(wordcloud)
```
## Import Dataset
```{r Import Dataset, echo=FALSE}
# find downloaded github folder
getwd()
#setwd(dir)
#Trump Tweets Dataset
# trump_tweets <- read_csv("ML-NLP/trump_tweets.csv")
# View(trump_tweets)
# Panama Papers Dataset
# nodes_entities <- read.csv("/Users/aishatsadiq/Library/Mobile Documents/iCloud~md~obsidian/Documents/PhD/CCSS Data Fellow/ML-NLP/full-oldb.LATEST/nodes-entities.csv")
# View(nodes_entities)
# Mass Mobilization Dataset
mmALL_073120_csv <- read_csv("mmALL_073120_csv.csv") %>%
filter(year=="2020")
View(mmALL_073120_csv)
```
## Data Preprocessing
```{r Data Preprocessing}
?unnest_tokens # Help R Doc for needed function
colnames(mmALL_073120_csv) # copy proper column name
# remove trailing and leading spaces
mmALL_073120_csv$notes <- str_trim(mmALL_073120_csv$notes, side = "both")
head(mmALL_073120_csv$notes)
# Uppercasing w/ Base R toupper(), could also uuse tolower() for lowercase transformation
mmALL_073120_csv[c("notes")] <- sapply(mmALL_073120_csv[c("notes")], function(x) toupper(x))
head(mmALL_073120_csv$notes)
mmALL_073120_csv[c("notes")] <- sapply(mmALL_073120_csv[c("notes")], function(x) tolower(x))
head(mmALL_073120_csv$notes)
# Split raw notes to individual words/tokens, Remove stop words, remove stem w/ porter method, Count Words
stem_counts <- mmALL_073120_csv %>%
unnest_tokens(word, notes) %>%
anti_join(stop_words) %>%
mutate(stem = wordStem(word)) %>%
count(id, stem) %>%
arrange(desc(n))
View(stem_counts)
```
## Analyzing text statistics
```{r}
tf_idf <- mmALL_073120_csv %>%
unnest_tokens(word, notes) %>%
anti_join(stop_words) %>%
mutate(stem = wordStem(word)) %>%
count(id, stem, region, country) %>%
arrange(desc(n))%>%
bind_tf_idf(stem, id, n)
tf_idf
top_tfidf <- tf_idf %>%
arrange(desc(tf_idf)) %>%
drop_na()
top_tfidf
par(mfrow = c(1, 1))
top_tfidf %>%
mutate(word = reorder_within(stem, tf_idf, country)) %>%
filter(region=="Europe") %>%
ggplot(aes(stem, tf_idf, fill = country)) +
geom_col(alpha = 0.8, show.legend = FALSE) +
# facet_wrap(~ country, scales = "free", ncol = 3) +
# facet_wrap(~ country, scales = "free", ncol = 3) +
# facet_grid_paginate(~ country, scales = "free", ncol = 3)+
scale_x_reordered() +
coord_flip() +
theme(strip.text=element_text(size=5)) +
labs(x = NULL, y = "tf-idf",
title = "Highest tf-idf words in 2020 Mass Mobilization Data")
```
## Topic Modeling Algorithms
Text2vec Package - handle large text datasets with high efficiency Topicmodels Package - LDA, CTM, model evaluation, viz MALLET Package - LDA, Hierarchical LDA TM Package LSAfun Package - Latent Semantic Analysis (LSA) tsne Package - dimensionality reduction and data visualization
Latent Dirichlet Allocation (LDA)
```{r}
# LDA outputs: the topic word distributions and the document-topic memberships (from which topics does a document come from)
mmDTM <- DocumentTermMatrix(stem_counts)
mmDTM
mm_lda <- LDA(mmDTM, k = 10, control = list(seed = 31415))
mm_lda
as.data.frame(terms(mm_lda, 10))
## A LDA_VEM topic model with 4 topics.
topics <- tidy(mm_lda, matrix = "beta")
#topics
memberships <- tidy(mm_lda, matrix = "gamma")
#memberships
top_terms <-
topics %>%
group_by(topic) %>%
top_n(10, beta) %>%
ungroup() %>%
arrange(topic, -beta)
top_terms
```
## Lexicon Approach to Sentiment Analysis
Sentiment Analysis package cleanNLP Package
```{r echo=TRUE}
mm_Sent <- mmALL_073120_csv %>%
unnest_tokens(word, notes) %>%
anti_join(stop_words) %>%
mutate(stem = wordStem(word)) %>%
inner_join(get_sentiments("nrc"))
View(mm_Sent)
```
## Visualizing Text Data: Networks, Word Clouds, Bar Charts
Wordcloud Package
<https://quanteda.io/articles/pkgdown/examples/plotting.html>
```{r}
library(dplyr)
top_terms %>%
mutate(term = reorder(term, beta)) %>%
ggplot(aes(term, beta, fill = factor(topic))) +
geom_col(show.legend = FALSE) +
facet_wrap(~ topic, scales = "free") +
coord_flip()
?wordcloud
wordcloud(mm_Sent$sentiment,colors="purple")
```