<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/goodreads-machine-learning-part-3/"></div></div><div><a data-url="https://www.r-bloggers.com/goodreads-machine-learning-part-3/" data-counturl="https://www.r-bloggers.com/goodreads-machine-learning-part-3/" data-count="horizontal" data-text="GoodReads: Machine Learning (Part 3)" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://datascienceplus.com/goodreads-machine-learning-part-3/"> DataScience+</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>In the <a target="_blank" href="http://datascienceplus.com/goodreads-webscraping-and-text-analysis-with-r-part-1/">first installment</a> of this series, we scraped reviews from Goodreads. In the <a target="_blank" href="http://datascienceplus.com/exploratory-data-analysis-and-sentiment-analysis/">second one</a>, we performed exploratory data analysis and created new variables. We are now ready for the “main dish”: machine learning!</p>
<h3>Setup and general data prep</h3>
<p>Let’s start by loading the libraries and our dataset.</p>
<pre>
library(data.table)
library(dplyr)
library(caret)
library(RTextTools)
library(xgboost)
library(ROCR)

setwd(&quot;C:/Users/Florent/Desktop/Data_analysis_applications/GoodReads_TextMining&quot;)
data &lt;- read.csv(&quot;GoodReadsCleanData.csv&quot;, stringsAsFactors = FALSE)
</pre>
<p>To recap, at this point, we have the following features in our dataset:</p>
<pre><em>review.id
book
rating
review
review.length
mean.sentiment
median.sentiment
count.afinn.positive
count.afinn.negative
count.bing.negative
count.bing.positive</em></pre>
<p>For this example, we’ll simplify the analysis by collapsing the 1 to 5 stars rating into a binary variable: whether the book was rated a “good read” (4 or 5 stars) or not (1 to 3 stars). This will allow us to use classification algorithms, and to have less unbalanced categories. </p>
<pre>
set.seed(1234)
# Creating the outcome value
data$good.read &lt;- 0
data$good.read[data$rating == 4 | data$rating == 5] &lt;- 1
</pre>
<p>The “good reads”, or positive reviews, represent about 85% of the dataset, and the “bad reads”, or negative reviews, with <code>good.read == 0</code>, about 15%. We then create the train and test subsets. The dataset is still fairly unbalanced, so we don’t just randomly assign data points to the train and test datasets; we make sure to preserve the percentage of good reads in each subset by using the caret function `createDataPartition` for stratified sampling.</p>
<pre>
trainIdx &lt;- createDataPartition(data$good.read, 
                                p = .75, 
                                list = FALSE, 
                                times = 1)
train &lt;- data[trainIdx, ]
test &lt;- data[-trainIdx, ]
</pre>
<h3>Creating the Document-Term Matrices (DTM)</h3>
<p>Our goal is to use the frequency of individual words in the reviews as features in our machine learning algorithms. In order to do that, we need to start by counting the number of occurrence of each word in each review. Fortunately, there are tools to do just that, that will return a convenient “Document-Term Matrix”, with the reviews in rows and the words in columns; each entry in the matrix indicates the number of occurrences of that particular word in that particular review.</p>
<p>A typical DTM would look like this:</p>
<table>
<tr>
<th>Reviews</th>
<th>about</th>
<th>across</th>
<th>ado</th>
<th>adult</th>
</tr>
<tr>
<td>Review 1</td>
<td>0</td>
<td>2</td>
<td>1</td>
<td>0</td>
</tr>
<tr>
<td>Review 2</td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>1</td>
</tr>
</table>
<p>We don’t want to catch every single word that appears in at least one review, because very rare words will increase the size of the DTM while having little predictive power. So we’ll only keep in our DTM words that appear in at least a certain percentage of all reviews, say 1%. This is controlled by the “sparsity” parameter in the following code, with <code>sparsity = 1-0.01 = 0.99</code>.</p>
<p>There is a challenge though. The premise of our analysis is that some words appear in negative reviews and not in positive reviews, and reversely (or at least with a different frequency). But if we only keep words that appear in 1% of our overall training dataset, because negative reviews represent only 15% of our dataset, we are effectively requiring that a negative word appears in <code>1%/15% = 6.67%</code> of the negative reviews; this is too high a threshold and won’t do. </p>
<p>The solution is to create two different DTM for our training dataset, one for positive reviews and one for negative reviews, and then to merge them together. This way, the effective threshold for negative words is to appear in only 1% of the negative reviews.</p>
<pre>
# Creating a DTM for the negative reviews
sparsity &lt;- .99
bad.dtm &lt;- create_matrix(train$review[train$good.read == 0], 
                         language = &quot;english&quot;, 
                         removeStopwords = FALSE, 
                         removeNumbers = TRUE, 
                         stemWords = FALSE, 
                         removeSparseTerms = sparsity) 
