Elamur Research

Emotion and sentiment analysis of tweets using BERT.

Paper · 2021 · Andrea Chiorrini, Claudia Diamantini, Alex Mircoli et al.

Summary

A tweet can express an unfavorable opinion without making clear whether its author is angry or sad. It can also express fear without evaluating a product, person, or decision. Chiorrini and colleagues investigate these different ways of reading brief social media posts. In their sentiment and emotion experiments, sentiment analysis assigns a tweet a positive, negative, or neutral label. Emotion recognition assigns anger, fear, happiness, or sadness. The authors ask whether a pretrained text encoder can learn to make both kinds of judgment from labeled tweets, which frequently contain informal spellings, abbreviations, and slang.

The authors build a separate classifier for each task using the same design. They clean up the tweets, pass the text through BERT-Base, and add a classification stage with an output for each label. They use fine-tuning to adapt pretrained BERT to the examples for each task. They also test whether preserving capitalization makes a difference. The sentiment experiment uses the manually labeled portion of the collection published by Go and colleagues. The emotion experiment uses the Tweet Emotion Intensity dataset, balances the emotion categories in the training and development pool, and predicts the category associated with each tweet.

Both versions reach accuracy of 0.92 and macro F1 of 0.92 in the sentiment experiment. The paper compares the accuracy with 0.82 reported for a support vector machine in earlier work on the Go collection. In emotion recognition, cased BERT reaches accuracy of 0.90 and macro F1 of 0.91. The uncased version reaches 0.89 on both measures. The cased emotion classifier retrieves a smaller share of the actual happiness examples than of the other emotion classes, even though its happiness predictions have the highest precision.

The validation curves and the mistakes qualify the aggregate scores. For sentiment, validation loss reaches its minimum after the first epoch. For emotion, the best validation behavior is reached after 2 epochs. Continuing to train increases validation loss, which the authors interpret as a sign of overfitting. In sentiment, the authors find that mistakes often send polarized tweets into the neutral category, while direct reversals between positive and negative are uncommon. The experiments show how the classifiers perform on these tweet collections under the paper’s preparation and training choices. The authors leave comparisons with other strong classifiers and tests on larger datasets for further work.

Deep dive: Emotion and sentiment analysis of tweets using BERT.

The paper tests how well fine-tuned BERT classifies sentiment and emotion in tweets, and examines where the classifiers make mistakes. · about 35 minutes to read

The problem and its context

An opinion and an emotion are different targets

The paper starts from the practical value of what people write in public. Posts and reviews can contain reactions that a business might otherwise have to ask customers for directly. The authors mention assessing customer satisfaction, seeing how a marketing campaign affects perceptions of a brand, and finding product problems or requests that could guide improvements. An individual message can give evidence about a particular experience. An automatic classification procedure makes it possible to sort many such messages by the kind of reaction they appear to express.

The meaning of the resulting categories depends on the question being asked. In the paper’s sentiment task, the question concerns polarity, the direction of an opinion. Positive and negative indicate favorable and unfavorable polarity, and neutral is a separate choice. In the emotion task, the categories describe the kind of feeling expressed in the text. Assigning sadness and deciding that an evaluation is negative are different judgments. In particular, the sentiment categories have no place to record the difference between sadness and anger. The emotion categories have no neutral option in the experiment. The authors therefore frame each task as its own instance of text classification.

The paper treats emotion recognition as generally harder because the set of possible feelings is wider and distinctions among them can be subtle. It also notes the lack of universal agreement about which emotions count as primary. The Tweet Emotion Intensity experiment deals with this by adopting the categories that the dataset supplies. The resulting task has a concrete answer for each example, but that answer is defined by the dataset’s labeling scheme. The same applies to the polarity experiment. A label in the dataset gives a basis for checking an automatic decision about a tweet.

Twitter matters in the paper for availability and for language. The authors contrast access to tweets with access to posts from Facebook, where data policies differ. They also identify slang, typing mistakes, and abbreviations as reasons for choosing tweets as a test of classification. An abbreviation such as btw represents a familiar phrase in a compact form. A system that relies on seeing the unabbreviated expression may miss that connection. A username or a link introduces another kind of challenge. It may occupy a substantial part of a brief message while contributing little to the decision the classifier is meant to make. The authors treat Twitter as a source of examples and as a setting where the written forms themselves complicate analysis.

These concerns come together at the point where a system has to generalize from examples. Labels make it possible to measure how frequently a decision agrees with an annotation. The practical difficulty is that labeled collections require effort to create, while a neural classifier trained from scratch can require a large collection. The paper presents adaptation from a pretrained encoder as a way to use information already learned from text and reserve the labeled examples for learning the categories of interest. That is the motivation for beginning with BERT.

Representing the words before classifying the tweet

The authors describe earlier sentiment analysis as including lexicon-based procedures and approaches that learn from examples. A lexicon supplies information associated with particular words. A learned classifier uses patterns acquired from data to decide how to label a new case. The paper describes a shift toward learned methods as researchers pursued better classification and began to use deep neural architectures. This shift makes the representation presented to the classifier an important design choice. The representation determines which properties of a word or its surroundings are readily available to later parts of the system.

