<p>Text Mining has become quite mainstream nowadays as the tools to make a reasonable text analysis are ready to be exploited and give astoundingly nice and reasonable results. At BNOSAC, we use it <strong>mainly for text mining on call center data, poetry, salesforce data, emails, HR reviews, IT logged tickets, customer reviews, survey feedback and many more</strong>. We also provide training on text mining with R in Belgium (next trainings are scheduled on November 14/15 2016 and March 23/24 2017 in Belgium, to subscribe: <a href="https://lstat.kuleuven.be/training/coursedescriptions/text-mining-with-r">go here</a> or <a href="http://di-academy.com/event/text-mining-with-r">here</a>).</p>
<p>For this blog post, we will focus on the <span><strong>most relevant visualisations which exist in text mining</strong></span> by using the <strong>CETA trade agreement between the EU and Canada</strong>.</p>
<p></p>
<p>This trade agreement is available as a pdf on <a href="http://www.trade.ec.europa.eu/doclib/docs/2014/september/tradoc_152806.pdf">www.trade.ec.europa.eu/doclib/docs/2014/september/tradoc_152806.pdf</a> and we would like to see what is written in there without having to read all of the 1598 pages in which our politicians in Belgium seem to have found good reasons to at least for a while politically block the process of signing this treaty.<br><br>Let us start by reading in the pdf file in R which is pretty easy nowadays.</p>
<pre>library(pdftools)<br>library(data.table)<br>txt &lt;- pdf_text(&quot;tradoc_152806.pdf&quot;)<br>txt &lt;- unlist(txt)<br>txt &lt;- paste(txt, collapse = &quot; &quot;)</pre>
<p>Research done in 2012 (<a href="https://en.wikipedia.org/wiki/Words_per_minute">Wikipedia</a>) showed that the average reading speed is 184 words per minute or 863 characters per minute. The CETA treaty has 3091384 characters and 334723 terms (words excluding punctuations). A quick calculation tells me that reading this document would take me between 30 and 59 hours non-stop. Were are not going to do this but instead do some text mining on the CETA treaty.</p>
<p>If you are doing text mining, people refer to text as part of documents. In this case there is only 1 document, the CETA treaty. For further analysis, we will assume that each article of the CETA treaty is a document. As you can see in the following screenshot, the article starts always with the word article and next some numbers. Let's extract this so that we have a dataset with 453 articles, the header and the content. The R code for this is put at <a href="https://github.com/jwijffels/ceta-txtmining">https://github.com/jwijffels/ceta-txtmining/blob/master/01_import_ceta_treaty_pos_tagging.R. </a>This dataset is available at <a href="https://github.com/jwijffels/ceta-txtmining">https://github.com/jwijffels/ceta-txtmining</a>.</p>
<p></p>
<p>A first step in text mining is always to do a Parts-of-Speech (POS) tagging. This assigns to each word a tag (noun, verb, adverb, adjective, pronoun, ...). Mostly you are only interested in nouns and some verbs and POS tagging allows you to easily do this. POS tagging for Dutch/French/English/German/Spanish/Italian can be done with the pattern.nlp package available at <a href="https://github.com/bnosac/pattern.nlp">https://github.com/bnosac/pattern.nlp</a>. We do this for all 453 articles in the treaty and show the distribution of the POS tags.</p>
<p></p>
<pre>## Natural Language Processing: POS tagging<br>library(pattern.nlp)<br>ceta_tagged &lt;- mapply(article.id = ceta$article.id, content = ceta$txt, FUN=function(article.id, content){<br>  out &lt;- pattern_pos(x = content, language = &quot;english&quot;, core = TRUE)<br>  out$article.id &lt;- rep(article.id, times = nrow(out))<br>  out<br>}, SIMPLIFY = FALSE)  <br>ceta_tagged &lt;- rbindlist(ceta_tagged)<br><br>## Take only nouns<br>ceta_nouns &lt;- subset(ceta_tagged, word.type %in% c(&quot;NN&quot;) &amp; nchar(word.lemma) > 2)<br><br>## All data in 1 list<br>ceta &lt;- list(ceta_txt = txt, ceta = ceta, ceta_tagged = ceta_tagged, ceta_nouns = ceta_nouns)<br><br>## Look at POS tags<br>library(lattice)<br>barchart(sort(table(ceta$ceta_tagged$word.type)), col = &quot;lightblue&quot;, xlab = &quot;Term frequency&quot;, <br>         main = &quot;Parts of Speech Tag term frequency\n in CETA treaty&quot;)</pre>
<p>In what comes further, we only work on the nouns (POS tags NN). <strong>The data preparation for the text analysis is now done</strong>, we have a dataset with 1 row per word and the corresponding tag. We can now start to do some analysis and to make some graphs</p>
<p>In order to split up the 453 articles into relevant topics, we generate a topic model (code can be found <a href="https://github.com/jwijffels/ceta-txtmining/blob/master/02_visualise_ceta_treaty.R">here</a>). Let's hope we find an indication that some part of the treaty will indeed cover the issues the <a href="https://www.rtbf.be/info/dossier/ceta-la-wallonie-defie-l-europe-et-le-canada/detail_ceta-suivez-la-seance-pleniere-en-direct-du-parlement-wallon-a-11h?id=9442295">Walloon minister president Paul Magnette was talking about</a>. The core R code which fits this is shown below and fits a topic model with 5 topics on the top 250 terms occurring in the CETA treaty.</p>
<pre>ceta_topics &lt;- LDA(x = dtm[, topterms], k = 5, method = &quot;VEM&quot;, control = list(alpha = 0.1, estimate.alpha = TRUE, seed = as.integer(10:1), verbose = FALSE, nstart = 10, save = 0, best = TRUE))</pre>
<p><strong>Can we find the topic which Mr Magnette was talking about</strong>? Yes it is topic 3 which emits the words <strong>claim, dispute, investment certainty, enterprise, decision and authority</strong>, these words will be visualised later on. If we were only interested in this, we can use the topic model to score the treaty and limit the further reading of that document to the 196 articles which cover that. Instead, we will show which typical text mining graphs can be generated with R.<br><br><span><strong>1. Text Mining is mostly about frequency statistics of terms</strong></span></p>
<p>Wordclouds are a commonly used way to display how many times each word is occurring in the text. You can easily do this with the wordcloud or wordcloud2 R package. The following code calculates how many times each noun is occurring and plots these in a wordcloud. The wordcloud2 package gives HTML as output and allows also to set a background image like an image of the Canada flag and the EU.</p>
<pre>## Word frequencies<br>x &lt;- ceta$ceta_nouns[, list(n = .N), by = list(word.lemma)]<br>x &lt;- x[order(x$n, decreasing = TRUE), ]<br>x &lt;- as.data.frame(x)<br><br>## Visualise them with wordclouds<br>library(wordcloud)<br>wordcloud(words = x$word.lemma, freq = x$n, max.words = 150, random.order = FALSE, colors = brewer.pal(8, &quot;Dark2&quot;))<br><br>library(wordcloud2)<br>wordcloud2(data = head(x, 700), figPath = &quot;maple_europa_black.png&quot;)</pre>
<p></p>
<p> </p>
<p><span><strong>2. But text mining is also about co-occurrence statistics</strong></span></p>
<p>Co-occurrence statistics indicate how many times 2 words are occuring in the same CETA article. That is great as it gives more indication of how word are used in its context. For this, you can rely on the ggraph &amp; ggforce R packages. The following shows the top 70 word pairs which co-occur and visualises them.</p>
<pre>library(ggraph)<br>library(ggforce)<br>library(igraph)<br>library(tidytext)<br>word_cooccurences &lt;- pair_count(data=ceta$ceta_nouns, group=&quot;article.id&quot;, value=&quot;word.lemma&quot;, sort = TRUE)<br>set.seed(123456789)<br>head(word_cooccurences, 70) %>%<br>  graph_from_data_frame() %>%<br>  ggraph(layout = &quot;fr&quot;) +<br>  geom_edge_link(aes(edge_alpha = n, edge_width = n)) +<br>  geom_node_point(color = &quot;lightblue&quot;, size = 5) +<br>  geom_node_text(aes(label = name), vjust = 1.8, col = &quot;darkgreen&quot;) +<br>  ggtitle(sprintf(&quot;\n%s&quot;, &quot;CETA treaty\nCo-occurrence of nouns&quot;)) +<br>  theme_void()</pre>
<p></p>
<p> </p>
<p><span><strong>3. And text mining is also about correlations between words</strong></span></p>
<p>Text mining is also about visualising which words are used next to other words. One can use correlations for that which can be visualised. The following graph shows the top 25 correlations of the words emmitted by topic 3 (the Mr Magnette topic which generated some media fuzz). It shows the words emitted by topic 3, these are words like: claim, dispute, investment certainty, enterprise, decision and authorit ). This correlation visualisation clearly shows the correlations between the words which got into the news recently namely investor claims of enterprises, investment certainties, who is deciding on that and when does this new type of procedure get into place.</p>
<pre>library(topicmodels.utils)<br>idx &lt;- predict(ceta_topics, dtm, type = &quot;topics&quot;)<br>idx &lt;- idx$topic == 3<br>termcor &lt;- termcorrplot(dtm[idx, ], <br>                        words = names(ceta_topic_terms$topic3), highlight = head(names(ceta_topic_terms$topic3), 3),<br>                        autocorMax = 25, lwdmultiplier = 3, drawlabel = TRUE, cex.label = 0.8) </pre>
<p></p>
<p><br>In text mining, you have a lot of terms, you can reduce the many word links to relevant links with the EBICglasso function from the qgraph package. This function allows to reduce the correlation matrix between the words to a similar matrix where correlations which are not relevant are set as much as possible to zero so that these do not need to be visualised. The following R code does this and visualises the positive (green) and negative (red) correlations which are left in the correlation matrix of words emmited by all topics. There is clearly and accreditation body which assess conformity according to regulations, an arbitration panel, and a lot is linked to each other regarding access to the market and the government which ensures the legality of the agreement.</p>
<pre>library(Matrix)<br>library(qgraph)<br>terms &lt;- predict(ceta_topics, type = &quot;terms&quot;, min_posterior = 0.025)<br>terms &lt;- unique(unlist(sapply(terms, names)))<br>out &lt;- dtm[, terms]<br>out &lt;- cor(as.matrix(out))<br>out &lt;- nearPD(x=out, corr = TRUE)$mat<br>out &lt;- as.matrix(out)<br><br>m &lt;- EBICglasso(out, n = 1000)<br>qgraph(m, layout=&quot;spring&quot;, labels = colnames(out), label.scale=FALSE,<br>       label.cex=1, node.width=.5)</pre>
<p></p>
<p><br><br><strong><span>4. If you think of it, words are basically also a network which can be visualised</span></strong></p>
<p>R packages semnet and visNetwork are your friends here. Words which occur next to each other or within a certain window can be extracted and visualised. Package semnet uses the igraph package for this, package visNetwork allows to generate HTML output to be published on websites. Example graphs are shown below.</p>
<pre>library(semnet)<br>terms &lt;- unique(unlist(sapply(ceta_topic_terms, names)))<br>cooc &lt;- coOccurenceNetwork(dtm[, terms])<br>cooc &lt;- simplify(cooc)<br>plot(cooc, vertex.size=V(cooc)$freq / 20, edge.arrow.size=0.5)</pre>
<p></p>
<p><br><span><strong>5. And of course you can find topics and visualise these topics</strong></span></p>
<p>If you are interested in topic models, like the one fitted on the CETA treaty, you should have a look at the excellent LDAvis package which allows you to interactively explore the most salient words that each topic emits and as well visualises the distance between the topics.<br>The visualisation is interactive and can be put into a web application easily. The following call to the createJSON and serVis R functions from the LDAvis package give you an interactive topic visualisation in no time.</p>
<pre>library(LDAvis)<br>json &lt;- createJSON(phi = posterior(ceta_topics)$terms,<br>                   theta = posterior(ceta_topics)$topics,<br>                   doc.length = row_sums(dtm),<br>                   vocab = colnames(dtm),<br>                   term.frequency = col_sums(dtm))<br>serVis(json)</pre>
<p></p>
<p><br><br><br>Hope this triggers you a bit to do text mining with R.</p>
<p><strong>If you are interested in all of this, you might be interested also in attending our course on Text mining with R.<br></strong></p>
<p>Our next course on Text Mining with R is scheduled on 2016 November 14/15 in Brussels (Belgium): more info + register at <a href="http://di-academy.com/event/text-mining-with-r/">http://di-academy.com/event/text-mining-with-r/</a><br>Our next course on Text Mining with R is scheduled on 2017 March 23/24 in Leuven (Belgium): more info + register at <a href="https://lstat.kuleuven.be/training/coursedescriptions/text-mining-with-r">https://lstat.kuleuven.be/training/coursedescriptions/text-mining-with-r</a></p>
<div><strong><span>For all other enquiries:  <a href="http://www.bnosac.be/index.php/contact/mail-us">Get in touch</a></span></strong></div>