#Converting the DTM in a data frame
bad.dtm.df &lt;- as.data.frame(as.matrix(bad.dtm), 
                            row.names = train$review.id[train$good.read == 0])

# Creating a DTM for the positive reviews
good.dtm &lt;- create_matrix(train$review[train$good.read == 1], 
                          language = &quot;english&quot;,
                          removeStopwords = FALSE, 
                          removeNumbers = TRUE, 
                          stemWords = FALSE, 
                          removeSparseTerms = sparsity) 

good.dtm.df &lt;- data.table(as.matrix(good.dtm), 
                          row.names = train$review.id[train$good.read == 1])

# Joining the two DTM together
train.dtm.df &lt;- bind_rows(bad.dtm.df, good.dtm.df)
train.dtm.df$review.id &lt;- c(train$review.id[train$good.read == 0],
                            train$review.id[train$good.read == 1])
train.dtm.df &lt;- arrange(train.dtm.df, review.id)
train.dtm.df$good.read &lt;- train$good.read
</pre>
<p>We also want to use in our analyses our aggregate variables (review length, mean and median sentiment, count of positive and negative words according to the two lexicons), so we join the DTM to the train dataset, by review id. We also convert all NA values in our data frames to 0 (these NA have been generated where words were absent of reviews, so that’s the correct of dealing with them here; but kids, don’t convert NA to 0 at home without thinking about it first).</p>
<pre>
train.dtm.df &lt;- train %>%
  select(-c(book, rating, review, good.read)) %>%
  inner_join(train.dtm.df, by = &quot;review.id&quot;) %>%
  select(-review.id)

train.dtm.df[is.na(train.dtm.df)] &lt;- 0
</pre>
<pre>
# Creating the test DTM
test.dtm &lt;- create_matrix(test$review, 
                          language = &quot;english&quot;, 
                          removeStopwords = FALSE, 
                          removeNumbers = TRUE, 
                          stemWords = FALSE, 
                          removeSparseTerms = sparsity) 
test.dtm.df &lt;- data.table(as.matrix(test.dtm))
test.dtm.df$review.id &lt;- test$review.id
test.dtm.df$good.read &lt;- test$good.read

test.dtm.df &lt;- test %>%
  select(-c(book, rating, review, good.read)) %>%
  inner_join(test.dtm.df, by = &quot;review.id&quot;) %>%
  select(-review.id)
</pre>
<p>A challenge here is to ensure that the test DTM has the same columns as the train dataset. Obviously, some words may appear in the test dataset while being absent of the train dataset, but there’s nothing we can do about them as our algorithms won’t have anything to say about them. The trick we’re going to use relies on the flexibility of the data.tables: when you join by rows two data.tables with different columns, the resulting data.table automatically has all the columns of the two initial data.tables, with the missing values set as NA. So we are going to add a row of our training data.table to our test data.table and immediately remove it after the missing columns will have been created; then we’ll keep only the columns which appear in the training dataset (i.e. discard all columns which appear only in the test dataset).</p>
<pre>
test.dtm.df &lt;- head(bind_rows(test.dtm.df, train.dtm.df[1, ]), -1)
test.dtm.df &lt;- test.dtm.df %>% 
  select(one_of(colnames(train.dtm.df)))