A common starting point in the related work is a set of word embeddings. An embedding represents a word by a vector, an ordered collection of real numbers that a classifier can use as input. Word2Vec learns such representations using prediction tasks involving words and their neighbors. In continuous bag-of-words, the surrounding words are given and the middle word is the prediction target. The paper illustrates this with a sentence in which the surroundings make a missing eating-related word predictable. The point of the example is how the training signal is obtained. The words already in the text supply both the input and the missing item to predict. Efficient Estimation of Word Representations in Vector Space

The Skip-gram variant reverses the direction of prediction. It starts with the target word and predicts the words around it. The resulting training procedure also puts information about usage into the numerical representation. A classifier downstream can then work with the representation of a word instead of learning every relevant feature of that word directly from its own labeled examples. Distributed Representations of Words and Phrases and their Compositionality

GloVe is another way of building such vectors. The paper describes it in terms of a corpus-wide record of word co-occurrences. A co-occurrence matrix associates pairs of words with information about how frequently they occur together. GloVe trains on entries for pairs with observed co-occurrences. This provides a different route to a reusable representation from the local prediction tasks just described. It also exemplifies the design the authors contrast with contextual encoding, where a general-purpose word representation serves as the input to a network designed for a particular task. GloVe: Global Vectors for Word Representation

Some of the earlier work that the authors discuss changes the information embeddings are intended to carry. Sentiment-specific embeddings aim to encode polarity alongside information about meaning. This matters because words that are used to talk about similar things can express opposing evaluations. Training a representation with sentiment information gives the learning procedure a reason to preserve a distinction that similarity of usage alone might obscure. The paper also describes work that integrates sentiment supervision at the word and document levels, and another approach that combines embedding learning with matrix factorization. The common concern is how to provide the classifier with a representation suited to the decision it will make. Learning Sentiment-Specific Word Embedding for Twitter Sentiment Classification

Learning from context and from social media signals

In its discussion of emotion recognition, the paper gives examples in which the relevant evidence is distributed through the text. One earlier system uses attention for posts that switch between languages. It uses a long short-term memory network to build a representation of each post and attention to give particular weight to informative words. The example illustrates a distinction between representing the entire post and determining which parts contribute most to the prediction. Another line of work deals with the difficulty of obtaining training labels. EmoNet uses distant supervision, an indirect way of generating labels, to assemble data and trains a recurrent neural system based on gated recurrent units for fine-grained emotion prediction. EmoNet

The authors also discuss earlier work using emoji occurrences to supply a learning signal. Emoji found in social media can be used to teach a system about the contexts in which different expressions tend to appear. The related work uses those occurrences during pretraining to produce representations for tasks including sentiment, emotion, and sarcasm. The use of emoji illustrates how properties of the medium can help with learning even when assembling human labels for every example would be expensive. In the experiments by Chiorrini and colleagues, the labels used for adaptation come from selected tweet datasets, and the initial text encoder comes from BERT pretraining. Using millions of emoji occurrences to learn any-domain representations

The architectural background to BERT is the Transformer and attention. Attention allows a representation at a particular position to draw on information at other positions. In BERT’s bidirectional encoder, that context can include material on both sides. The paper presents pretrained BERT as a departure from the arrangement in which a task-specific network has to build the relevant contextual representation on top of a general word embedding layer. With BERT, the reusable component is already an encoder. The question then becomes how well its representations can be adapted to a dataset’s labels with a small extension to the architecture. Attention Is All You Need

The paper places its sentiment experiment beside earlier applications of BERT to aspect-based sentiment analysis. An aspect-based task connects sentiment to a particular part or property of what is being discussed. Whole-tweet polarity is a different target. A system that assigns a single polarity to a tweet produces a different answer from one that identifies which aspect received which evaluation. The paper cites applications to aspect-based analysis, including work on review reading and on using an auxiliary sentence to specify the target of an analysis. These precedents show the breadth of tasks to which BERT had already been applied in the account given by the authors. BERT Post-Training for Review Reading Comprehension and Aspect-based Sentiment Analysis and Utilizing BERT for Aspect-Based Sentiment Analysis via Constructing Auxiliary Sentence

The authors also distinguish their emotion study from an earlier comparison of pretrained Transformer architectures for emotion recognition. Their interest is how an architecture with BERT-Base behaves on social content. The choice of tweets, the cleaning decisions, and the source of each task’s labels are therefore integral to the question. The work asks about the performance of a concrete classifier under those conditions. The sentiment and emotion tasks share the general strategy of adapting a pretrained encoder, while each gives the strategy a different kind of prediction to learn.

The method, step by step

From a tweet to a set of scores

The method starts with a tweet and a label during training. For sentiment, the label describes the polarity of the tweet. For emotion, it names the emotion associated with the tweet. Preparing the text, encoding it, and translating the encoding into a choice among the relevant labels are separate parts of the procedure. The authors keep the general architecture the same across the tasks and train a classifier for each. At prediction time, a text input goes through the classifier for the desired task, whose output categories determine what kind of answer can be returned.

From a labeled tweet to a classification decision

The steps in order.

From a labeled tweet to a classification decisionStep 1: Select tweets and labels for the task1. Select tweets and labels for the taskStep 2: Clean the tweet text2. Clean the tweet textStep 3: Tokenize with the chosen BERT variant3. Tokenize with the chosen BERT variantStep 4: Encode the input with BERT-Base4. Encode the input with BERT-BaseStep 5: Compute class scores through a fully connected layer5. Compute class scores through a fully connected layerStep 6: Turn scores into probabilities with softmax6. Turn scores into probabilities with softmaxStep 7: Predict a label from the task's categories7. Predict a label from the task's categories

