<?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 Jan Rus on Medium]]></title>
        <description><![CDATA[Stories by Jan Rus on Medium]]></description>
        <link>https://medium.com/@jan.rus?source=rss-356b0cf27f5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*DaX9VN1Dq0EDhGYt.jpg</url>
            <title>Stories by Jan Rus on Medium</title>
            <link>https://medium.com/@jan.rus?source=rss-356b0cf27f5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 14:30:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jan.rus/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[Sentiment Analysis at Socialbakers]]></title>
            <link>https://medium.com/socialbakers-engineering/sentiment-analysis-at-socialbakers-c98cf7c908e?source=rss-356b0cf27f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c98cf7c908e</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Jan Rus]]></dc:creator>
            <pubDate>Mon, 23 Mar 2020 09:56:09 GMT</pubDate>
            <atom:updated>2020-03-23T15:39:12.150Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mQqnGJj0iKQaD6SpFeiARA.png" /></figure><p>Our Innovations team at <a href="https://www.socialbakers.com/">Socialbakers</a> was working on a very interesting task last year, <em>sentiment analysis</em> for social media. In the context of our work, sentiment analysis is an automated process of text analysis leading to a prediction of how an audience feels towards any given subject from texts of social media messages.</p><p>The result of this process is a <em>classification</em> of the texts into 3 classes: positive, neutral and negative.</p><p>Such text analysis can be rented as a service these days, but our goal was a system that can analyze 150,000,000 messages in 5–10 different languages every day. We researched this option and found out that it would be an extremely expensive service to rent even from the cheapest providers on the market in 2019.</p><p>Moreover, most text analysis tools and services are not fine-tuned to social media and don’t support all languages we are interested in such as Czech or Arabic.</p><p>So, we decided to build the solution in-house. We shared the architecture of our deep learning solution (recurrent neural network) and the necessary theoretical background in the previous post: <a href="https://medium.com/socialbakers-engineering/sentiment-analysis-at-socialbakers-ca10f567eed9">Theoretical Introduction and Architecture</a>¹.</p><p>But as we wrote at the end of the blog post, we think that the largest building block of any successful deep learning project is the data. If the neural network is a student then the dataset is a textbook.</p><h3>Data for Deep Learning POC</h3><p>In the case of courses, trainings or competitions deep learning practitioners often start their work with given training and test datasets. They can invest their effort into algorithms and tuning of their parameters from the very beginning.</p><blockquote><strong>In practice, the work starts with getting the dataset first.</strong></blockquote><p>Ideally, research teams can find an open-source dataset that is large, high quality and matches the goal (including domain) of the deep learning project but it is a very rare situation. The research teams usually have three options: 1) to build the perfect manually annotated dataset from scratch in-house which is an expensive and time-consuming process, 2) to find and combine the right but smaller datasets from different sources with lower and varying quality that at least partially overlap with the goal of the project or 3) to find a way how to create a dataset with labels derived from a different but related information. The 2) and 3) may lead to larger but noisy datasets or even a necessity of <em>transfer learning</em>².</p><h4>The First Dataset</h4><p>After initial research, we realized that it will be hard to find publicly available datasets with texts and sentiment labels that would fit our needs. Datasets we found were:</p><ul><li><strong>small</strong>, having only 500–1,000 samples is currently unsuitable for such deep learning project,</li><li><strong>using only 2 classes</strong> (positive and negative), while we need 3 classes,</li><li><strong>from a different domain</strong>, for example, long movie reviews,</li><li><strong>having wrong properties</strong> such as too long texts missing slang or emojis,</li><li><strong>licensed</strong> in a way that prevents us from using them even for experiments.</li></ul><p>Simply, nothing close to a large dataset of short social media messages in a number of different languages and sentiment labels with 3 classes. We, therefore, started to evaluate the more laborious options:</p><ul><li><strong>Amazon Mechanical Turk</strong>: unnecessarily expensive and without decent control over the quality of the annotations. We would need multiple annotations per text to keep the quality high and so we estimated the cost to at least $15,000 just for the English training set of 200,000–300,000 texts annotated by 3–5 annotators.</li><li><strong>Client sentiment labels</strong>: it is possible to label sentiment in our Socialbakers Suite manually, so we have a large number of such labels in our databases. Here, we worried (and experimentally confirmed) the quality of annotations would suffer as well because the clients are not trained to do the job, they are also biased and they also use the labels for different purposes in some cases.</li><li><strong>Customer product reviews</strong>: these datasets are mostly pairs of textual reviews and up to 5 stars assigned to the reviewed product, for example, <em>Amazon reviews</em>³. The number of stars can be used as a noisy sentiment label (the more starts the more positive sentiment). We researched a few such datasets and concluded that a) the number of stars doesn’t correlate well with the sentiment of the textual review and b) a customer review sentiment is different from the common conversation sentiment. Consider that the typical “positive” phrases in these datasets are phrases like <em>low price</em>, <em>quick delivery</em> or <em>100% leather</em>. The last argument against such datasets is that they are mostly not available for commercial use.</li></ul><p>We experimented with even more options that didn&#39;t work for us at the end, but the last option in the list above was closest to our idea of how we may get the first data for our deep learning proof of concept.</p><p>We intended to use a widespread noisy (not always correct) labels that could be quickly and automatically gathered on a large scale and correlated with the sentiment in the related texts.</p><p>Social media messages are full of emojis and we decided to use the emojis as the noisy automatically gathered sentiment labels. We focused on English first, because it is a very frequent language with a higher chance to find some available datasets and competitive algorithms for benchmarking. But in general, this approach would enable us to build datasets for any language.</p><p>Our approach was to download a sample of Facebook messages written in English (we used PyCLD⁴ for language detection) and for each message:</p><ul><li>extract all emojis,</li><li>map each emoji to a sentiment class,</li><li>use the most frequent sentiment class as a label for the original message.</li></ul><p>If there was no emoji found in the message or if there wasn’t a single most frequent sentiment class assigned to the emojis (e.g. the same amount of positive and neutral emojis appeared in the message), the message was removed from the dataset, see example in image 1 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*694QNpje5ySrvdMwqspIQg.png" /><figcaption>Image 1: Mapping emojis to sentiment label.</figcaption></figure><p>The mapping between emojis and sentiment was made in-house but it is a very small amount of work in comparison to the manual annotation of all the downloaded messages. With this approach, we quickly prepared a balanced dataset of 38,000 social media messages written in English. This was our source for the first training and validation datasets.</p><p>Next, we created a small balanced dataset consisting of 500 Facebook messages (not all of them contained emojis) which were labeled manually by our Innovations team. This was our first test dataset. The reason to choose this approach was that we knew that we are not able to build a large<br>hand-labeled dataset in a short time but we are able to quickly build at least a test set this way and have a well-defined target to aim on.</p><p><em>The messages we use in this project are publicly available user comments provided by Facebook and other social networks via their APIs. They are anonymized.</em></p><h4>Performance Benchmark</h4><p>To be able to measure our progress during the project, we needed to set up an accuracy benchmark. We had no KPIs in place at this phase but we used a well-known sentiment analysis library called <em>VADER</em>⁵ as a benchmark. The VADER is a very lightweight model based on the valence lexicon and a set of linguistic rules, it was the cheapest solution and also the fastest to deliver we were aware of. A tempting solution for quick prototyping in the commercial sphere. The only (and significant) drawback is the dictionary itself that exists only for English and we would need an expert in linguistics to be able to extend it to other languages. We wanted to overcome this drawback and prove that a machine learning solution will be not just easier to extend and maintain but also better performing on our use case. Overall, a better approach in the long term. The VADER became the lower threshold for the benchmark.</p><p>Next, we chose the <em>inter-annotator agreement</em>⁶ to be the upper threshold for the benchmark. If you ask a group of people to label the sentiment of the given set of texts, you will find out that there will be some examples where they will not agree on the sentiment, i.e. they will not agree in 100% cases. It would be therefore naive to expect that a machine learning algorithm would achieve better results. It has been experimentally proven that the typical inter-annotator agreement in sentiment analysis is approximately 80%⁶. This means that if an algorithm reaches 80% accuracy, it has approximately a human-level performance.</p><p>Last, we picked 2 services (APIs) providing sentiment analysis as a reference: <em>MeaningCloud</em> and <em>Amazon Comprehend</em>. We analyzed the first test set with these two services and the VADER, measured their accuracy and constructed the benchmark. See chart 1 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KSsfkGY8mDX6u7bzG6agig.png" /><figcaption>Chart 1: Accuracy benchmark for our POC.</figcaption></figure><h4>The First Experiment</h4><p>During the first series of experiments, we tuned, trained and validated our neural network on the dataset of 38,000 emoji-labeled Facebook messages. Then, we run a test against the 500 Facebook messages labeled by our Innovations team.</p><blockquote><strong>We failed really badly.</strong></blockquote><p>We achieved accuracy better than random (which is 33%) but much worse than VADER which we intended to beat, see the accuracy measurements in table 1 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-tLcxEP6XR68LUF9muDvrg.png" /><figcaption>Table 1: Accuracy measurements for a model trained on the emoji-labeled dataset.</figcaption></figure><p>We suspected the problem is in the training dataset immediately. VADER was working worse on the emoji-labeled dataset than on the manually labeled dataset. On the other hand, the neural network learned to work quite well on the emoji-labeled dataset and then totally failed on the manually labeled dataset. So the neural network can learn to predict emojis from a text but it doesn’t help it to predict sentiment from a text. It’s not that surprising in retrospective.</p><p>In contrast to for example stars and customer reviews, the emojis are an integral part of the messages. If we remove the emojis from the text and use them as a sentiment label, we may completely change the meaning of the message (especially if it’s a short message) and build a very noisy labeled dataset. If we keep the emoji in the message, the network will likely learn to predict the sentiment mostly based on the emojis (remember the 96% accuracy on the validation set above). We experimented with both but the results on the test dataset were more or less the same.</p><h4>The Second Dataset and Experiment</h4><p>Due to the tight time constraints and lessons taught during the previous experiments, we avoided using any hints to a sentiment of a text hidden in the text itself (emojis, hashtags, etc.) in the future and built the next dataset with real sentiment labels exploiting VADER and two more third-party services. We managed to do this practically at no cost. We kept only the messages where the sentiment analysis algorithms agreed as sufficiently reliable for our training set (approximately 80% of cases). This way we obtained a balanced dataset of 147,000 English social media messages with sentiment labels.</p><p>We repeated the previous experiment with training and validating on one dataset and testing on the manually labeled dataset and we finally succeeded, see table 2 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pcnkVcSvsFblrY1Bl5UBCw.png" /><figcaption>Table 2: Accuracy measurements for a model trained on the automatically-labeled dataset.</figcaption></figure><p>The results may be a bit misleading because the test set is very small (only 500 messages) and the training/validation set is probably not very challenging (a subset of the original dataset where multiple algorithms agreed) but it was a good signal and reliable enough to get support from the Product Management team. Until now, it was just a proof of concept created by 2 team members in 3 weeks in parallel with other higher-priority projects.</p><h3>In-house Sentiment Dataset</h3><p>After a discussion of the results with the stakeholders, we decided to continue in the project, to invest effort into building the infrastructure and further experiments with our own machine learning solution. We also agreed that we can start cooperating with our internal tagging team on building a manually labeled dataset for this sentiment analysis project. The Taggers proved to be a tremendous help on many occasions since then. In the beginning, we wanted to use the created dataset only as a test set. But with a larger volume of data, we could start to mix a fraction of the dataset into training and validation sets and ideally end up with a dataset large enough to train, validate and test our models only on this dataset itself.</p><h4>Crash Course for Annotators</h4><p>The Taggers team underwent a crash course on the sentiment analysis and how to label the datasets. Then, we selected 5 of them, asked them to label a set of approximately 400 texts and calculated their inter-annotator agreement. They reached almost 90% agreement which is higher than the claimed typical inter-annotator agreement (80%) but it’s likely due to the fact that the Taggers are trained and they are trained to work as a team (a single annotator). Such a high agreement encouraged us to let the team to label each text of the target dataset by only one annotator (typically multiple untrained annotators label every single text to achieve a higher quality of the labels) and progress faster to the first milestone that was set to 100,000 labeled English Facebook messages.</p><p>Once the team produced a dataset of 15,000 labeled texts, we proceeded to a test of alignment to be able to identify and fix eventual small discrepancies in time. We used the previously trained model and predicted sentiment for the original small dataset of 500 Facebook messages labeled by our Innovations team. Next, we used the same model to predict the sentiment for the larger new (unbalanced) dataset of 15,000 Facebook messages labeled by the team of annotators and compared the achieved accuracies.</p><blockquote><strong>We failed badly again.</strong></blockquote><p>We expected the accuracy will change with a larger and more robust test dataset but we didn’t expect it to drop by 14%, from 75% to <strong>61%</strong> failing to beat the VADER again.</p><h4>What is Sentiment</h4><p>Such a suspiciously big drop in performance motivated us to start researching the cause immediately. Luckily, we monitored which annotator labeled which text. We filtered the messages where labels created by the Taggers team were different from predictions of the model and looked for outliers: taggers with a significantly worse agreement with the model than others. We didn’t find them. Not just the amount, but also the distribution of positive, neutral and negative labels were similar for all annotators. It looked like a systematic error. The team of annotators (true labels) tends to a wider range of what is neutral than the model (predictions), see chart 2 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vIlZcPrba6NpegxFYGHTfA.png" /><figcaption>Chart 2: Distribution of true labels and predictions with the old labeling manual.</figcaption></figure><p>We decided to relabel a small subset of these different messages only in the Innovations team and we inclined (also systematically) to the results of the model, not the Taggers team. In fact, it was good news. Systematic errors are easier to uncover, understand and fix than random errors.</p><p>We organized another training session with the Taggers team, shared our findings and followed with a discussion about the possible cause of the systematic discrepancy between labels provided by the Innovations team, the model and the Taggers team. The outcome was quite surprising. <strong>Their high-level understanding of what is sentiment was different from ours.</strong> They understood sentiment as to <strong>how an author feels</strong> when writing the given text, for us it was <strong>how a reader feels</strong> when reading the given text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Y3oRTsrW68yNbgilfGi5g.png" /><figcaption>Image 2: This sample text was labeled as neutral by Taggers because it’s an ad (the author feels neutral) and positive by Innovations because we had a positive feeling while reading the text.</figcaption></figure><p>It’s a crucial principle yet something we didn’t think of before and didn’t cover with examples in the labeling manual. What the Taggers did wasn’t wrong. It was an interesting finding, another point of view and we needed to know which one is the right one. We prepared a questionnaire with a description of sentiment analysis, the issue we were facing and a set of 20 examples of texts with questionable sentiment labels. This document was shared with selected Socialbakers employees and clients and collected feedback uncovered that the <strong>how a reader feels</strong> point of view is the more desirable one. We updated the labeling manual with this enlightening discovery, ask Taggers to relabel affected part of the manually labeled dataset and then continue in pursuing the 100,000 dataset milestone.</p><p>Shortly thereafter, when the Taggers team reached 20,000 manually labeled texts, we repeated the alignment test and were happy with the result. You can see in the chart 3 below that the distribution of the predicted and labeled sentiment became better defined, the positive and negative classes were rarely confused with the neutral class and the (balanced and unbalanced) accuracy achieved by the model on this dataset raised to 77%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bvLzgUCc7_UN5_rZJiGUEQ.png" /><figcaption>Chart 3: Distribution of true labels and predictions with the new labeling manual.</figcaption></figure><p>With the growing and more robust test set, the accuracy of our solution slowly dropped to 70% after some time. We kept searching for and experimenting with new sources of sentiment labels and mixing them together to counter fight the drop in the performance. But once the team of annotators reached another milestone of 200,000 labeled messages, we started to use this dataset for training and validation as well and pushed the performance of our sentiment analysis model even further.</p><h3>Summary</h3><p>You can see that it is not a straightforward task to build a dataset for a machine learning project. Even for businesses. But having the (bug-fixed) labeling manual, a trained team of annotators and a large amount of data from the right domain allowed us to build a large high-quality dataset of English social media messages with sentiment labels.</p><p>This is the end of this episode. This is where many machine learning projects just begin.</p><p>Sounds interesting? Check out more of our <a href="https://medium.com/socialbakers-engineering">stories</a> &amp; don’t forget <a href="https://www.socialbakers.com/careers?utm_source=mediumblog&amp;utm_medium=.&amp;utm_campaign=Sentiment_Analysis_2">we’re hiring</a>!</p><h3>Notes and References</h3><p>[1]: Sentiment Analysis: Theoretical introduction and Architecture<br><a href="https://medium.com/socialbakers-engineering/sentiment-analysis-at-socialbakers-ca10f567eed9">https://medium.com/socialbakers-engineering/sentiment-analysis-at-socialbakers-ca10f567eed9</a></p><p>[2]: Transfer learning, exploiting a knowledge gained while solving a different but related problem, see a brief description here:<br><a href="https://en.wikipedia.org/wiki/Transfer_learning">https://en.wikipedia.org/wiki/Transfer_learning</a></p><p>[3]: Amazon Customer Reviews dataset<br><a href="https://s3.amazonaws.com/amazon-reviews-pds/readme.html">https://s3.amazonaws.com/amazon-reviews-pds/readme.html</a></p><p>[4]: PyCLD, Python bindings for the Compact Language Detect 2<br><a href="https://github.com/aboSamoor/pycld2">https://github.com/aboSamoor/pycld2</a></p><p>[5]: VADER, a lexicon and rule-based sentiment analysis tool<br><a href="https://github.com/cjhutto/vaderSentiment">https://github.com/cjhutto/vaderSentiment</a></p><p>[6]: How Companies Can Use Sentiment Analysis to Improve Their …, 2012<br><a href="https://mashable.com/2010/04/19/sentiment-analysis">https://mashable.com/2010/04/19/sentiment-analysis</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c98cf7c908e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/socialbakers-engineering/sentiment-analysis-at-socialbakers-c98cf7c908e">Sentiment Analysis at Socialbakers</a> was originally published in <a href="https://medium.com/socialbakers-engineering">Emplifi</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sentiment Analysis at Socialbakers]]></title>
            <link>https://medium.com/socialbakers-engineering/sentiment-analysis-at-socialbakers-ca10f567eed9?source=rss-356b0cf27f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca10f567eed9</guid>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Jan Rus]]></dc:creator>
            <pubDate>Mon, 01 Jul 2019 09:16:39 GMT</pubDate>
            <atom:updated>2020-03-23T11:35:24.680Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9lolWiP6AfvOn0X3Hz-9jQ.png" /></figure><p>One of the problems our Innovations team is working on at Socialbakers is <em>sentiment analysis</em>. Sentiment analysis is an automated process of recognition of how an audience feels towards any given subject from written or spoken language. It is one of the most common classification tools exploiting artificial intelligence. Sentiment analysis algorithm analyzes given text and predicts whether the underlying sentiment is positive, neutral or negative.</p><p>Socialbakers is a global AI-powered social media marketing company and there are many use cases for sentiment analysis in our marketing software-as-a-service platform, called the Socialbakers Suite. For example, clients need to understand how people feel about their brand or campaign and we can analyze user conversations related to their campaign posts to discern how they feel. Another example is customer relationship management. Imagine thousands of messages filling a brand’s inbox every day — it’s extremely difficult to read and properly respond to each of them. This is when sentiment analysis can help them to filter and prioritize the importance of each case, and decide which must be dealt with first.</p><p>Knowing how important this feature is, we decided to deliver corresponding functionality to the Socialbakers Suite in the shortest possible time. We researched available 3rd-party solutions and realized that none of them fit our needs completely:</p><ul><li>They typically cover only a very limited set of languages (especially open-source projects) but our clients are spread all around the world</li><li>They can be quite expensive, considering the tens of millions of messages we need to process every day</li><li>They are not well-suited to social media messages (short texts on a wide range of topics containing slang and practically no context) a nightmare for most <em>NLP</em> (natural language processing) algorithms in general</li></ul><p>Therefore, we decided to build our sentiment analysis solution in-house. The Innovations team has six members and is responsible for the design, research and development of “smart features” for Socialbakers products. This involves exploiting big data analysis and machine learning techniques. It’s our job to create concepts and bring them from concepts to working prototypes and production implementations. So, just another day in paradise.</p><p>By the way, an entertaining demonstration of our solution has been <a href="https://www.linkedin.com/feed/update/urn:li:activity:6536588528325808128">published by Socialbakers’ Data Analysis Team on LinkedIn recently</a>. They have applied our sentiment analysis algorithm to user comments published on the Game of Thrones Facebook page. They did this one day prior and one day after the premiere of each episode of season 8. The results correlate with the feelings of Game of Thrones fans across the internet during the same time period. See image 1 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LlNIAdwCQDrnqx1Adch9yQ.png" /><figcaption>Image 1: Evolution of sentiment of Game of Thrones fans during season 8.</figcaption></figure><p>A state-of-the-art approach to sentiment analysis exploits <em>recurrent neural networks</em>. This blog post presents an architecture of our solution and briefly discusses the theoretical background necessary to understand our approach. The following blog posts will focus on how we gathered the data necessary for training our neural network and how we built and deployed the solution into production. Getting the right data and fine-tuning the system to the data are, in our experience, the crucial parts of such projects.</p><h3>Introduction to Recurrent Neural Networks</h3><p>Before we explain HOW we built our sentiment analysis algorithm, let’s look at the very basic theory about WHAT we built first. A recurrent neural network is an essential part of our solution and like any other neural network, it consists of neurons.</p><h4>Neurons</h4><p>Every <em>neuron</em> has 1 or more inputs, 1 output and performs 2 elementary operations, see image 2 below. Firstly, it reads data from the inputs and calculates a weighted sum of all input values. Secondly, it applies the so-called <em>activation function</em> on the sum and exposes the result at its output. Value at the output of a neuron represents <em>activation</em> (strength of response) of a neuron caused by given input. The magnitude of the activation is affected by the specific <em>weights</em> applied in the weighted sum operation (the weights are set by training the neural network) and selecting the activation function, which transforms numbers from a potentially infinite range (resulting from the sum operation) to a very narrow range, typically between 0 and 1¹. Neurons also typically have a so-called <em>bias</em> term that is trained together with the weights but it is not shown in schemes. This term is added to the sum and shifts the whole input of the activation function. You can read about shifting a decision boundary in this context sometimes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZhMgNvJWHudrRO5dT053nw.png" /><figcaption>Image 2: Scheme of a neuron. Input values 25, 1 and 0.2 activate this neuron to 0.98 out of 1.0.</figcaption></figure><h4>(Deep) Neural Networks</h4><p>A <em>neural network</em> is a set of neurons, typically arranged into <em>layers</em>², see image 3 below. The first layer stores input values of a network (e.g. representation of words of a sentence, see Word Embeddings) and it is called an <em>input layer</em>. The last layer stores the result of the network (e.g. predicted sentiment classes) and it’s called an <em>output layer</em>. The rest of the layers are so-called <em>hidden layers</em> and that’s where most of the artificial intelligence of a neural network is hidden. The more neurons a neural network contains, the more expressive it is and the more complex problems it is capable of solving.</p><p>Arranging the neurons into a larger number of narrower hidden layers (in contrast to shallow networks with wide hidden layers) enables data scientists to significantly decrease the number of neurons in the network while maintaining the original expressiveness. Thus, deeper networks allow us to build solutions to more complex problems without needing to consume significantly more computational resources. Once the network has 2 or more hidden layers, we say it is a <em>deep neural network</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*42vi-U9TtJ5USn5ebFcmVg.png" /><figcaption>Image 3: Scheme of a basic neural network with 3 input values <em>x</em> and 1 output value <em>y</em>. Shallow network on the left, deep network on the right, both consist of 12 neurons.</figcaption></figure><h4>The Weakness of Feed-forward Neural Networks</h4><p>As you can see in image 3 above, the architecture of such a neural network allows the information to flow in only one direction, straight from the input to the output layer (see the arrows). The input and output layers have a fixed size and there is no <em>a priori</em> structure in the input — everything is processed at once. Such architecture has a bad notion of order and doesn’t perform well in the processing of sequential data (time series, speech, text, audio) in general. While processing a sequence of numbers, this architecture can grasp that a value in neuron 2 has to be followed by a larger value in neuron 3 to detect “growth” in the data (which is a very specific rule just for neurons 2 and 3). But it cannot grasp well that a value in neuron <em>n</em> has to be followed by a larger value in neuron <em>n+1</em> to derive a general rule for recognition of “growth”. To achieve decent performance with such an architecture, a network has to have an unnecessarily large number of neurons and larger training data set.</p><h4>Recurrent Neural Networks</h4><p><em>Recurrent neural networks</em> (RNNs) overcome the weakness of <em>feed-forward neural networks by</em> introducing a recurrent element with memory into the architecture. RNNs don’t process the whole input sequence at once (in contrast to the previously mentioned architecture) they process it entry by entry. In our case, instead of processing the whole sentence, RNN consumes the input sentence iteratively, word by word. In every iteration:</p><ol><li>a word is read by the <em>recurrent unit</em> (e.g. recurrent hidden layer)</li><li>last known state of the recurrent unit is loaded from memory</li><li>(1) and (2) are combined resulting in a new state of the recurrent unit</li><li>the result is stored in memory (replacing last known state) and can be forwarded deeper in the network</li></ol><p>An <em>a priori</em> structure or order is introduced into data this way. Simply, an RNN reads a word while keeping a representation of a sequence of previously read words in memory and considering them during the analysis of the word, see image 4 below.</p><p>RNN can for example read a sequence of words of arbitrary size and produce a single label at the output (N:1, N words are read and 1 sentiment class label is returned), or read a single word and produce whole sentence (sequence of words) at the output (1:N, one word is read and the whole poem is generated) or read a sequence of words and produce a sequence of words (N:M, an English sentence having four words is translated into a French sentence having six words).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pd1_MtqLOEu4PfqubiT0Dw.png" /><figcaption>Image 4: Scheme of a recurrent unit (e.g. layer) <em>H</em> with the previous state of the layer (in memory) <em>h</em>.</figcaption></figure><h3>Word Embeddings</h3><p>In general, neural networks are made to process numbers, not words. Therefore applying them to NLP tasks, such as sentiment analysis, requires preprocessing of the input data to represent the analyzed texts with scalars (numbers) or vectors (lists of numbers).</p><h4>Word Representations</h4><p>A simple and widespread approach to a <em>word representation</em> is to represent a limited set of acceptable words with a set of orthonormal vectors — every word is represented with a unique vector consisting of all <em>0</em>s and only one <em>1</em>, it is called <em>one-hot encoding</em>. For example, for a set of four words: (good, bad, and, ugly), we get a set of four one-hot encoded <em>word vectors</em>: ([1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]).</p><p>As you can see, every word occupies its own dimension (position in a vector) and makes individual word vectors independent from the mathematical point of view — that comes in handy when processing with machine learning algorithms. The dimension of the vectors equals the number of words in the dictionary (only words recognized by the network), which is the key drawback of this approach. With an increasing number of words increases also the dimension of the vectors and the size of the input layer and the number of neurons of the neural network. This leads to a higher demand for computational resources during the training and application of the network.</p><h4>Word Embeddings</h4><p><em>Word embedding</em> can overcome the high-dimensionality issue at the cost of losing the independence of the word vectors. It’s a process of reprojection of (one-hot encoded) word vectors from high-dimensional space into low-dimensional space.</p><p>This transformation is frequently designed to not only significantly reduce the dimensionality of the data but also to place similar words close to each other in the new space (it depends on the definition of similarity). In other words, we move from representation, where every word occupies its own dimension and word vectors have nothing in common to representation, where words share dimensions and similar words have similar vector representation. Thanks to this new property, neural networks can more successfully process unseen combinations of words.</p><p>For example, we want to build a neural network that reads a sentence and outputs “true” or “false” value, based on whether the sentence is or isn’t a fact. A sentence “A banana is a fruit.” is used during training of the network and the network learns it is “true”. Then, it has to process the sentence “An orange is a fruit.”. It has never seen this sentence before. Thanks to word embeddings, the network knows “banana” and “orange” are similar to each other (they have very similar word vectors) and it decides to evaluate the sentence in a similar way — “true”.</p><p>The calculation of word embeddings is a lengthy, computationally expensive process requiring a lot of data. Therefore, a common practice is to use precalculated embeddings (word vectors), such as <em>word2vec³</em> or <em>GloVe⁴</em>, prepared by research teams who have the necessary resources. Most of these word embeddings use a similarity metric based on the context within a sentence or frequency of co-occurring words — a semantic similarity. There are also more advanced approaches that consider subwords or even generate embeddings on the fly based on the given combination of a word and its actual context (<em>ELMo</em>⁵, <em>BERT</em>⁶). But for all of them, similar words are words with similar meanings. Which is not our case.</p><h4>Sentiment Word Embeddings</h4><p>We decided to build our own word embedding in-house because we think that using the embeddings mentioned previously could confuse our algorithm. They use similarity metrics based on the similarity of meaning or context of words. Considering our use case, we suppose that a similarity metric based on the similarity of the sentiment of given words will lead to a better separation of positive and negative words. This helps with better identification of what kinds of things make whole sentences positive, negative or neutral.</p><p>For example, the words “good” and “bad” have a similar context in sentences but very different sentiments. On the other hand, the words “science” and “politics” have a different context in sentences but the sentiment is rather neutral in both cases.</p><p>You can see an example of a sentiment-based embedding in image 5 below. We have selected the 50,000 most frequent tokens (words, emojis, symbols, etc.) and created an embedding into 300-dimensional space. Then, only a subset of emojis was selected and their word vectors were projected onto a 2D plane using the <em>t-SNE</em>⁷ algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YnKixq7dTB5avjsJ9HzQ0Q.png" /><figcaption>Image 5: Visualization of sentiment-based embedding applied on emojis.</figcaption></figure><h3>Final Architecture</h3><p>A number of experiments led us to a recurrent neural network with surprisingly simple architecture. In fact, it was the first baseline architecture we came up with and no following modification of the architecture brought a significant improvement to its performance. Our initial theory was that the task is so simple that the word embedding itself largely solved it, or we just didn’t have enough data to fully exploit the potential of the network. A diagram of the network can be seen in image 6 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GeOo4_Irp_1io11H4KrL2g.png" /><figcaption>Image 6: Scheme of a neural network predicting sentiment for given texts.</figcaption></figure><p>The input layer of the neural network can consume a sequence of up to 50 one-hot encoded tokens⁸ (word vectors) from a set of 50,000 tokens (a dictionary) most frequently appearing in our training data set. We expect most of the processed texts to be very short — they’re social media messages. Longer messages are truncated to the first 50 tokens found in the dictionary.</p><p>The sequence of up to 50-word vectors is sent into the embedding layer. There, the 50,000-dimensional word vectors are embedded into 300-dimensional space. This layer is trained together with the rest of the neural network to help the network to do its job in the best possible way. The example results in image 5 were generated right from this layer once we finished training the network.</p><p>The recurrent layer that consumes the sequence of the 300-dimensional word vectors outputs a single 300-dimensional vector representing the whole input of the network. Here, we decided to use the unidirectional <em>gated recurrent unit</em> (<em>GRU</em>⁹). It’s much faster to train than <em>long short-term memory</em> unit (<em>LSTM</em>¹⁰) or even their bidirectional¹¹ versions. We didn’t see any significant changes in the performance of the network except much longer training times when we were experimenting with them.</p><p>Next, the 300-dimensional representation of the input is processed with a fully connected layer. This is the very basic neural network layer we presented in image 3 and its only job is to derive more complex features from the 300-dimensional representation of the input sequence. We use the <em>ReLU</em> activation function in this and all previous layers. Again, it helps to train the network faster and didn’t inhibit its performance during our experiments.</p><p>Finally, the output layer combines all the 300 features from the previous layer and calculates values for the 3 output neurons. Here, we use the <em>softmax</em> activation function. Its key property is that it considers all neurons in the given layer and normalizes their output values such that their sum is equal to 1.0. Then, the values can be interpreted as probabilities. In other words, the output of the network is a probability of an input text being positive (neuron #1), neutral (neuron #2) and negative (neuron #3). Neuron with the strongest activation is used to assign a sentiment to the analyzed text.</p><h3>Summary</h3><p>We have presented a simple architecture of the recurrent neural network we use for analysis of a sentiment of social media messages. It’s not bad to end up with such a simple model if you need to efficiently analyze hundreds of millions of messages a day. Moreover, it works very well considering the type of texts you’ll encounter.</p><p>We have also briefly introduced some basic concepts from the area of neural networks to make it easier to understand what exactly we have built and to explain some decisions we made.</p><p>But, the largest building block of any successful deep learning model is the data. In the <a href="https://medium.com/socialbakers-engineering/sentiment-analysis-at-socialbakers-c98cf7c908e">next blog post</a>, we will focus on this topic: <a href="https://medium.com/socialbakers-engineering/sentiment-analysis-at-socialbakers-c98cf7c908e">where and how to get the right data</a> and how to prepare it for training our model. That and some implementations details, finally.</p><p>Sounds interesting? Check out more of our <a href="https://medium.com/socialbakers-engineering">stories</a> &amp; don’t forget <a href="https://www.socialbakers.com/careers/?utm_source=medium&amp;utm_medium=medium&amp;utm_campaign=Sentiment%20Analysis%20no.1">we’re hiring</a>! You can also find the next episode <a href="https://medium.com/socialbakers-engineering/sentiment-analysis-at-socialbakers-c98cf7c908e">here</a>.</p><h3>Notes and References</h3><p>[1]: There are activation functions, such as ReLU, that don’t map values into finite range. For more details, see: <a href="https://arxiv.org/pdf/1811.03378.pdf">https://arxiv.org/pdf/1811.03378.pdf</a></p><p>[2]: Neural networks may have more advanced architecture, see examples here: <a href="https://bura.brunel.ac.uk/bitstream/2438/14221/1/FullText.pdf">https://bura.brunel.ac.uk/bitstream/2438/14221/1/FullText.pdf</a></p><p>[3]: Word2vec word embedding<br>Efficient Estimation of Word Representations in Vector Space, 2013<br><a href="https://arxiv.org/pdf/1301.3781.pdf">https://arxiv.org/pdf/1301.3781.pdf</a></p><p>[4]: GloVe word embedding<br>GloVe: Global Vectors for Word Representation, 2014<br><a href="https://nlp.stanford.edu/pubs/glove.pdf">https://nlp.stanford.edu/pubs/glove.pdf</a></p><p>[5]: ELMo word embedding<br>Deep contextualized word representations, 2018<br><a href="https://arxiv.org/pdf/1802.05365.pdf">https://arxiv.org/pdf/1802.05365.pdf</a></p><p>[6]: BERT word embedding<br>BERT: Pre-training of Deep Bidirectional Transformers for Language…, 2019<br><a href="https://arxiv.org/pdf/1810.04805.pdf">https://arxiv.org/pdf/1810.04805.pdf</a></p><p>[7]: The t-SNE is an ML algorithm performing a nonlinear dimensionality reduction, see: <a href="http://www.cs.toronto.edu/~hinton/absps/tsne.pdf">http://www.cs.toronto.edu/~hinton/absps/tsne.pdf</a></p><p>[8]: One-hot encoded vectors are frequently stored in a table and calculations refer to entries in this table using indices instead of using the original vectors. It is one of many optimizations we can see in the implementations of neural networks.</p><p>[9]: GRU recurrent unit<br>Learning Phrase Representations using RNN Encoder–Decoder for St…, 2014<br><a href="https://arxiv.org/pdf/1406.1078.pdf">https://arxiv.org/pdf/1406.1078.pdf</a></p><p>[10]: LSTM recurrent unit<br>Long short-term memory, 1997<br><a href="https://www.bioinf.jku.at/publications/older/2604.pdf">https://www.bioinf.jku.at/publications/older/2604.pdf</a></p><p>[11]: A bidirectional recurrent layer is basically a combination of two unidirectional layers reading an input from the opposing directions. When analyzing an entry of the input, it knows not just what preceded the entry but also what follows it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca10f567eed9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/socialbakers-engineering/sentiment-analysis-at-socialbakers-ca10f567eed9">Sentiment Analysis at Socialbakers</a> was originally published in <a href="https://medium.com/socialbakers-engineering">Emplifi</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>