test.dtm.df[is.na(test.dtm.df)] &lt;- 0
</pre>
<p>With this, we have our training and test datasets and we can start crunching numbers!</p>
<h2>Machine Learning</h2>
<p>We’ll be using XGboost here, as it yields the best results (I tried Random Forests and Support Vector Machines too, but the resulting accuracy is too instable with these to be reliable).</p>
<p>We start by calculating our baseline accuracy, what would get by always predicting the most frequent category, and then we calibrate our model.</p>
<pre>
baseline.acc &lt;- sum(test$good.read == &quot;1&quot;) / nrow(test)

XGB.train &lt;- as.matrix(select(train.dtm.df, -good.read),
                       dimnames = dimnames(train.dtm.df))
XGB.test &lt;- as.matrix(select(test.dtm.df, -good.read),
                      dimnames=dimnames(test.dtm.df))
XGB.model &lt;- xgboost(data = XGB.train, 
                     label = train.dtm.df$good.read,
                     nrounds = 400, 
                     objective = &quot;binary:logistic&quot;)

XGB.predict &lt;- predict(XGB.model, XGB.test)

XGB.results &lt;- data.frame(good.read = test$good.read,
                          pred = XGB.predict)
</pre>
<p>The XGBoost algorithm yields a probabilist prediction, so we need to determine a threshold over which we’ll classify a review as good. In order to do that, we’ll plot the ROC (Receiver Operating Characteristic) curve for the true negative rate against the false negative rate. </p>
<pre>
ROCR.pred &lt;- prediction(XGB.results$pred, XGB.results$good.read)
ROCR.perf &lt;- performance(ROCR.pred, 'tnr','fnr') 
plot(ROCR.perf, colorize = TRUE)
</pre>
<p><a title="" data-rel="lightbox-0" target="_blank" href="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2016/09/ROC_curve.png"><img sizes="(max-width: 611px) 100vw, 611px" alt="ROC curve" class="wp-image-4759" src="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2016/09/ROC_curve.png?resize=456%2C356" data-recalc-dims="1"></a></p>
<p>Things are looking pretty good. It seems that by using a threshold of about 0.8 (where the curve becomes red), we can correctly classify more than 50% of the negative reviews (the true negative rate) while misclassifying as negative reviews less than 10% of the positive reviews (the false negative rate).</p>
<pre>
XGB.table &lt;- table(true = XGB.results$good.read, 
                   pred = as.integer(XGB.results$pred >= 0.80))