The shared preprocessing description calls out mentions, web addresses, and retweet markers. A mention names a user and begins with @. A web address can point to media or another page. The retweet prefix RT signals that a message is being passed along. The authors treat these features as noise for classification and remove them during preparation. In the sentiment experiment they also report removing hashtags. The classifier is thus evaluated with access to the text left by these choices. It receives whatever clues survive the cleaning procedure, including the remaining wording and its order.

The case choice applies when the cleaned text is prepared for the encoder. With uncased BERT-Base, text is converted to lower-case before tokenization, the procedure that divides an input into the units the encoder processes. The authors also describe the uncased variant as ignoring accents. Their example contrasts the usual capitalization of Michael Jackson with the lower-case form. In the cased comparison, capitalization is preserved. The comparison concerns two pretrained variants and their respective treatment of input text. It does not involve adding capitalization as a separately scored feature to one already trained classifier.

Each classifier also has a sequence-length setting. The authors motivate that setting by looking at distributions of tweet lengths measured in characters. They give a task-specific value for max_seq_length based on what they see in those distributions. The length analysis informs an input decision. It does not by itself tell the programmer which tokenized examples would exceed the setting, because the paper discusses the length histogram in characters and uses the parameter to configure the sequence input. The paper does not spell out that relationship for individual examples.

BERT-Base forms the encoder. An encoder turns the input sequence into a numerical representation used by the layers that follow. The paper lists BERT-Base with 12 encoders and a hidden size of 768. Here the hidden size describes the width of the encoder’s internal representation. The authors characterize BERT-Base as having roughly 110 million trainable parameters. For context on their choice of size, they describe BERT-Large as having more than 340 million. The larger variant is discussed as an option and as future work. The trained and evaluated classifiers in this study use BERT-Base.

To extend the encoder, the authors add a fully connected layer along with a softmax layer. A fully connected layer forms output values using learned combinations of its input values. This lets information from the encoded tweet contribute to the scores for the possible classes. Softmax converts the scores into probabilities distributed over the output categories. A separate set of output units is needed for each task’s label inventory. The paper gives 3 outputs for sentiment and 4 for emotion recognition. Since the classifiers are trained separately, the sentiment outputs and emotion outputs never compete against each other in one softmax.

The main architectural change between the tasks is at the output, but the labels teach each classifier something different throughout fine-tuning. The sentiment examples provide signals about agreement with polarity labels. The emotion examples provide signals about agreement with named categories of feeling. When the paper says the architecture is common, this refers to the organization of the classifier. It does not imply that a completed training run supplies a single set of learned parameters for both tasks. The experiment adapts the pretrained starting point to the data for each task and tests the resulting decisions separately.

Preparing training and evaluation data

The authors describe a shared splitting policy of train (80%), development (10%), and test (10%) using stratified sampling. Training examples supply the labels used to fit the classifier. The development set is used to assess behavior during training, including whether another epoch is helping. The test set is for evaluating the fitted classifier. Stratification uses the classes when making the split, so that a random partition can be organized around the label distribution. The emotion experiment also uses undersampling, a distinct step that reduces the representation of classes with more examples in the fitting pool.

The emotion data come from Emotion Intensities in Tweets. Each tweet is associated with an emotion category and a numerical intensity ranging from 0 to 1. The intensity records the degree of the associated emotion in the dataset. The experiment uses the category as its prediction target. Its output can therefore identify fear as the selected class, for example, while having no separate output for the strength of the fear. A softmax probability for fear is also a different quantity from the recorded intensity. It is the classifier’s score for the label relative to the other available labels.

To balance the emotion examples used for training and development, the authors describe randomly choosing 1300 tweets from each emotion class. They also describe discarding 974 messages they considered unsuitable, including some that were very short or consisted entirely of non-ASCII characters. The resulting training and development pool contains 5200 tweets distributed equally among the classes. The emotion test set contains 581 tweets and has its own class distribution. The authors do not state that the test set was forced to match the equality of the training and development pool. Their setup separates a decision about what the classifier sees while adapting from the composition of the set on which its decisions are assessed.

For sentiment, Go and colleagues’ original collection offers two different labeling sources. A large training portion was labeled by distant supervision using emoticons, while a smaller portion was annotated by people. Chiorrini and colleagues choose the latter because they regard the human labels as more reliable. This choice also changes the role of that data. Go and colleagues called the hand-labeled portion their test set. In Chiorrini and colleagues’ experiment it is the source collection for the sentiment task under the paper’s train, development, and test procedure. The word “test” therefore refers to different things depending on which experiment is being described.

The sentiment choice illustrates a tradeoff in supervision. A large collection labeled by emoticons can be produced without a separate human polarity judgment for every tweet. Using the manually labeled portion gives the classifier direct human judgments at the cost of a much smaller pool for adaptation. The experiment takes that tradeoff as part of its setup. It does not estimate how the classifier would behave if the distant-supervision examples were added or if the same amount of data were collected under a different labeling procedure. The evaluation concerns the chosen data and labels, a specific instance of linguistic annotation.

