<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Wayne Xu on Medium]]></title>
        <description><![CDATA[Stories by Wayne Xu on Medium]]></description>
        <link>https://medium.com/@curiositybits?source=rss-6dc273954828------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4DdJzPk-3zMdjogw7NYlWQ.png</url>
            <title>Stories by Wayne Xu on Medium</title>
            <link>https://medium.com/@curiositybits?source=rss-6dc273954828------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 06:04:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@curiositybits/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The awe of making]]></title>
            <link>https://curiositybits.medium.com/the-awe-of-making-f2495c350257?source=rss-6dc273954828------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2495c350257</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[francis-fukuyama]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[psalms]]></category>
            <dc:creator><![CDATA[Wayne Xu]]></dc:creator>
            <pubDate>Sun, 28 Feb 2021 21:31:08 GMT</pubDate>
            <atom:updated>2021-02-28T21:31:08.136Z</atom:updated>
            <content:encoded><![CDATA[<p>I love computers. That’s the geeky side of me. I find intrinsic joy in building Raspberry Pi desktop PCs and assembling automated webcams for my three guinea pigs. I am elated to know that Francis Fukuyama, the world-renowned political economist, is a Raspberry Pi fan. <a href="https://www.americanpurpose.com/blog/fukuyama/why-everyone-should-build-their-own-pc-and-stop-using-macs/">He uses a $50 Raspberry Pi-based computer to read the newspaper in the morning</a> and <a href="https://www.americanpurpose.com/blog/fukuyama/why-you-should-also-switch-to-linux/">advocates for Linux</a>. Francis Fukuyama said he owns four Linux desktop machines. Here, I want to brag: I have seven running four different Linux distros.</p><p><strong><em>The beauty of gadgets-making</em></strong></p><p>People who are drawn to the open-source community see the beauty in what <a href="https://en.wikipedia.org/wiki/Yochai_Benkler">Yochai Benkler</a> calls “<a href="https://en.wikipedia.org/wiki/Commons-based_peer_production">commons-based peer production</a>:” everyday users, like us, free of monetary incentives and managerial commands, can create great things together. Here are the things we the people have built: Wikipedia and many open-source software and tools that power much of today’s digital economy.</p><p>I am not an engineer. I only want to dabble in the open-source making. The Raspberry Pi computer I’ve built is running elegantly. It is so quiet, efficient, and small. It can accomplish much of the work that is usually done on proprietary and expensive machines. I use it for writing, research, and crunching data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A-TjNQo-gfHHe_XbHeNw-A.jpeg" /><figcaption>My $100 Pi computer crunching Twitter data</figcaption></figure><p>Sometimes I look at this credit-card-sized computer chip, nested inside a cheap plastic case. It can do so much with so little built inside. Obviously, as a non-engineer, I do not know the motherboard’s intricate design, the many calculations that have to be done to make things right, and trials and errors beneath the current state of elegance. I cannot begin to fathom. I only marvel at it.</p><p><strong><em>The awe of creatures</em></strong></p><p>Today I took a stroll in the backyard and took down an abandoned bee’s nest. All bees are gone in the winter. Now I can safely inspect the inner part of a honeycomb (see picture below), the layers, the structure, and the texture. They are just mysteriously beautiful. Honey bees are small creatures. Collectively, they make these intricate hexagonal prismatic wax cells to store honey and pollen. I have to read Wikipedia entries to get myself educated about such a mechanism. That is the awe of seeing crowd wisdom in animals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WBNYTGNj6PtAPVoZ0Yy28Q.jpeg" /></figure><p><strong><em>The Heaven declares His glory</em></strong></p><p>We love making gadgets, planting gardens, drawing, and painting because they express our creative instincts. After all, we bear the image of the Creator who spends time and love knitting together the universe and the lives in it. If we can feel the awe of small creatures and gadgets, we must see the immense beauty of the grander story of life-making. Here is how the birth of life is described in Psalm 139:</p><blockquote>“For you formed my inward parts; you knitted me together in my mother’s womb. I praise you, for I am fearfully and wonderfully made. Wonderful are your works; my soul knows it very well. My frame was not hidden from you, when I was being made in secret, intricately woven in the depths of the earth. Your eyes saw my unformed substance; in your book were written, every one of them, the days that were formed for me, when as yet there was none of them.” (Psalm 139: 13–16)</blockquote><p>Eugene Peterson, an American Presbyterian theologian, said: “<strong>In the presence of birth, we don’t calculate, we marvel.</strong>” Let that sink in.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2495c350257" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lunar New Year and a song of lament]]></title>
            <link>https://curiositybits.medium.com/lunar-new-year-and-a-song-of-lament-e29f23bb98dd?source=rss-6dc273954828------2</link>
            <guid isPermaLink="false">https://medium.com/p/e29f23bb98dd</guid>
            <dc:creator><![CDATA[Wayne Xu]]></dc:creator>
            <pubDate>Thu, 11 Feb 2021 19:56:22 GMT</pubDate>
            <atom:updated>2021-02-11T19:56:22.868Z</atom:updated>
            <content:encoded><![CDATA[<p>It is the Lunar New Year, the year of the Ox. “Wish You a Bullish 2021” has become the standard greeting on this celebratory day. Like every new year within the Christian community, we like to use Psalm 65:11 to thank God as He crowns the year with a bountiful harvest. However, Psalm 65:11 wasn’t the first verse that came to my mind today. It was Psalm 137, “By the rivers of Babylon,” a song of lament by a people in exile.</p><p>Every New Year Eve, Chinese Mainlanders gather around and watch the nationally-televised spring gala. It is the Super Bowl Night in China, a rare occasion to glue together people of various groups and tastes. Many hate the spring gala, seeing it as a showcase to project “multi-ethnic harmony and prosperity.” Others are indifferent to the embedded politics and treat it as part of the new year ritual. This year, a song, called Shepherds of Koktokay, rang in my ears. It was heard at this year’s gala.</p><p>My parents explained to me how this song has become viral on Douyin (the domestic version of TikTok) and the love story it tells. It is so popular that Koktokay, the previously little-known small town in the land of Uyghurs, is now a top tourist destination. It is a song based on a fictional love between a shepherd and a honey farmer. Like all romances, it has the elements of serendipitous encounter, sacrificial waiting, and departure. This song, this story, a fictional one, moves a nation to tears.</p><p>Shepherds of Koktokay fits so conveniently into a political imagination of “the others,” of the “strangers in our own land.” The song brings home a far-flung, exotic place of idyllic beauty and natural abundance, a people that live in the romance of ‘the other’ and the politics of “one of us.”</p><p>But, there are other songs. Songs that are unsung. There are other tears, shredded not out of love but fear. There are other realities, not of pasture, but prisons. “How can we sing the songs of the LORD while in a foreign land?” (Psalm 137:4). That is Israel’s lament of life in exile and the yearning to restore hope and home. I think about those in exile, those who become strangers in a foreign land, those born strangers in their own land, and those who are not free, consumed by the culture and the power of the day.</p><p>I hope this new year brings the light that shines into darkness, and a stream of water that grows the rose of hope in the desert.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e29f23bb98dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clubhouse invites and a heavenly invite]]></title>
            <link>https://curiositybits.medium.com/clubhouse-invites-and-a-heavenly-invite-39ff0c9dc1b0?source=rss-6dc273954828------2</link>
            <guid isPermaLink="false">https://medium.com/p/39ff0c9dc1b0</guid>
            <category><![CDATA[clubhouse]]></category>
            <category><![CDATA[fear-of-missing-out]]></category>
            <category><![CDATA[fomo]]></category>
            <category><![CDATA[dogecoin]]></category>
            <dc:creator><![CDATA[Wayne Xu]]></dc:creator>
            <pubDate>Mon, 08 Feb 2021 00:52:32 GMT</pubDate>
            <atom:updated>2021-02-08T00:52:32.736Z</atom:updated>
            <content:encoded><![CDATA[<p>Last week I did two things: I bought <a href="https://www.businessinsider.com/tesla-ceo-elon-musk-sends-dogecoin-cryptocurrency-up-35-tweets-2021-2">Dogecoin</a>, and I posted on Facebook asking for a <a href="https://www.theguardian.com/technology/2021/feb/05/what-is-clubhouse-the-invite-only-audio-chat-app-used-by-elon-musk">Clubhouse invite</a>. Two unrelated things, but since Elon Musk tweeted about both, I guess I acted like his “disciple.”</p><p>There is something to be admired about Clubhouse. It is an invite-only audio-chat app that first became popular among the elite. The early adopters were influencers, tech entrepreneurs, venture capitalists, political insiders, gurus and hero. These people are the idols of our time, who define cultures, drive trends, and make history. Who won’t want to be in the same club with them?</p><p>As a tech observer, I have every reason to join the app. Many of my friends and colleagues are already there. I asked around for invites. They either have exhausted the two invites upon signing-up or remained undecided over whether I am important enough to be the next recipient. Some offered to put me on their waitlists, which I gratefully accepted. At the time, a Clubhouse invite was bid at ~$100 on eBay.</p><p>I am not crazy about Clubhouse. Yet, seeing others joining while I am not brings a bit of FOMO (Fear of Missing Out). The app’s exclusivity sells. It arouses the desire to be associated with the famous and the important. It activates the fear of not being invited, not being included, missing the next big thing, of not being in the same room with those we idolize.</p><p>As I was waiting for my clubhouse invite, I remembered another invite, a heavenly one. This one was sent out thousands of years ago by the Author of Life. This invite was delivered to every person through every generation. It has been delivered on papyrus and papers, in words and actions, through tribulations and peace. For us, the digital-only generation, we may find that invite in text messages, phone calls, emails, Instagram posts, TikTok/YouTube clips, or maybe a Clubhouse room chat. Some of us have clicked that invite, believed it, and acted upon it. Some haven’t, thinking that it is not important enough or that there is still time to RSVP. Some have discarded the invite as spam. This invite, the heavenly one, is for every one of us to be reconciled with the Author of Life. <br> <br>I remembered Zacchaeus, that tax collector in the Bible. Zacchaeus was short, rich but despised by his people. When Jesus entered Jericho, Zacchaeus did something outside of his character and the cultural norm of the day. He wanted to see Jesus so much that he climbed a sycamore-fig tree. I question if my craving for a Clubhouse invite outweighed Zacchaeus’s desire to see God. As recorded in the Scripture, on that day, Jesus, when seeing Zacchaeus up in the tree, said, “Zacchaeus, come down immediately, I must stay at your house today.” This is Jesus’s heavenly invite to Zacchaeus, a short and dejected man, a sinner, one among the deplorable. It is also an invite to us.</p><p>I finally got a Clubhouse invite thanks to a friend’s generosity. I love the app! Today I listened in a clubhouse chat on <a href="https://www.latimes.com/world-nation/story/2020-09-03/china-inner-mongolia-bilingual-education-assimilation-xinjiang-resistance-crackdown">the controversial language policies in Inner Mongolia</a>. It was a roundtable attended by the liberal intelligentsia as well as by Marxist nationalists and social Darwinists. I find it incredibly riveting to see people from opposite sides of the parallel worlds come together and talk (and not to troll), such a rarity in a time of polarization and distrust.</p><p>However, I doubt that the public-spirited civic conversations will last very long before they turn into another echo chambers or shouting matches. The app may not even outlive the COVID-19 virus. The bidding price of clubhouse invites? It is currently ~$25 on eBay, quite a price drop from its high.</p><p>The app, the exclusive club, will one day fade into our memory, like all others. But, the heavenly invite stands…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39ff0c9dc1b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I tried to turn a Raspberry Pi desktop into a productivity powerhouse]]></title>
            <link>https://curiositybits.medium.com/i-tried-to-turn-a-raspberry-pi-desktop-into-a-productivity-powerhouse-bff5c923fe3c?source=rss-6dc273954828------2</link>
            <guid isPermaLink="false">https://medium.com/p/bff5c923fe3c</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[digital-minimalism]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Wayne Xu]]></dc:creator>
            <pubDate>Mon, 01 Feb 2021 03:49:30 GMT</pubDate>
            <atom:updated>2021-02-01T03:54:13.960Z</atom:updated>
            <content:encoded><![CDATA[<p>There are eleven computing devices in my home office: my two work laptops, three spare Linux laptops, a Raspberry Pi desktop, a smartphone, two old and new iPads, a Chromebook, and a Kindle. They are all vying for the home WiFi and my attention.</p><p>As a tech aficionado, I work and live with many screens, browser tabs, and cloud servers. Digital distraction is real and feels like enslavement. This gets me to think about digital minimalism. Don’t get me wrong. It is not Tech Sabbath (tech-free days/hours) or digital distancing (rationing screen time). What I want to practice is with <em>device affordances</em>. To put it more bluntly, I will test if I can become more productive with a minimalist (and slower) tech.</p><p>Each tech has its unique affordances. Let’s compare Kindle and iPad. Kindle is for e-book reading. While Kindle does come with an experimental browser, you don’t want to use Kindle for web-browsing. Yes, it is slow! (but, to digress a bit, Kindle used to offer free and unrestricted global 3G access; this unique affordance became a blessing for users behind the Great Firewall). iPad is excellent for e-books as well, but it is just not that great compared to Kindle. Those who use Kindle can testify about the beauty of E ink and the joy it sparks. When reading on Kindle, you focus purely on words, not screen glare or nagging notification. Long story short, Your iPad is an all-purpose machine. Kindle is not. Kindle is designed for one task only. We are accustomed to thinking that the more affordances a device has, the more productive and fulfilling we become. Here goes the thinking: I can write better if I type on a faster MacBook Air. I learn better if I have a Retina display. But, in my experience, slow and single-tasking tech can lead to a more focused life.</p><p>I am writing this piece on a Raspberry Pi 4 desktop. <a href="https://www.raspberrypi.org/products/raspberry-pi-4-model-b/">Raspberry Pi</a> is a single-board Linux computer. It is small as a credit card and extremely cheap (~$70). You can turn it into a full-fledged desktop computer, with many productivity suites that meet every day computing needs. I use the opensource and free operating system <a href="https://ubuntu-mate.org/">UBuntu MATE</a> on my Pi. There I have Vivaldi/Firefox/Chromium for web-browsing and LibreOffice for documents/spreadsheets. If I just need to read papers, writing documents, and do some lightweight cloud-based coding (through Google Colab), this little thing can get the job done.</p><p>Okay, Pi is a powerful machine (for the price). But it is not that powerful as your work laptop. Multitasking on a Raspberry Pi desktop feels laggy. It slows to crawl if you have more than 20 tabs open in a web browser. It is not fun writing when streaming YouTube videos or refreshing Twitter feed. Raspberry Pi’s beauty as a productivity tool is that it is powerful enough to get things done but not fast enough to make digital loitering frictionless. Pi’s limited affordance constrains your desire to multitask, and therefore liberates you from all the distractions. Everything feels slower on Pi, yet, that slowing down gives you space to reflect on the task at hand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YRNavAcxy000UBirQPKVWA.jpeg" /><figcaption>Credit-card sized Raspberry Pi</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ieQqp_vklBoE6Rg-oc0wQ.png" /><figcaption>My Raspberry Pi desktop</figcaption></figure><p>Minimal tech being productive is never a myth. I have colleagues who prefer writing on a plain text editor than on feature-rich Google Docs. The author of the book <a href="https://www.amazon.com/How-Write-Lot-Practical-Productive/dp/1433829738">How to Write a Lot: A Practical Guide to Productive Academic Writing</a>, Paul J. Silvia, used an archaic computer for writing. This is how Paul described his writing machine in the book:</p><p><em>“This computer was prehistoric even by 1996 standards — no mouse, no Windows, just a keyboard, a soothing blue DOS screen, and WordPerfect 5.0. When the computer died, taking some of my files with it to its grave, I bought a laptop that I typed into the ground. Even now, I’m writing this book on a “state-contract special” that is so old that it occasionally scowls and shakes its fist at me from its porch rocker.”</em></p><p>So I will keep my writing practice on Raspberry Pi and see what it churns out. Speaking of digital distractions broadly, I recently encountered <a href="https://www.chadl.co/mbits/s4e3">a techy podcast made by a fellow Christian</a>. The host, Chad Landman, spoke biblical truth to the issue of digital addictions. Tech is one of God’s great provisions, but cannot-live-without-tech is a sign of spiritual enslavement. This echoes what is said in the 1 Corinthians 6:12 of the Bible:</p><blockquote>“I have the right to do anything,” you say — but not everything is beneficial. “I have the right to do anything” — but I will not be mastered by anything.</blockquote><p>This is a lesson not just for Christians. To all, digital distraction points to a condition of our heart. Our heart longs for something and that thing cannot and will never be satisfied by our gadgets.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bff5c923fe3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text mining: Topic models]]></title>
            <link>https://curiositybits.medium.com/text-mining-topic-models-1f1b6ea6e101?source=rss-6dc273954828------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f1b6ea6e101</guid>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[social-media]]></category>
            <dc:creator><![CDATA[Wayne Xu]]></dc:creator>
            <pubDate>Mon, 04 Mar 2019 21:59:23 GMT</pubDate>
            <atom:updated>2019-03-04T22:14:03.302Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is a static and abbreviated version of this <a href="https://curiositybits.shinyapps.io/R_social_data_analytics/#section-text-mining-topic-models">interactive tutorial</a> on using R for social data analytics.</p><p><strong>What is a topic model?</strong></p><p>Have you dreamed of a day when algorithms can quickly scan through your textbooks and give you a bullet point summary? How convenient! No more tedious reading! Actually, there are algorithms out there that do automatic summarization of large-scale corpus. They are called <em>topic models</em>. In building topic models, we basically ask computers to discover some abstract topics from the text. The internal logic is this: words about the same topic tend to be used together in the same or adjacent semantic space.</p><p><strong>New library?</strong></p><p>The topic model feature is built in the quantaeda library. But you may need to install<em>topicmodels</em>.</p><p><strong>The workflow</strong></p><p>Run the code below and wait untill you get an output.</p><pre>library(quanteda) library(ggplot2) library(topicmodels) reviews_tok &lt;- tokens(review_corpus, remove_punct = TRUE,remove_numbers = TRUE, remove_symbols = TRUE, remove_twitter=TRUE, remove_url=TRUE) reviews_tok &lt;- tokens_select(reviews_tok, pattern = stopwords(&#39;en&#39;), selection = &#39;remove&#39;) reviews_tok &lt;- tokens_select(reviews_tok, min_nchar=3, selection = &#39;keep&#39;) reviews_dfm &lt;- dfm(reviews_tok) reviews_dfm &lt;- dfm(review_corpus, remove = stopwords(&quot;english&quot;), stem = TRUE, remove_punct = TRUE) dfm_fortm &lt;- convert(reviews_dfm, to = &quot;topicmodels&quot;) lda &lt;- LDA(dfm_fortm, k = 6) terms(lda, 10)</pre><p>As you can tell, producing topic models takes time–it is computationally intensive if you hope to build a topic model based on a large-scale corpus.</p><p>In quanteda, we convert a regular DFM object into a format ready for building topic models (see the <em>convert()</em> function in the code above). We then apply the <em>LDA()</em> function to build a topic mode. LDA stands for Latent Dirichlet allocation. It is one of the most commonly used topic modeling algorithms. <em>terms(lda, 10)</em> gives 10 frequent terms from each topic.</p><p><strong>But, what does <em>k=6</em> mean?</strong></p><p>By setting k=6, we ask the LDA algorithm to identify six topics in the corpus. This is where things get extremely complicated and confusing. The algorithm is agnostic about how many topics are there in the corpus. So you will start with a k value and check if the keywords returned shows any clear distinction of topics. If you struggle to summarize the text based on the keywords returned, chances are it is not a good model. Then you will go back and adjust the k value until you find one that gives you somewhat sensible output.</p><p>Tuning up a topic model is an art. It is like tuning up a telescope. So based on the corpus we have, let’s try different k values. This time, run the code in your own laptop.</p><p><strong>Extracting meaning?</strong></p><p>Based on your experience with topic models so far, do you think computers can extract true meanings from textual data?</p><p><em>Originally published at </em><a href="https://curiositybits.cc/post/r_analytics14/"><em>https://curiositybits.cc/post/r_analytics14/</em></a><em> on March 4, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f1b6ea6e101" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text mining: Semantic network]]></title>
            <link>https://curiositybits.medium.com/text-mining-semantic-network-9de4bdd57562?source=rss-6dc273954828------2</link>
            <guid isPermaLink="false">https://medium.com/p/9de4bdd57562</guid>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Wayne Xu]]></dc:creator>
            <pubDate>Mon, 04 Mar 2019 21:55:57 GMT</pubDate>
            <atom:updated>2019-03-04T22:12:27.517Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is a static and abbreviated version of this <a href="https://curiositybits.shinyapps.io/R_social_data_analytics/#section-text-mining-semantic-network">interactive tutorial</a> on using R for social data analytics.</p><p>To understand what a semantic network looks like, go ahead and run the code below.</p><pre>library(quanteda) library(ggplot2) reviews_tok &lt;- tokens(review_corpus, remove_punct = TRUE,remove_numbers = TRUE, remove_symbols = TRUE, remove_twitter=TRUE, remove_url=TRUE) reviews_tok &lt;- tokens_select(reviews_tok, pattern = stopwords(&#39;en&#39;), selection = &#39;remove&#39;) reviews_tok &lt;- tokens_select(reviews_tok, min_nchar=3, selection = &#39;keep&#39;) reviews_dfm &lt;- dfm(reviews_tok) #create a feature co-occurrence matrix (FCM) review_fcm &lt;- fcm(reviews_dfm) #extract the top 50 frequent terms from the FCM object feat &lt;- names(topfeatures(review_fcm, 50)) #trim the old FCM object into a one that contains only the 50 frequent terms fcm_select &lt;- fcm_select(review_fcm, pattern = feat) set.seed(144) textplot_network(fcm_select, min_freq = 0.8)</pre><p>What you see in the output are a bunch of words interconnected to each other. A semantic network can tell us the most central concept/ideas in your corpus. We can use mathematical functions to quantify each position in a semantic network. For example, centrally located words tend to have higher <a href="https://en.wikipedia.org/wiki/Betweenness_centrality"><em>betweenness centrality</em></a>. Even without any mathematic calculation, we can easily spot the most central words based on the visualization. In the corpus of Airbnb reviews, the most central word is <em>place</em>. The concept of semantic networks is developed from the <a href="https://en.wikipedia.org/wiki/Graph_theory">graph theory</a> and <a href="https://en.wikipedia.org/wiki/Social_network_analysis">social network analysis</a>. We will have a separate set of tutorials on online social networks.</p><p><strong>How are words connected to one and another?</strong> You may wonder about that. In quantaeda, a semantic network is referred to as feature co-occurrence matrix (FCM). It is a type of network based on co-occurrence: more specifically, two words are linked to each other if they appear in the same document. In our case, two words are connected to each other if they occur in the same review.</p><p>The semantic network approach can be useful in mapping out central ideas and see how different ideas are connected and clustered. A shortcoming here, though, is that there are too many vague words (e.g., <em>next</em>, <em>first</em>, <em>lots</em>)in the corpus. A refined approach is tagging each word token as noun, adjective, or verb (a process called <a href="https://www.bing.com/search?q=pos+tagging&amp;PC=U316&amp;FORM=CHROMN">Part-of-speech tagging</a>) and then create a semantic network based only on one type of words, say, a semantic network entirely based on nouns or adjectives. You may also consider this approach in analyzing Twitter hashtags. You will learn alot by looking at how different hashtags are concentrated and clustered based on their co-occurrence in the same tweet. If you want to know how to create a semantic network based on hashtags, revist the code <a href="https://curiositybits.shinyapps.io/R_social_data_analytics/#section-make-wordclouds">here</a>.</p><p><em>Originally published at </em><a href="https://curiositybits.cc/post/r_analytics13/"><em>https://curiositybits.cc/post/r_analytics13/</em></a><em> on March 4, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9de4bdd57562" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text mining: discover insights]]></title>
            <link>https://curiositybits.medium.com/text-mining-discover-insights-8b22ae94c61a?source=rss-6dc273954828------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b22ae94c61a</guid>
            <category><![CDATA[social-media]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Wayne Xu]]></dc:creator>
            <pubDate>Mon, 04 Mar 2019 21:14:25 GMT</pubDate>
            <atom:updated>2019-03-04T22:11:35.614Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is a static and abbreviated version of this <a href="https://curiositybits.shinyapps.io/R_social_data_analytics/#section-text-mining-discover-insights">interactive tutorial</a> on using R for social data analytics.</p><p>Now you are on course to try basic text mining techniques to extract insights from textual data. In this tutorial, we will try four techniques: <em>simple word frequency, word cloud, n-grams, and keyness.</em></p><p><strong>Simple word frequency</strong></p><p>Suppose we want to see how often the word “noisy” appears in Airbnb reviews from the three cities respectively. We first create a tokenized corpus called <em>reviews_tok</em> and then use the dfm() function to create a DFM. Subsequently, we ask R to group the text based on the <em>city</em> column. With the grouped DFM, we can inspect the word frequency across documents.</p><pre>library(quanteda) reviews_tok &lt;- tokens(review_corpus,remove_punct = TRUE,remove_numbers = TRUE, remove_symbols = TRUE, remove_twitter=TRUE, remove_url=TRUE) reviews_tok &lt;- tokens_select(reviews_tok, pattern = stopwords(&#39;en&#39;), selection = &#39;remove&#39;) reviews_dfm &lt;- dfm(reviews_tok, group=&quot;city&quot;) #use the city column as the grouping variable reviews_dfm[,&quot;noisy&quot;]</pre><p>It appears that <em>noise</em> is a common complaint among Airbnb users who stayed in Boston.</p><p>Next, we use ggplot2 to visualize the most frequent terms by group (city). We use <em>textstat_frequency()</em> function to calculate the frequency. Inside the function, we set <em>n=20</em> to get the 20 most frequent terms, and <em>groups = “city”</em> to ask for a breakdown of the frequency by three cities.</p><pre>library(quanteda) library(ggplot2) reviews_tok &lt;- tokens(review_corpus,remove_punct = TRUE,remove_numbers = TRUE, remove_symbols = TRUE, remove_twitter=TRUE, remove_url=TRUE) reviews_tok &lt;- tokens_select(reviews_tok, pattern = stopwords(&#39;en&#39;), selection = &#39;remove&#39;) reviews_dfm &lt;- dfm(reviews_tok) #get frequency count for keywords by groups freq &lt;- textstat_frequency(reviews_dfm, n = 20, groups = &quot;city&quot;) ggplot(data = freq, aes(x = nrow(freq):1, y = frequency)) + geom_point() + facet_wrap(~ group, scales = &quot;free&quot;) + coord_flip() + scale_x_continuous(breaks = nrow(freq):1, labels = freq$feature) + labs(x = NULL, y = &quot;Relative frequency&quot;)</pre><p><strong>Word cloud</strong></p><p>In addition to plotting the most frequent terms, we can create a word cloud for city-by-city comparison.</p><pre>library(quanteda) library(ggplot2) reviews_tok &lt;- tokens(review_corpus,remove_punct = TRUE,remove_numbers = TRUE, remove_symbols = TRUE, remove_twitter=TRUE, remove_url=TRUE) reviews_tok &lt;- tokens_select(reviews_tok, pattern = stopwords(&#39;en&#39;), selection = &#39;remove&#39;) reviews_dfm &lt;- dfm(reviews_tok, groups=&quot;city&quot;) set.seed(132) textplot_wordcloud(reviews_dfm, comparison = TRUE, max_words = 200)</pre><p><strong>Keyness</strong></p><p>Based on the frequency plot and word cloud, can you discern any noticeable difference in the reviews across three cities? Well, it appears that the most frequent terms are quite similar across. But, just because a term is frequent, does not mean it is a “keyword.” In text mining, keywords are measured by <a href="http://www.thegrammarlab.com/?p=193">“keyness”</a>. It smeans how <em>distinctive</em> a word is for a corpus when compared to a different corpus. For instance, there are terms frequently used in describing the Airbnb experience in Boston, but not so often used in reviews about the Airbnb experience in other cities. We can use the <em>textstat_keyness</em> function to find these terms based on the keyness measure.</p><pre>library(quanteda) library(ggplot2) reviews_tok &lt;- tokens(review_corpus,remove_punct = TRUE,remove_numbers = TRUE, remove_symbols = TRUE, remove_twitter=TRUE, remove_url=TRUE) reviews_tok &lt;- tokens_select(reviews_tok, pattern = stopwords(&#39;en&#39;), selection = &#39;remove&#39;) reviews_dfm &lt;- dfm(reviews_tok, groups=&quot;city&quot;) result_keyness &lt;- textstat_keyness(reviews_dfm, target = &quot;Boston&quot;) # Plot estimated word keyness textplot_keyness(result_keyness)</pre><p><strong>N-gram</strong></p><p>Text mining is a process of data reduction. It simplifies a complex text into tokens. Along the way, lots of information is lost, especially, when you take single words out of context. Next, we will try <a href="https://en.wikipedia.org/wiki/N-gram">N-grams</a>. N-grams can preserve multi-word phrases and expressions.</p><pre>library(quanteda) library(ggplot2) reviews_tok &lt;- tokens(review_corpus,remove_punct = TRUE,remove_numbers = TRUE, remove_symbols = TRUE, remove_twitter=TRUE, remove_url=TRUE) reviews_tok &lt;- tokens_select(reviews_tok, pattern = stopwords(&#39;en&#39;), selection = &#39;remove&#39;) #create a bi-gram toks_ngram &lt;- tokens_ngrams(reviews_tok, n = 2) reviews_dfm &lt;- dfm(toks_ngram, groups=&quot;city&quot;) set.seed(132) textplot_wordcloud(reviews_dfm, comparison = TRUE, max_words = 200)</pre><p><em>toks_ngram &lt;- tokens_ngrams(reviews_tok, n = 2)</em> is the code you use to create bigrams from the tokenized corpus called reviews_tok. Now observe how the output has changed.</p><p><em>Originally published at </em><a href="https://curiositybits.cc/post/r_analytics12/"><em>https://curiositybits.cc/post/r_analytics12/</em></a><em> on March 4, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b22ae94c61a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean messy text]]></title>
            <link>https://curiositybits.medium.com/clean-messy-text-e3aea912515e?source=rss-6dc273954828------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3aea912515e</guid>
            <category><![CDATA[social-media]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[r]]></category>
            <dc:creator><![CDATA[Wayne Xu]]></dc:creator>
            <pubDate>Mon, 25 Feb 2019 21:52:50 GMT</pubDate>
            <atom:updated>2019-03-04T22:09:11.262Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is a static and abbreviated version of this <a href="https://curiositybits.shinyapps.io/R_social_data_analytics/#section-text-mining-clean-messy-text">interactive tutorial</a> on using R for social data analytics.</p><p><strong>Why text cleaning?</strong></p><p>Textual data are always messy. The data may contain words that, if taken out of context, would be meaningless. You may also encounter a group of different words which convey the same meaning. Or you might have to convert slangs and acronyms into standard English, or emojis into something computer can recognize. Only by cleaning the mess and the noise in the text will you be able to discern useful patterns and signals.</p><p><strong>Tokenization</strong> The text cleaning process mainly occurs during tokenization. Tokenization is part of the text mining workflow. But we did not cover that in the last tutorial because the dfm() function performs tokenization under the hood. In other words, by default, dfm() tokenizes your text first before constructing a DFM object. But, sometimes, we need to call the tokens() function to apply additional cleaning criteria on top of the default setting in dfm().</p><p>Remember we have a pre-created corpus, called review_corpus, which contains 9,000 documents of Airbnb reviews? Run the code below and see what happens.</p><pre>library(quanteda) reviews &lt;- read.csv(&quot;https://curiositybits.cc/files/airbnb_reviews_2018_sample.csv&quot;) review_corpus &lt;- corpus(reviews,docid_field = &quot;id&quot;,text_field = &quot;comments&quot;) tokens(review_corpus[5])</pre><p><strong>tokens(), by default, segments a corpus into tokens where each token represents a word</strong>. The code above tokenizes the 5th document (i.e., the 5th document) in the corpus.</p><p>We commonly tokenize corpus based on words. The following code tokenizes the corpus based on sentences so that each unique sentence is treated as a token. We do that by adding <em>what = “sentence</em> to the <em>tokens()</em> function.</p><pre>tokens(review_corpus[5],what = &quot;sentence&quot;)</pre><p>In the code below, a number of cleaning criteria are added. Observe changes in the output.</p><pre>tokens(review_corpus[5],remove_punct = TRUE,remove_numbers = TRUE, remove_symbols = TRUE, remove_twitter=TRUE, remove_url=TRUE)</pre><p>This time, tokens() segments our corpus into word tokens, but in the process, remove punctuation marks, numbers, symbols, Twitter handles and hashtags, and URLs. As discussed early, choosing what cleaning criteria to apply should be decided on a case by case basis. For some tasks, you may want to preserve Twitter handles and hashtags because they hold the key to understanding your data. You may also want to preserve punctuations if you are interested in how punctuations convey emotions.</p><p>Now, let’s apply tokens() to tokenize the whole corpus and identify the most frequent terms. The tokenization produces an object call <em>review_tok</em>. We can create a DFM from review_tok.</p><pre>library(quanteda) library(ggplot2) review_tok &lt;- tokens(review_corpus,remove_punct = TRUE,remove_numbers = TRUE, remove_symbols = TRUE, remove_twitter=TRUE, remove_url=TRUE) reviews_dfm &lt;- dfm(review_tok) #find 20 most frequent terms topfeatures(reviews_dfm, 20)</pre><p>Hold on, the most frequent terms are: <em>and</em>, <em>the</em>, <em>a</em>, <em>to</em>, <em>was</em>, <em>is</em>? This tells us hardly anything interesting about the data. Well, this is because there are common stop words in our data. <a href="https://en.wikipedia.org/wiki/Stop_words">Stop words</a> are commonly used function words that we ask algorithms to ignore in processing text data. In many text mining tasks, we reckon such stop words as meaningless noises. But, there is a school of thoughts that argue how people use function words (e.g., <em>the</em>, <em>is</em>, <em>at</em>, <em>which</em>, and <em>on</em>) reveals important insights about social identities, power dynamics in a communication context, and personality. <a href="https://www.npr.org/sections/health-shots/2012/04/30/151550273/to-predict-dating-success-the-secrets-in-the-pronouns">Read more here</a>.</p><p>To remove stop words from review_tok (the tokenized corpus created from the previous step), use the code below.</p><pre>reviews_tok &lt;- tokens(review_corpus[5],remove_punct = TRUE,remove_numbers = TRUE, remove_symbols = TRUE, remove_twitter=TRUE, remove_url=TRUE) reviews_tok &lt;- tokens_select(reviews_tok, pattern = stopwords(&#39;en&#39;), selection = &#39;remove&#39;)</pre><p>Alternatively, you can directly use <em>remove = stopwords(“english”)</em> inside the <em>dfm()</em> function. It will do the same trick.</p><pre>library(quanteda) library(ggplot2) reviews_dfm &lt;- dfm(review_corpus, remove = stopwords(&quot;english&quot;), stem = FALSE, remove_punct = TRUE)</pre><p>Ever wonder what <em>stem = FALSE</em> means in the code above? Or do you want to try other cleaning criteria? Run the below code blocks. Each will test a new set of cleaning criteria.</p><pre>library(quanteda) reviews_tok &lt;- tokens(review_corpus[5],remove_punct = TRUE,remove_numbers = TRUE, remove_symbols = TRUE, remove_twitter=TRUE, remove_url=TRUE) reviews_tok &lt;- tokens_select(reviews_tok, min_nchar=3, selection = &#39;keep&#39;) reviews_tok</pre><p>And try this.</p><pre>library(quanteda) reviews_tok &lt;- tokens(review_corpus[5],remove_punct = TRUE,remove_numbers = TRUE, remove_symbols = TRUE, remove_twitter=TRUE, remove_url=TRUE) reviews_tok &lt;- tokens_select(reviews_tok, pattern = c(&quot;lockbox&quot;,&quot;guests&quot;,&quot;however&quot;), selection = &#39;remove&#39;) reviews_tok</pre><p>The code above can be handy when we want to create our own list of filter words. Note that the tokenization process will automatically convert anything into lower cases, so instead of adding “However” as a filter word, we added “however.”</p><p><strong>Stemming</strong></p><p>Here comes the mysterious <em>stem = FALSE</em> in the code. Run the code below and see the output. Notice that <em>stem</em> is set to <em>TRUE</em>.</p><pre>library(quanteda) library(ggplot2) reviews_dfm &lt;- dfm(review_corpus, remove = stopwords(&quot;english&quot;), stem = TRUE, remove_punct = TRUE) reviews_dfm[1:5,1:10]</pre><p><em>Stemming</em> refers to a cleaning process that chops off the ends of words. Why do we do that? This is because different words (e.g., <em>working</em>, <em>works</em>, and <em>worked</em>) may share a same stem/root word and thus convey similar meaning. In text mining, we might want to treat such words as identical.</p><p><em>Originally published at </em><a href="https://curiositybits.cc/post/r_analytics11/"><em>https://curiositybits.cc/post/r_analytics11/</em></a><em> on February 25, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3aea912515e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From corpus to document-feature matrix]]></title>
            <link>https://curiositybits.medium.com/from-corpus-to-document-feature-matrix-ba2a94c66971?source=rss-6dc273954828------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba2a94c66971</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[social-media]]></category>
            <dc:creator><![CDATA[Wayne Xu]]></dc:creator>
            <pubDate>Mon, 25 Feb 2019 21:42:42 GMT</pubDate>
            <atom:updated>2019-03-04T22:07:25.942Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is a static and abbreviated version of this <a href="https://curiositybits.shinyapps.io/R_social_data_analytics/#section-text-mining-from-corpus-to-dfm">interactive tutorial</a> on using R for social data analytics.</p><h3>Text mining: From corpus to DFM</h3><p>There is a lot of interest in quantifying and visualizing textual data. Texts reveal <a href="https://blogs.wsj.com/numbers/mining-tweets-for-public-opinion-1118/">our thoughts</a>, <a href="https://wordwatchers.wordpress.com/">our personality</a>, and <a href="http://theconversation.com/how-twitter-gives-scientists-a-window-into-human-happiness-and-health-62255">the pulse of a society</a>. We broadly refer to the <em>quantification of text</em> as <em>text mining</em>. Thanks to the developments in <a href="https://en.wikipedia.org/wiki/Natural_language_processing">Natural Language Processing</a> and <a href="https://en.wikipedia.org/wiki/Information_retrieval">Information retrieval</a>, we now have a wide selection of easy-to-use R libraries for cleaning, transforming, quantifying, and visualizing text.</p><p><strong>Which R library?</strong></p><p>Throughout the tutorials on text mining, we will use the library <em>quantaeda</em>, which stands for Quantitative Analysis of Textual Data. You can visit the <a href="https://quanteda.io/">library website</a> to view many examples.</p><p>There is another decent text mining library called <em>tidytext</em>. Although we will not use it since there is a considerable overlap in functionality between the two libraries, I still highly recommend checking out <a href="https://cran.r-project.org/web/packages/tidytext/vignettes/tidytext.html">tidytext</a> and <a href="https://www.tidytextmining.com/">a free e-book</a> written by the library author.</p><p><strong>What data?</strong></p><p>You might get a wrong impression that the codes we have implemented so far only apply to Twitter data. Not at all. You can use the codes on any sort of data (e.g., Facebook posts, Reddit posts, news articles, Wikipedia entries, your personal texts/emails, etc.). In this tutorial, we will analyze Airbnb reviews in 2018 from three cities: Boston, Denver, and Rhode Island. The <a href="http://insideairbnb.com/get-the-data.html">data are shared</a> by the company Airbnb. The original datasets are enormous. But in our example, we will deal with randomly selected 9,000 reviews.</p><p><strong>Workflow</strong></p><p>A typical workflow in text mining is:</p><ol><li><strong>create a corpus from text files</strong>;</li><li><strong>tokenization</strong>;</li><li><strong>create a DFM</strong>;</li><li><strong>conduct a variety of text analyses</strong>.</li></ol><p><strong>Text file</strong></p><p>Text mining typically begins with text files (e.g., a data frame or a CSV file) containing character strings (the actual text) and the metadata of the text. Take a look at the example below (a data frame named <em>reviews</em>).</p><pre>library(quanteda) library(readr) library(dplyr) library(topicmodels) reviews &lt;- read.csv(&quot;https://curiositybits.cc/files/airbnb_reviews_2018_sample.csv&quot;) head(reviews)</pre><p>The <em>reviews</em> dataframe has a column called <em>comments</em>, which contains Airbnb users’ reviews. Along with it are metadata such as <em>date</em>, <em>city</em>, and etc.</p><p><strong>Corpus</strong></p><p>Think of a <em>corpus</em> as a container of different <em>documents</em>. A <em>corpus</em> is the complete collection of text you want to analyze, <em>Documents</em> are individual units in that collection. For example, if you want to analyze someone’s tweets (the corpus), each unique tweet can be treated as a document. Another example is: if you want to compare tweets sent by GOP and the Democratic Party, you can treat all tweets sent by one party as a single document. This treatment will lead you to have two documents in the corpus.</p><p>Let’s put the idea to test. Run the code below. The code will create a corpus of Airbnb reviews, which contains 9,000 documents (i.e., 9,000 reviews). In this example, each review has an unique id (the <em>id</em> column), the ids are used as the document IDs (docid_field = “id”); we specify the <em>comments</em> column as the text field so that R knows where to extract character strings.</p><pre>review_corpus &lt;- corpus(reviews,docid_field = &quot;id&quot;,text_field = &quot;comments&quot;) review_corpus</pre><p>The output shows that there are 9,000 documents in the corpus we have just created. Next, let’s test a bolder idea: creating a corpus in which reviews from each city will be combined and treated as a document.</p><pre>#create a new data frame with three rows, each containing reviews from a respective city reviews_bycity &lt;- aggregate(comments~city, data = reviews, paste0, collapse=&quot;. &quot;) #create a corpus based on the new data frame review_corpus_bycity &lt;- corpus(reviews_bycity,docid_field = &quot;city&quot;,text_field = &quot;comments&quot;) review_corpus_bycity</pre><p>Yes. the corpus created from the above step contains three documents, for Boston, Denver, and Rhode Island, respectively. We first create a new data frame (called reviews_bycity) by using aggregate() to merge reviews from the same city. Then, in corpus(), we specify <em>docid_field = “city”</em>. This tells R to recognize the city column as the document IDs.</p><p><strong>DFM</strong></p><p>With a corpus, we can go ahead and create a DFM (document feature matrix). What is a DFM? The best way to understand it is perhaps by playing around one.</p><p>Run the code below. It will construct a DFM based on the corpus of 9,000 documents.</p><pre>review_corpus &lt;- corpus(reviews,docid_field = &quot;id&quot;,text_field = &quot;comments&quot;) reviews_dfm &lt;- dfm(review_corpus) reviews_dfm[1:5,1:5] #show the first 5 words in the first 5 documents</pre><p><strong>How to make sense of a DFM?</strong></p><p>DFM is a matrix. Numbers in DFM represent how many times a token (commonly referring to a word or a sentence) appears in a given document. In the output above. The word <em>awesome</em> appears once in document <em>321027819</em>. Based on this interpretation, answer the quiz question below.</p><p><em>reviews_dfm[1:5,1:5]</em> gives you the frequency distribution of the first 5 words across the first 5 documents. The complete matrix (the object named reviews_dfm) is 13,894 by 9,000. It means that this dfm object has 13,894 features (i.e., words) across 9,000 documents.</p><p><strong>What’s next?</strong></p><p>After you have a DFM from your text data, you can do all sorts of things. For instance, run the code below will show you the most frequent terms in your corpus.</p><pre>library(quanteda) review_corpus &lt;- corpus(reviews,docid_field = &quot;id&quot;,text_field = &quot;comments&quot;) reviews_dfm &lt;- dfm(review_corpus) library(ggplot2) reviews_dfm %&gt;% textstat_frequency(n = 25) %&gt;% ggplot(aes(x = reorder(feature, frequency), y = frequency)) + geom_point() + coord_flip() + labs(x = NULL, y = &quot;Frequency&quot;) + theme_minimal()</pre><p>But, wait a minute! The most frequent terms are: <em>and</em>, <em>the</em>, <em>a</em>, period and comma? Shouldn’t we take those meaningless and noisy words out of the analysis?</p><p>You are right! What I have demonstrated above is a very messy and rudimentary step in text mining. The next topic will cover a set of standard text cleaning and transformation procedures.</p><p><em>Originally published at </em><a href="https://curiositybits.cc/post/r_analytics10/"><em>https://curiositybits.cc/post/r_analytics10/</em></a><em> on February 25, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba2a94c66971" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sentiment analysis]]></title>
            <link>https://curiositybits.medium.com/sentiment-analysis-cb507f8bad01?source=rss-6dc273954828------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb507f8bad01</guid>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data-mining]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[twitter]]></category>
            <dc:creator><![CDATA[Wayne Xu]]></dc:creator>
            <pubDate>Tue, 12 Feb 2019 05:15:06 GMT</pubDate>
            <atom:updated>2019-02-14T04:59:37.359Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is a static and abbreviated version of this <a href="https://curiositybits.shinyapps.io/R_social_data_analytics/#section-sentiment-analysis">interactive tutorial</a> on using R for social data analytics.</p><p>During the 2012 US presidential election, Twitter, in partnership with several polling agencies, launched something called <a href="https://www.socialmediatoday.com/content/twitter-political-index">Twitter Political Index</a>. The idea was to track candidates’ popularity among voters based on sentiment expressed in tweets. Back then, such idea was a novelty. Nowadays, sentiment analysis of social media text has been widely applied in <a href="https://ipullrank.com/step-step-twitter-sentiment-analysis-visualizing-united-airlines-pr-crisis/">marketing/PR</a>, <a href="https://techcrunch.com/2016/11/10/social-media-did-a-better-job-at-predicting-trumps-win-than-the-polls/">electoral forecasting</a>, and sports analytics. The NPR show Planet Money even built a <a href="https://twitter.com/botus?lang=en">Twitter bot</a> to automatically trade stocks based on sentiments in Trump’s tweets.</p><p>There are many types of sentiment analysis. Before you work on this tutorial, I assume you have reviewed <a href="https://curiositybits.cc/files/W4_sentimentdetection.pdf">this slide</a> in which I introduce different approaches to sentiment detection, its strengths and weaknesses. Sentiment analysis is an evolving field in information and computer science. The tutorial only touches upon the very basic of dictionary-based sentiment analysis. If you are keen on learning more, simply google “sentiment analysis” and “R.”</p><p>We will work with the same dataset from the last tutorial. The data contain tweets from the two political parties in the US (@GOP and @TheDemocrats). The task is to visualize the sentiment in their tweets over time. Like codes used in previous tutorials, with slight tweaks, you can make the code work for any sort of social media texts (e.g., Facebook posts, YouTube comments, Reddit posts, etc).</p><p>Yes. For this task we will use <em>syuzhet</em>, a library for extracting sentiments from text. Use <strong>install.packages()</strong> to install and <strong>library()</strong> to load <em>syuzhet</em>.</p><p><strong>How is sentiment detected?</strong> The library <em>syuzhet</em> uses the dictionary-based approach (as opposed to using supervised machine learning algorithms) in sentiment detection. It uses the <a href="http://sentiment.nrc.ca/lexicons-for-research/">NRC Emotion Lexicon</a> which rates words by eight dimensions: <em>joy</em>, <em>anger</em>, <em>anticipation</em>, <em>disgust</em>, <em>fear</em>, <em>sadness</em>, <em>surprise</em> and <em>trust</em>.</p><p>Run the code below. You should be able to see a plot showing the anger score over time for both parties.</p><pre>library(ggplot2) library(lubridate) library(reshape2) library(dplyr) library(syuzhet) #this is the library for sentiment detection library(stringr) partytweets &lt;- read.csv(&quot;https://curiositybits.cc/files/gop_thedemocrats_timeline.csv&quot;) #standardize timestamps partytweets$created_at &lt;- ymd_hms(partytweets$created_at) partytweets$created_at &lt;- with_tz(partytweets$created_at,&quot;America/New_York&quot;) partytweets$created_date &lt;- as.Date(partytweets$created_at) #create a factor column for dates; used for groupping in later steps partytweets$date_label &lt;- as.factor(partytweets$created_date) #clean the text partytweets$clean_text &lt;- str_replace_all(partytweets$text, &quot;@\\w+&quot;, &quot;&quot;) #extract sentiments Sentiment &lt;- get_nrc_sentiment(partytweets$clean_text) #combine the data frame containing sentiment scores and the original data frame containing tweets and other Twitter metadata alltweets_senti &lt;- cbind(partytweets, Sentiment) #aggregate the data by dates and screennames senti_aggregated &lt;- alltweets_senti %&gt;% group_by(date_label,screen_name) %&gt;% summarise(anger = mean(anger), anticipation = mean(anticipation), disgust = mean(disgust), fear = mean(fear), joy = mean(joy), sadness = mean(sadness), surprise = mean(surprise), trust = mean(trust)) %&gt;% melt senti_aggregated$day &lt;- as.Date(senti_aggregated$date_label) #plot the data ggplot(data = senti_aggregated[senti_aggregated$variable==&quot;anger&quot;,], aes(x = day, y = value, group = screen_name)) + geom_line(size = 0.5, alpha = 0.6, aes(color = screen_name)) + geom_point(size = 0) + ylim(0, NA) + theme(legend.title=element_blank(), axis.title.x = element_blank()) + ylab(&quot;Average sentiment score&quot;) + ggtitle(&quot;Sentiments Over Time&quot;)</pre><p><strong>Step 1: Standardize timestamps and text</strong></p><p>We use the same code from the last tutorial to standardize tweet timestamps based on the <strong>YYYY-MM-DD HH:MM:SS</strong> format. We add <strong>str_replace_all()</strong> to clear out screen names in tweet content and store the clean text in the column <strong>clean_text</strong>.</p><pre>library(ggplot2) library(lubridate) library(reshape2) library(dplyr) library(syuzhet) #this is the library for sentiment detection library(stringr) partytweets &lt;- read.csv(&quot;https://curiositybits.cc/files/gop_thedemocrats_timeline.csv&quot;) #standardize timestamps partytweets$created_at &lt;- ymd_hms(partytweets$created_at) partytweets$created_at &lt;- with_tz(partytweets$created_at,&quot;America/New_York&quot;) partytweets$created_date &lt;- as.Date(partytweets$created_at) #create a factor column for dates; used for groupping in later steps partytweets$date_label &lt;- as.factor(partytweets$created_date) #clean the text partytweets$clean_text &lt;- str_replace_all(partytweets$text, &quot;@\\w+&quot;, &quot;&quot;) partytweets[,c(&quot;text&quot;,&quot;clean_text&quot;)] #show two clumns (text and clean_text) in partytweets</pre><p><strong>Step 2: Create sentiment scores for tweets</strong></p><p>We apply the <strong>get_nrc_sentiment()</strong> function to the <strong>clean_text</strong> column and get sentiment rating for each tweet. The sentiment scores are stored in the newly created data frame <strong>Sentiment</strong>, with columns corresponding to the types of sentiment and rows matching tweets based on their original order in <strong>partytweets</strong>. We then use the <strong>rbind()</strong> to combine <strong>Sentiment</strong> and <strong>partytweets</strong> so that you can see exactly which tweet receives what sentiment rating (rbind() this is a function used for merging two data frames if they have the same number of columns).</p><pre>library(lubridate) library(reshape2) library(dplyr) library(syuzhet) #this is the library for sentiment detection library(stringr) partytweets &lt;- read.csv(&quot;https://curiositybits.cc/files/gop_thedemocrats_timeline.csv&quot;) #standardize timestamps partytweets$created_at &lt;- ymd_hms(partytweets$created_at) partytweets$created_at &lt;- with_tz(partytweets$created_at,&quot;America/New_York&quot;) partytweets$created_date &lt;- as.Date(partytweets$created_at) #create a factor column for dates; used for groupping in later steps partytweets$date_label &lt;- as.factor(partytweets$created_date) #clean the text partytweets$clean_text &lt;- str_replace_all(partytweets$text, &quot;@\\w+&quot;, &quot;&quot;) partytweets[,c(&quot;text&quot;,&quot;clean_text&quot;)] #show two clumns (text and clean_text) in partytweets #extract sentiments Sentiment &lt;- get_nrc_sentiment(partytweets$clean_text) #combine the data frame containing sentiment scores and the original data frame containing tweets and other Twitter metadata alltweets_senti &lt;- cbind(partytweets, Sentiment) alltweets_senti[1:20,] #show the first 20 rows for preview of the data</pre><p><strong>Step 3: Create daily sentiment scores</strong></p><p>Like how we aggregate data in the last tutorial, we use <strong>group_by()</strong> and <strong>summarise()</strong> to aggregate the data frame <strong>alltweets_senti</strong> based on two columns:<strong>screen_name</strong> and <strong>date_label</strong>. The aggregated data frame is called <strong>senti_aggregated</strong>.</p><p><strong>senti_aggregated</strong> includes daily average counts of each sentiment type for each Twitter account. For example, if @GOP sent 6 tweets on a given day, to calculate the daily anger score, we sum up the anger scores of the 6 tweets and divide the sum by 6.</p><pre>library(lubridate) library(reshape2) library(dplyr) library(syuzhet) #this is the library for sentiment detection library(stringr) partytweets &lt;- read.csv(&quot;https://curiositybits.cc/files/gop_thedemocrats_timeline.csv&quot;) #standardize timestamps partytweets$created_at &lt;- ymd_hms(partytweets$created_at) partytweets$created_at &lt;- with_tz(partytweets$created_at,&quot;America/New_York&quot;) partytweets$created_date &lt;- as.Date(partytweets$created_at) #create a factor column for dates; used for groupping in later steps partytweets$date_label &lt;- as.factor(partytweets$created_date) #clean the text partytweets$clean_text &lt;- str_replace_all(partytweets$text, &quot;@\\w+&quot;, &quot;&quot;) partytweets[,c(&quot;text&quot;,&quot;clean_text&quot;)] #show two clumns (text and clean_text) in partytweets #extract sentiments Sentiment &lt;- get_nrc_sentiment(partytweets$clean_text) #combine the data frame containing sentiment scores and the original data frame containing tweets and other Twitter metadata alltweets_senti &lt;- cbind(partytweets, Sentiment) senti_aggregated &lt;- alltweets_senti %&gt;% group_by(date_label,screen_name) %&gt;% summarise(anger = mean(anger), anticipation = mean(anticipation), disgust = mean(disgust), fear = mean(fear), joy = mean(joy), sadness = mean(sadness), surprise = mean(surprise), trust = mean(trust)) %&gt;% melt senti_aggregated</pre><p>**Step 4: Visualize it **</p><p>We use <strong>ggplot()</strong> to visualize the data frame <strong>senti_aggregated</strong>.</p><p>We enter the following in the code because we want to visualize daily anger scores only. That means we filter out observations in <strong>senti_aggregated</strong> with the value equal to “anger” in the <strong>variable</strong> column.</p><pre>data = senti_aggregated[senti_aggregated$variable==&quot;anger&quot;,]</pre><p>If you want to plot daily average anticipation score, simply set:</p><pre>data = senti_aggregated[senti_aggregated$variable==&quot;anticipation&quot;,]</pre><pre>library(lubridate) library(reshape2) library(dplyr) library(syuzhet) #this is the library for sentiment detection library(stringr) partytweets &lt;- read.csv(&quot;https://curiositybits.cc/files/gop_thedemocrats_timeline.csv&quot;) #standardize timestamps partytweets$created_at &lt;- ymd_hms(partytweets$created_at) partytweets$created_at &lt;- with_tz(partytweets$created_at,&quot;America/New_York&quot;) partytweets$created_date &lt;- as.Date(partytweets$created_at) #create a factor column for dates; used for groupping in later steps partytweets$date_label &lt;- as.factor(partytweets$created_date) #clean the text partytweets$clean_text &lt;- str_replace_all(partytweets$text, &quot;@\\w+&quot;, &quot;&quot;) partytweets[,c(&quot;text&quot;,&quot;clean_text&quot;)] #show two clumns (text and clean_text) in partytweets #extract sentiments Sentiment &lt;- get_nrc_sentiment(partytweets$clean_text) #combine the data frame containing sentiment scores and the original data frame containing tweets and other Twitter metadata alltweets_senti &lt;- cbind(partytweets, Sentiment) senti_aggregated &lt;- alltweets_senti %&gt;% group_by(date_label,screen_name) %&gt;% summarise(anger = mean(anger), anticipation = mean(anticipation), disgust = mean(disgust), fear = mean(fear), joy = mean(joy), sadness = mean(sadness), surprise = mean(surprise), trust = mean(trust)) %&gt;% melt senti_aggregated$day &lt;- as.Date(senti_aggregated$date_label) #plot the data ggplot(data = senti_aggregated[senti_aggregated$variable==&quot;anger&quot;,], aes(x = day, y = value, group = screen_name)) + geom_line(size = 0.5, alpha = 0.6, aes(color = screen_name)) + geom_point(size = 0) + ylim(0, NA) + theme(legend.title=element_blank(), axis.title.x = element_blank()) + ylab(&quot;Average sentiment score&quot;) + ggtitle(&quot;Sentiments Over Time&quot;)</pre><p>**Try interactive plotting ** <strong>ggplot2</strong> is a great library for visualization. But if you want to create an interactive plot, you will use a library called <a href="https://ramnathv.github.io/rCharts/"><em>rCharts</em></a>.</p><p>To install rCharts, run the following code.</p><pre>require(devtools) install_github(&#39;rCharts&#39;, &#39;ramnathv&#39;)</pre><p>After rCharts is installed and loaded, run the following code on the <strong>senti_aggregated</strong> data frame.</p><pre>library(rCharts) senti_aggreated$day_show &lt;- as.character(senti_aggreated$date_label) h1 &lt;- hPlot(x = &quot;day_show&quot;, y = &quot;value&quot;, data = senti_aggreated[senti_aggreated$variable==&quot;anger&quot;,], type = &quot;line&quot;, group = &quot;screen_name&quot;) h1$print(&quot;chart5&quot;,include_assets = TRUE) h1</pre><p><em>Originally published at </em><a href="https://curiositybits.cc/post/r_analytics9/"><em>https://curiositybits.cc/post/r_analytics9/</em></a><em> on February 12, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb507f8bad01" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>