XGB.table
XGB.acc &lt;- sum(diag(XGB.table)) / nrow(test)
</pre>
<p>Our overall accuracy is 87%, so we beat the benchmark of always predicting that a review is positive (which would yield a 83.4% accuracy here, to be precise), while catching 61.5% of the negative reviews. Not bad for a “black box” algorithm, without any parameter optimization or feature engineering!</p>
<h3>Directions for further analyses</h3>
<p>If we wanted to go deeper in the analysis, a good starting point would be to look at the relative importance of features in the XGBoost algorithm:</p>
<pre>
### Feature analysis with XGBoost
names &lt;- colnames(test.dtm.df)
importance.matrix &lt;- xgb.importance(names, model = XGB.model)
xgb.plot.importance(importance.matrix[1:20, ])
</pre>
<p><a title="" data-rel="lightbox-1" target="_blank" href="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2016/09/XGBoost_feature_importance.png"><img sizes="(max-width: 700px) 100vw, 700px" alt="XGBoost feature importance" class="wp-image-4760" src="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2016/09/XGBoost_feature_importance.png?resize=456%2C456" data-recalc-dims="1"></a></p>
<p>As we can see, there are a few words, such as “colleen” or “you” that are unlikely to be useful in a more general setting, but overall, we find that the most predictive words are negative ones, which was to be expected. We also see that two of our aggregate variables, <code>review.length</code> and <code>count.bing.negative</code>, made the top 10. </p>
<p>There are several ways we could improve on the analysis at this point, such as:</p>
<blockquote><ul>
<li> using N-grams (i.e. sequences of words, such as “did not like”) in addition to single words, to better qualify negative terms. “was very disappointed” would obviously have a different impact compared to “was not disappointed”, even though on a word-by-word basis they could not be distinguished.</li>
<li> fine-tuning the parameters of the XGBoost algorithm.</li>
<li> looking at the negative reviews that have been misclassified, in order to determine what features to add to the analysis.</li>
</ul>
</blockquote>
<h3>Conclusion</h3>
<p>We have covered a lot of ground in this series: from webscraping to sentiment analysis to predictive analytics with machine learning. The main conclusion I would draw from this exercise is that we now have at our disposal a large number of powerful tools that can be used “off-the-shelf” to build fairly quickly a complete and meaningful analytical pipeline. </p>
<p>As for the first two installments, the complete R code for this part is available on <a target="_blank" rel="nofollow" href="https://github.com/BuissonFlorent/GoodReads_TextMining">my github</a>.</p>
<ul></ul>
<p><strong>
<p>Related Post</p>
<p>
<ol>
<li><a title="Permanent Link toMachine Learning for Drug Adverse Event Discovery" target="_blank" rel="bookmark" href="http://datascienceplus.com/machine-learning-for-drug-adverse-event-discovery/">Machine Learning for Drug Adverse Event Discovery</a></li>
<li><a title="Permanent Link toGoodReads: Exploratory data analysis and sentiment analysis (Part 2)" target="_blank" rel="bookmark" href="http://datascienceplus.com/exploratory-data-analysis-and-sentiment-analysis/">GoodReads: Exploratory data analysis and sentiment analysis (Part 2)</a></li>
<li><a title="Permanent Link toGoodReads: Webscraping and Text Analysis with R (Part 1)" target="_blank" rel="bookmark" href="http://datascienceplus.com/goodreads-webscraping-and-text-analysis-with-r-part-1/">GoodReads: Webscraping and Text Analysis with R (Part 1)</a></li>
<li><a title="Permanent Link toEuro 2016 analytics: Who’s playing the toughest game?" target="_blank" rel="bookmark" href="http://datascienceplus.com/euro-2016-analytics-whos-playing-the-toughest-game/">Euro 2016 analytics: Who’s playing the toughest game?</a></li>
<li><a title="Permanent Link toIntegrating R with Apache Hadoop" target="_blank" rel="bookmark" href="http://datascienceplus.com/integrating-r-with-apache-hadoop/">Integrating R with Apache Hadoop</a></li>
</ol></strong>
<div>
<a target="_blank" href="http://feeds.feedburner.com/~ff/datascienceplus?a=Tqno-SSlZ9Q:rBH3Dhqum6I:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/datascienceplus?i=Tqno-SSlZ9Q:rBH3Dhqum6I:D7DqB2pKExk" border="0"></a> <a target="_blank" href="http://feeds.feedburner.com/~ff/datascienceplus?a=Tqno-SSlZ9Q:rBH3Dhqum6I:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/datascienceplus?d=qj6IDK7rITs" border="0"></a> <a target="_blank" href="http://feeds.feedburner.com/~ff/datascienceplus?a=Tqno-SSlZ9Q:rBH3Dhqum6I:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/datascienceplus?d=yIl2AUoC8zA" border="0"></a>
</div>
<p><div><div><div><div data-width="55" data-show-faces="false" data-send="true" data-layout="box_count" data-height="62" data-href="https://www.r-bloggers.com/goodreads-machine-learning-part-3/"></div></div><div><a data-url="https://www.r-bloggers.com/goodreads-machine-learning-part-3/" data-counturl="https://www.r-bloggers.com/goodreads-machine-learning-part-3/" data-count="vertical" data-text="GoodReads: Machine Learning (Part 3)" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://datascienceplus.com/goodreads-machine-learning-part-3/"> DataScience+</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/?s=data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/?s=Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/?s=map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/?s=animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/?s=sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/?s=LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/?s=SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/?s=git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/?s=hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/?s=Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/?s=PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/?s=time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/?s=trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/Co-mm1G0Le8"></a></div>