Choosing the settings and deciding when to stop

Fine-tuning involves settings chosen before a run as well as parameters learned during it. A learning rate governs the scale of updates to the trainable parameters. A batch groups examples for processing together. The sequence-length setting establishes a limit for the input configuration. The authors carry out a preliminary search for settings and, for sentiment, describe using a grid search. A grid search evaluates combinations of chosen settings on a prescribed set of candidate values. The reported method gives the selected setup more clearly than the full set of alternatives that was searched.

For emotion, the reported learning rate is 2e-5. The training and evaluation batch sizes are both 8, the maximum sequence-length setting is 95, and the adam_epsilon parameter is 1e-8. The last is the optimizer’s epsilon setting, a numerical constant used in the update procedure. Training and evaluation batch sizes serve different purposes. During training the grouping determines how examples are processed for learning. During evaluation it determines how examples are grouped for scoring. The paper uses the same reported hyper-parameter configuration for cased and uncased BERT in the emotion comparison.

The authors set the sentiment maximum sequence length to 82 because, in their analysis, the sentiment tweets are shorter on average than the emotion tweets. In the emotion collection they describe a single isolated tweet at the reported upper bound of 452 characters. Setting the input configuration from a length distribution allows the authors to consider typical inputs without building the configuration around that isolated observation. The paper reports the chosen settings. It supplies no accuracy comparison across different sequence lengths, so the resulting values are part of the experimental recipe.

In both tasks the authors examine training durations from 1 to 6 epochs. An epoch is a pass through the training examples. They follow training loss, which reflects the error signal on the data used for fitting, and validation loss, which applies the corresponding assessment to development data. Watching both provides evidence about how the classifier is learning. If training loss decreases while validation loss rises, the extra fitting helps according to the training objective on seen examples while worsening the objective on development examples. The curves are thus used to decide how much training is appropriate, before the final decisions are described in terms of accuracy, precision, recall, and F1.

How the paper scores a classifier

The paper formalizes its evaluation with a confusion matrix, a count of the actual and predicted labels across the examples being scored. Let an entry xᵢⱼ count examples whose true class is j and whose predicted class is i. Under this convention, xᵢᵢ is the count of correct predictions for class i. The paper’s displayed tables put actual classes on rows and predicted classes on columns, so their visual orientation is transposed relative to this index convention. This matters when identifying which totals provide the denominators for precision and recall.

accuracy = (1 / N) · ∑[i = 1 to C] xᵢᵢ

Here accuracy is the share of evaluated examples assigned their true labels. N is the total number of evaluated examples, C is the number of classes, and i indexes those classes. The notation ∑[i = 1 to C] means to add the following term for each class in order, and xᵢᵢ counts correct predictions for that class. The multiplication sign · applies the factor in parentheses, and / denotes division. The sum takes in the entire correct diagonal. Each example therefore contributes equally to accuracy, even when the classes have unequal numbers of examples.

precisionᵢ = xᵢᵢ / ∑[j = 1 to C] xᵢⱼ

precisionᵢ is precision for the class indexed by i. Its numerator xᵢᵢ is the count correctly assigned to class i. Its denominator adds xᵢⱼ, the number assigned to class i whose actual class is j, over every class j from 1 through C. C is the number of classes, the sum is denoted by ∑, and / divides by that total. The denominator therefore includes every prediction of the class. In interpreting a class such as happiness, precision answers how often a prediction of happiness agrees with the label.

recallᵢ = xᵢᵢ / ∑[j = 1 to C] xⱼᵢ

recallᵢ is recall for the class indexed by i. xᵢᵢ again counts the correct decisions for that class. Now xⱼᵢ counts examples whose actual class is i and whose predicted class is j. C is the number of classes and ∑[j = 1 to C] adds those entries over all possible predicted classes. The division sign / forms the fraction recovered from the actual class. With happiness as the class of interest, a tweet labeled happiness and predicted as anger reduces happiness recall. The same mistake affects anger precision.

F₁ᵢ = 2 · (precisionᵢ · recallᵢ) / (precisionᵢ + recallᵢ)

F₁ᵢ is F1 for class i, precisionᵢ is precision for that class, and recallᵢ is its recall. The 2 is the factor in the harmonic mean of precision and recall. The · signs indicate multiplication, + adds the terms in the denominator, and / indicates division. The resulting score reflects both the reliability of predictions for the class and the recovery of the examples that belong to it. A classifier can have high precision by making a class prediction selectively. If this leaves many actual instances assigned elsewhere, the resulting low recall also affects F1.

F₁ = (1 / C) · ∑[i = 1 to C] F₁ᵢ

F₁ is the classifier’s reported overall F1. F₁ᵢ is the score just defined for class i, and C is the number of classes. ∑[i = 1 to C] adds the class scores, / forms the reciprocal of the class count in parentheses, and · multiplies by that factor. This is macro F1, an average in which each class has equal weight. Its unit of averaging is the class. Accuracy instead counts correct decisions across individual examples, which gives classes with more examples more influence on the final result.

Experiments and results

The emotion experiment

The Tweet Emotion Intensity dataset starts with 6755 tweets labeled for anger, fear, happiness, or sadness. The authors report 5200 equally distributed examples in the training and development pool and 581 in the emotion test set after their data preparation. The setup gives the classifiers an even supply of the emotion labels in the pool used for adaptation and development. The test-set distribution, reported separately by the authors, supplies the context for interpreting the errors. A difference in the number of errors across classes can reflect both the difficulty of making a decision and the number of opportunities to make it. The class-level rates are therefore useful alongside the counts.

Both versions use the emotion settings described in the method. The authors report that training took about 5’30"/epoch and that predicting an emotion for a test tweet took approximately 0.4 seconds. The experiments ran on a laptop with a 2x2. The hardware includes an Nvidia GeForce 740M graphics card, a 2 GHz CPU, and 8 GB of RAM. These timings describe the reported experiment on that hardware. Training time per epoch concerns a pass through the fitting data, while the prediction timing concerns an individual test tweet. The two measurements answer different questions about the cost of using the classifier.

The aggregate emotion results slightly favor the cased variant. Uncased BERT-Base records test accuracy of 0.89 and macro F1 of 0.89. Cased BERT-Base records test accuracy of 0.90 and macro F1 of 0.91. The comparison is between versions of the same approach on the same task. The study does not report an external emotion baseline for this experiment. The scores therefore establish how the tested variants performed, with the size of the advantage interpreted in light of the data and the single reported evaluation.

BERT-Base variants on Tweet Emotion Intensity test accuracy

The cased classifier has the higher reported accuracy on the emotion test set.

BERT-Base variants on Tweet Emotion Intensity test accuracyUncased BERT-Base: 0.89Uncased BERT-Base0.89Cased BERT-Base (this paper): 0.90Cased BERT-Base (this paper)0.90
The numbers
System or settingaccuracy
Uncased BERT-Base0.89
Cased BERT-Base (this paper)0.90

The confusion matrix for uncased BERT shows how the decisions differ by class. Of tweets labeled as happiness, 131 were assigned happiness, 10 anger, 6 sadness, and 11 fear. That row gives happiness recall of 0.83. For sadness, the uncased classifier has recall of 0.96 and precision of 0.93. Anger has recall of 0.92 and precision of 0.85. These class-level pairs show how a classifier can retrieve labeled cases well while admitting more examples from other classes into its predictions. Anger is recovered more often than happiness in this run, even though happiness predictions have higher precision, at 0.91.

In the cased happiness row, 135 examples receive the happiness label correctly. The remaining happiness examples in that row go to anger, sadness, and fear, with counts of 7, 9, and 7 respectively. Happiness has recall of 0.85 and precision of 0.94 for the cased version. The paper identifies it as the highest-precision class and the lowest-recall class in that run. It identifies sadness as the class with the highest recall and the strongest average metrics. The aggregate gain for the cased variant and the dispersion of errors within particular classes are both part of the result. A reader interested in finding happy tweets would need the class-level rates to understand what the higher aggregate score means for that application.

The authors use the training curves to assess the duration of emotion fine-tuning. Both variants reach the best validation behavior after 2 epochs. From the third epoch onward the paper describes training error declining while validation loss begins to turn upward. This gives the authors reason to favor an early point in the run. The later training epochs demonstrate that the classifier can continue fitting the examples it sees while the validation objective worsens. The curves concern loss on the fitting and development sets. The class-level scores describe decisions on evaluation examples and answer a separate question.

The sentiment experiment

The source collection from Go and colleagues contains 1,600,000 tweets in its emoticon-labeled training portion and 430 in its manually annotated test portion. Chiorrini and colleagues work with the manually annotated portion only. In that source portion, 157 tweets are positive, 117 are neutral, and 156 are negative. Those figures describe what Go and colleagues supplied in the portion selected for reuse. The paper’s shared experimental setting describes a further split into training, development, and test data for fitting and assessing BERT.

Neutral is the smallest of the polarity classes in the source pool. The authors regard this imbalance as acceptable for their purpose because they are more interested in the detection of emotion-bearing text. That choice gives a practical context to the decision about balancing. In the emotion experiment the authors intervene to give equal representation to the named emotions in the fitting pool. In the sentiment experiment the three-way category distribution is retained as described, and the neutral category still forms part of the assessment. Macro F1 gives its class score equal influence with the other class scores regardless of how many examples are labeled neutral.

The sentiment runs use the sequence-length setting of 82. The paper reports approximately 1’15"/epoch on the same laptop and connects the shorter training time with the smaller sentiment dataset. The cased and uncased runs reach their minimum validation loss after the first epoch. The authors suggest that the number of trainable parameters relative to the size of the dataset may explain why the loss begins to worsen so quickly. The short run time and the early validation minimum are distinct observations. One concerns how long a pass through the data takes. The other concerns whether further passes improve predictions according to the development loss.

Both sentiment variants have reported accuracy of 0.92 and macro F1 of 0.92. The paper places these scores alongside the earlier results from Go and colleagues, whose strongest conventional classifier was a support vector machine, or SVM. An SVM learns a decision boundary between categories from the representation it is given. The accuracy cited for that classifier is 0.82. The paper reports this as an accuracy improvement of 0.10 for BERT. The comparison is to the earlier score on the Go collection. It is reported as a historical comparison, and the study does not describe rerunning the SVM with the BERT train and development procedure.

Reported sentiment accuracy on the Go tweet collection

Both BERT-Base variants share the higher reported accuracy in the paper's comparison with the earlier support vector machine.

Reported sentiment accuracy on the Go tweet collectionGo and colleagues' SVM: 0.82Go and colleagues' SVM0.82Cased and uncased BERT-Base (this paper): 0.92Cased and uncased BERT-Base (this paper)0.92
The numbers
System or settingaccuracy
Go and colleagues' SVM0.82
Cased and uncased BERT-Base (this paper)0.92

The sentiment error analysis distinguishes a reversal of polarity from a decision to assign neutral. For uncased BERT, the paper’s matrix lists 11 actual negative tweets predicted neutral and 3 predicted positive. The corresponding entries for actual positive tweets are 10 predicted neutral and 4 predicted negative. In the cased matrix, 12 actual negatives are assigned neutral and 3 positive, while 9 actual positives are assigned neutral and 5 negative. The counts give content to the statement that errors generally involve the neutral category. They also show that agreement in aggregate metrics can coexist with different counts in particular categories.

The paper reports polarity inversions at 1.8% in its discussion of sentiment errors. An inversion assigns a favorable label to a tweet annotated as unfavorable, or an unfavorable label to one annotated as favorable. A neutral assignment to a polarized tweet loses the direction of the opinion. An inversion gives that opinion the opposite direction. The authors regard reversals as especially costly because they misrepresent the user’s opinion in that stronger sense. They suggest weak polarity and slang as possible reasons for the movement of tweets into neutral. The paper illustrates weak polarization by considering the absence of clearly favorable or unfavorable adjectives. This is an interpretation of the pattern of mistakes.

Neutral also illustrates what recall and precision contribute to the account of the errors. In the uncased sentiment matrix, neutral has recall of 0.95 and precision of 0.84. In the cased matrix, the values reported for neutral are 0.96 and 0.84. The classifiers recover a large share of the tweets labeled neutral, and neutral predictions also include tweets labeled with a polarity. A reader using only the reported aggregate accuracy would miss this behavior. A reader using only neutral recall could mistake successful recovery of neutral examples for reliable identification of neutral whenever that label is predicted. Both rates are necessary for the paper’s observation about where polarized mistakes go.

Reading across the two tasks

The sentiment score describes a choice among polarity labels in Go and colleagues’ manually annotated collection. The emotion score describes a choice among named feelings on the Tweet Emotion Intensity data prepared by the authors. The datasets differ in preparation, class definitions, and the amount of data available. The numerical ordering of the results therefore describes what happened in these experiments and cannot serve as a controlled estimate of how much harder one task is in general. Accuracy remains the fraction correctly classified in each case, and its meaning depends on what the paper counts as a correct decision for that experiment.

The two evaluations provide complementary evidence about the common architecture. For sentiment, the authors can place the scores beside a result from prior work on the same source collection and look at the practical distinction between kinds of mistakes. For emotion, they can compare the two BERT variants directly and look at how the behavior differs across several specific feelings. The strongest evidence in both tasks is the pattern of observed decisions and validation losses under the reported setup. The causal contribution of each design choice would require comparisons that hold more of the procedure fixed.

What the ablations show

What case changes in the reported runs

The paper does not present a component-by-component ablation, but it does compare cased and uncased BERT-Base, examine the effect of training duration on validation loss, and analyze errors by class.

The case comparison asks whether the choice between the two available BERT-Base variants matters for these tweet classifications. The architecture and task remain fixed in each comparison. In the emotion experiment, the authors explicitly use the same reported hyper-parameter configuration for the variants. The cased version scores higher on both aggregate emotion metrics. On sentiment, both versions attain the same reported aggregate scores. These observations support different conclusions for the tasks as conducted. In emotion the cased variant is the better of the reported runs on the aggregate measures. In sentiment the two versions are tied at the reported precision of those measures.

A causal account of capitalization itself would require a tighter intervention. The paper compares pretrained variants, each with its own handling of input text. In particular, the uncased variant also ignores accents. The experiment therefore gives the result of choosing one complete variant over the other. It leaves open whether the change in emotion performance came from retaining capitalization, from other aspects of the variants’ preprocessing or pretrained representations, or from run-to-run variation. The paper gives no repeated-run estimates with which to tell those possibilities apart. A favorable result for cased BERT is consequently evidence about a practical configuration choice on this dataset.

The confusion matrices give a more specific view of what can change. In the emotion results, the cased happiness row has more correct happiness decisions and fewer transfers from happiness to anger or fear than the uncased row. It also has more happiness examples assigned to sadness. The higher happiness recall comes with a changed distribution of errors among the other emotions. This illustrates why a change to the input configuration can affect several boundaries between labels at once. The matrix documents the altered decisions. It does not isolate a textual feature that caused an individual correction or mistake.

The sentiment results show a different relationship between totals and errors. The same accuracy and macro F1 are reported for both variants, but the actual negative and positive rows have differing counts for neutral and for reversals. Thus the aggregate tie is a statement about the reported scores and leaves room for changes in which tweets are correctly classified or which labels receive the errors. The paper’s comparison gives no reason to favor the cased version on aggregate sentiment performance. An evaluation that assigned different costs to different errors would make use of information that the aggregate tie leaves unspecified.

What more training does to validation loss

The epoch sweeps vary training duration directly. In the emotion runs, after the early validation minimum the continued decline of training error accompanies a rise in validation loss. In sentiment, the increase begins after the first epoch. These observations support the interpretation that the fitting procedure can adapt too closely to the training examples when it is allowed to continue. The signs in the two curves matter together. Training performance on its own would still favor continuing when the validation behavior had started to worsen.

The curves also show the relevance of the development split. The test metrics give a final account of classification behavior, while development loss can be followed repeatedly during fine-tuning. A rising development loss signals that further changes to the learned parameters are becoming less helpful on examples outside the training set according to the loss being measured. Loss and accuracy need not trace the same pattern. Loss can react to changes in the scores underlying a decision even if the winning label stays the same. The figures therefore justify statements about the training objective and its behavior on held-out development examples. They do not give a series of test accuracies for each epoch.

The authors associate the especially early sentiment minimum with the small data pool relative to BERT-Base’s capacity. The data are compatible with that explanation, and the authors explicitly call for larger-scale follow-up. The comparison between the tasks cannot settle the explanation because dataset size varies alongside the prediction target, the label distribution, and the training settings. A study that deliberately varied the amount of labeled sentiment data under the same evaluation protocol would address the size explanation more directly. Here the supported finding is that the window of favorable validation behavior is short in the reported sentiment run.

What the mistakes reveal about the label choices

The class analyses answer a different question from the cased comparison and the training curves. They show which decisions account for the overall performance. In emotion, high precision alongside the lowest recall for happiness means that predictions of happiness are comparatively dependable while some actual happiness examples escape detection. Sadness has the highest recall in the cased run. These outcomes can matter differently depending on what a reader would do with the predictions. Someone reviewing a set of predicted happy tweets is concerned with precision. Someone trying to recover happy tweets from an annotated collection is concerned with recall.

In sentiment, the concentration of polarized mistakes in neutral provides evidence about the direction of errors. A three-way classifier can err by reacting too little to a polarity signal or by responding in the opposite direction. The observed counts support the authors’ distinction between these patterns. The paper does not track error rates for groups of tweets independently marked for slang or weak polarity, so it leaves the suggested explanations at the level of plausible readings. Likewise, the analysis of neutral errors does not show what would happen if the output categories or the training objective were changed. It identifies a behavior that a later experiment could measure more directly.

The remaining method choices enter the experiments as parts of the chosen pipeline. The paper has no paired comparison of cleaning versus retaining mentions, of emotion balancing versus using the original distribution for fitting, or of BERT-Base versus a different encoder with the rest of the procedure fixed. The same applies to the size and depth of the classification layers. The attention architecture, training data, preparation, and short fine-tuning schedule all contribute to the reported conditions. The analyses provide evidence for case choice and stopping behavior and a description of errors. They leave the contribution of the other components unresolved.

Limitations

Limits the authors identify

The authors identify training data size as a particular concern for sentiment. They choose the human-annotated portion of the source dataset for the reliability they associate with those labels. That gives the sentiment fine-tuning procedure a small pool in relation to the number of trainable parameters. The paper reports the rapid increase in validation loss and proposes a follow-up on larger datasets. A larger evaluation would help determine whether the early validation minimum recurs and how the classifier behaves when the small manually annotated collection is no longer the sole source of supervision.

The paper proposes the Twitter sentiment benchmark SemEval-2017 Task 4 for a future sentiment experiment. This proposal concerns the scope of the evaluation. The reported sentiment metrics were obtained with data selected from Go and colleagues, and the additional benchmark would supply another dataset on which to assess the method. Its appearance in the conclusion records an intended direction rather than a result of the present study.

The authors also propose EmoBank for broader emotion experiments. Its cited title concerns how annotation perspective and representation format affect dimensional emotion analysis. The current emotion experiment uses the named classes from Tweet Emotion Intensity. Adoption of another data source would require making the prediction target and the evaluation conditions explicit. The paper gives no result of such a comparison.

The choice of architecture receives similar treatment in the conclusion. The authors propose investigating the number of fully connected layers and their widths. Those properties determine how much additional processing takes place between the pretrained representation and the scores for the classes. They also propose swapping BERT-Base for BERT-Large or trying traditional embeddings such as Word2Vec or GloVe. These proposals reflect a limitation of attribution in the current study. The experiments evaluate the architecture as a whole. A comparison that varies the encoder or the classification layers would provide more specific evidence about what those choices contribute.

The authors explicitly call for a comparison with other strong classifiers. The sentiment section has a historical SVM comparison, and the emotion section compares versions of BERT-Base. Neither part gives the broad side-by-side evaluation the authors identify as useful. Their conclusion relates the reported performance to BERT’s ability to represent language. The proposed follow-up comparisons would help determine how much of the observed performance is specific to that capacity under matched data and evaluation conditions.

Limits visible in the evaluation setup

The sentiment comparison needs care because of the change in how the manually annotated data are used. In Go and colleagues’ work, the manual labels belong to a test portion, distinct from the distant-supervision training collection. Chiorrini and colleagues say that they use only the manually labeled portion and describe a train, development, and test split. Their article also gives confusion-matrix counts on a scale that would be difficult to reconcile with scoring only the stated 10% of the 430 tweets. For instance, the uncased matrix alone reports 141 actual negative tweets correctly predicted as negative. The two descriptions leave the exact evaluation denominator unclear. The matrix and the splitting statement are both part of the report, and the paper gives insufficient detail to assign an unambiguous relationship between them.

That ambiguity matters both for interpreting the absolute sentiment score and for comparing it with the older SVM. A direct effect estimate for substituting BERT would compare classifiers on identical evaluation instances, with training access to labels specified for both. The paper reports the SVM number from the earlier work and describes a different use of the hand-labeled pool. It supplies no matched rerun establishing common training and test partitions. The reported figures can be read as a comparison of results associated with the same collection, with the original and reused roles of the annotations kept in view. The evaluation protocol as described is insufficient to identify the numerical gap as the effect of changing the classifier alone.

The emotion account is clearer about the final sizes of the two pools than about how the pools were derived. The paper gives the original size, the class-specific sampling amount, the number filtered out, and the training-and-development and test sizes. It also gives the general stratified splitting policy. It does not fully specify the ordering of filtering, undersampling, and assignment to splits. Order would matter to someone trying to reproduce the experiment, because applying a random selection within the training pool has different implications from selecting examples before defining what is held out. The sampling procedure can be understood in broad terms, while a reconstruction of individual membership would require more information.

Filtering affects the scope of the emotion evaluation. The paper excludes certain very short tweets and tweets composed entirely of non-ASCII characters, among its examples of messages judged unsuitable. The results describe the collection after the authors’ preparation. They give no separate estimate for excluded kinds of tweets. A short message can contain little text, and a character sequence dismissed during cleaning can carry an expressive signal for a human reader. Whether particular exclusions remove largely noise or also remove useful information is an empirical question left open by the experiment. The same consideration applies to removed hashtags in sentiment and to links or mentions in the general preprocessing.

The written account of sequence length also leaves an implementation detail unresolved. The authors measure tweet length in characters and use that analysis to motivate the sequence-length setting for BERT input. They do not specify precisely how measured character lengths map onto the lengths presented to the encoder, or quantify the subsequent treatment of inputs exceeding the configured limit. This limits a reader’s ability to reproduce the handling of longer or unusual tweets. It also leaves open whether the sequence limits are consequential for the reported results. There is no comparison of performance with different limits or an error breakdown by input length.

The class targets restrict what the reported metrics can establish about expressions in the wild. The emotion classifier must select from anger, fear, happiness, and sadness. It has no separate output for intensity, multiple concurrent feelings, or a tweet for which all of the available categories are poor descriptions. The sentiment classifier selects a polarity for the tweet as a whole. It does not record differing opinions expressed about different targets within a tweet. These are implications of the task definitions. The scores measure agreement with the labels the experiments define, rather than a direct measurement of how an author felt or of every opinion the author expressed.

Practical claims also depend on how stable the measurements are. The paper reports point estimates and class-level counts, without repeated-run variation or intervals around scores. For the case comparison, that means the ranking on emotion is the ranking observed in the reported experiment. The paper gives no evidence about how often it would recur across different random samples and training runs. Equal reported sentiment scores likewise establish an observed tie at the displayed precision. And the timing information gives the cost under the authors’ hardware and data sizes. It cannot characterize the behavior on a larger corpus or a different computing configuration.

Finally, the social media motivation describes why people’s posts may be useful for understanding reactions. The experiments operate at the level of agreement with tweet annotations. They do not evaluate whether aggregating the predictions measures customer satisfaction accurately, whether the posts represent the affected population, or whether classification mistakes alter a business decision. Those are downstream questions requiring their own evidence. The paper contributes a set of measured classification results and an analysis of the decisions behind them.

What came after

A later citing work takes up the sentiment side of the problem. SentimentGPT frames its contribution as using GPT for advanced sentiment analysis and examining how that approach departs from prevailing machine learning. This shifts the focus from fitting a BERT-Base classifier with an explicit sentiment output to investigating GPT as the basis for sentiment analysis. The citation connects the work to the earlier use of pretrained language technology for sentiment. It does not establish that SentimentGPT inherited Chiorrini and colleagues’ architecture, used their data splits, or repeated their emotion experiment.

The connection is therefore clearest at the level of the question each work poses. Chiorrini and colleagues ask how well a pretrained encoder, adapted with labels and a classification layer, can recover polarity and emotion categories in tweets. SentimentGPT takes up the use of pretrained language technology for polarity through a different approach. The citation alone gives no common evaluation conditions under which to compare their results, and it leaves the emotion categories, the effect of casing, and the short validation window as findings specific to Chiorrini and colleagues’ experiments.

Cite

Cite as Andrea Chiorrini, Claudia Diamantini, Alex Mircoli and Domenico Potena. 2021. Emotion and sentiment analysis of tweets using BERT. Università Politecnica delle Marche (Università Politecnica delle Marche).

The paper itself, not this page. BibTeX from the library's record of the work.

@inproceedings{chiorrini2021emotion,
  title = {{Emotion and sentiment analysis of tweets using BERT.}},
  author = {Andrea Chiorrini, Claudia Diamantini, Alex Mircoli and Domenico Potena},
  booktitle = {Università Politecnica delle Marche (Università Politecnica delle Marche)},
  year = {2021},
  url = {http://hdl.handle.net/11566/289290}
}

↑ back to top

This page in Markdown https://md.research.elamur.ai/free/en/papers/chiorrini-2021-emotion-sentiment-analysis-tweets-bert/