scieee AI-readable full text Open interactive document viewer

Emotional state detection through text analysis

Martins, Ricardo Alexandre Gonçalves Carotta

Abstract

Atualmente, as pessoas são submetidas a rotinas intensas e muitas vezes exaustivas para que possam acomodar todas as expectativas e realizar seus desejos, sejam pessoais ou profissionais. Trabalhadores que exercem suas profissões diurnas e durante a noite tornam-se estudantes universitários, mães que têm que acomodar sua jornada profissional com as tarefas domésticas e jovens que dividem seu tempo em vários estudos escolares e profissionais - muitas vezes tendo que ajudar nos os lares - são alguns exemplos de perfis de pessoas que correm o risco de ter um problema emocional. Apesar de atingir um grande número de pessoas, não é trivial saber quando alguém está a atingir seu limite, pois é impossível conectar fios e dispositivos que coletem dados por alguns dias para identificar problemas futuros. Além disso, o acesso a esse tipo de equipamento exige dinheiro e tempo, o que não é para todos. A abordagem proposta aqui é coletar dados para inferir o estado emocional atual, tais como (stress, fadiga, ansiedade, etc.) de forma não invasiva, transparente, barata, simples de usar e de fácil integração com outras sistemas, através da análise de textos curtos, como a troca de mensagens, redigidos através dos mecanismos de comunicação rápida hoje em voga (chats de e-mails e redes sociais, blogs, fóruns de discussão, SMS, etc.). Para isso, a ideia é ensinar o computador a identificar as pistas deixadas nas mensagens de texto que revelem o estado emocional do autor. Usando técnicas de aprendizado de máquina (machine learning) e mineração de texto, várias mensagens previamente coletadas de diferentes fontes serão analisadas a fim de criar um modelo que classifique o estado emocional. Posteriormente, usando esse modelo de classificação, novas mensagens de texto podem ser analisadas para inferir o estado emocional atual do autor. Após utilizar diferentes técnicas para extrair as emoções de textos, essas informações foram sintetizadas na criação um perfil emocional que foi utilizado em tarefas de classificação para identificar doenças como depressão, e prever comportamentos tanto individuais como coletivos, atingindo 98% de precisão na detecção de depressão.

Full text

Universidade do Minho Escola de Engenharia Ricardo Alexandre Gonçalves Carotta Martins February 2022 Ricardo Martins UMinho|2022 Emotional state detection through text analysis Emotional state detection through text analysis February 2022 Doctoral Program in Informatics Universidade do Minho Escola de Engenharia Ricardo Alexandre Gonçalves Carotta Martins Work developed under the supervision of Paulo Novais Pedro Henriques Doctoral Thesis Universidade do Minho Escola de Engenharia Emotional state detection through text analysis COPYRIGHT AND TERMS OF USE OF THIS WORK BY A THIRD PARTY This is academic work that can be used by third parties as long as internationally accepted rules and good practices regarding copyright and related rights are respected. Accordingly, this work may be used under the license provided below. If the user needs permission to make use of the work under conditions not provided for in the indicated licensing, they should contact the author through the RepositoriUM of Universidade do Minho. License granted to the users of this work Creative Commons Atribuição-NãoComercial-CompartilhaIgual 4.0 Internacional CC BY-NC-SA 4.0 https://creativecommons.org/licenses/by-nc-sa/4.0/deed.pt ii Acknowledgements First of all, I would like to thank the professors Pedro Henriques, Paulo Novais and José João Almeida for all support, discussions and good times during this work. Also, I would like to thank the ISLab members, for all lunches, soccer, and good ideas that enriched this work. For my familiy: Luciana - love of my life, Manuela - my little princess, thank you to embrace one more time another crazy idea of mine. Without you it couldn’t be possible ! For my parents and brother, thank you for all positive words and support during difficult times. At last, thank you for all friends - I will not cite individually here because I would be unfair if forget someone - whoo cheered for this work. In many times you gave me inspiration to keep in the right path. iii STATEMENT OF INTEGRITY I hereby declare having conducted this academic work with integrity. I confirm that I have not used plagiarism or any form of undue use of information or falsification of results along the process leading to its elaboration. I further declare that I have fully acknowledged the Code of Ethical Conduct of the Universidade do Minho. Braga (Place) (Ricardo Alexandre Gonçalves Carotta Martins) iv Assinado por: RICARDO ALEXANDRE GONÇALVES CAROTTA MARTINS Num. de Identificação: BI32248997 Data: 2022.03.08 09.31.34 GMT Standard Time Signature Not Verified “Só levo a certeza de que muito pouco sei.” (Almir Sater) v Resumo Detecção do estado emocional através de análise de textos Atualmente, as pessoas são submetidas a rotinas intensas e muitas vezes exaustivas para que possam acomodar todas as expectativas e realizar seus desejos, sejam pessoais ou profissionais. Trabalhadores que exercem suas profissões diurnas e durante a noite tornam-se estudantes universitários, mães que têm que acomodar sua jornada profissional com as tarefas domésticas e jovens que dividem seu tempo em vários estudos escolares e profissionais - muitas vezes tendo que ajudar nos os lares - são alguns exemplos de perfis de pessoas que correm o risco de ter um problema emocional. Apesar de atingir um grande número de pessoas, não é trivial saber quando alguém está a atingir seu limite, pois é impossível conectar fios e dispositivos que coletem dados por alguns dias para identificar problemas futuros. Além disso, o acesso a esse tipo de equipamento exige dinheiro e tempo, o que não é para todos. A abordagem proposta aqui é coletar dados para inferir o estado emocional atual, tais como ( stress , fadiga, ansiedade, etc.) de forma não invasiva, transparente, barata, simples de usar e de fácil integração com outras sistemas, através da análise de textos curtos, como a troca de mensagens, redigidos através dos mecanismos de comunicação rápida hoje em voga (chats de e-mails e redes sociais, blogs, fóruns de discussão, SMS, etc.). Para isso, a ideia é ensinar o computador a identificar as pistas deixadas nas mensagens de texto que revelem o estado emocional do autor. Usando técnicas de aprendizado de máquina ( machine learning ) e mineração de texto, várias mensagens previamente coletadas de diferentes fontes serão analisadas a fim de criar um modelo que classifique o estado emocional. Posteriormente, usando esse modelo de classificação, novas mensagens de texto podem ser analisadas para inferir o estado emocional atual do autor. Após utilizar diferentes técnicas para extrair as emoções de textos, essas informações foram sintetizadas na criação um perfil emocional que foi utilizado em tarefas de classificação para identificar doenças como depressão, e prever comportamentos tanto individuais como coletivos, atingindo 98% de precisão na detecção de depressão. Palavras-chave: Análise de Sentimentos, Aprendizado de Máquina, Processamento de Linguagem Natural vi Abstract Emotional state detection through text analysis Daily a large number of people end up suffering car accidents, heart attacks and emotional problems due to stress. Some reasons like sedentary lifestyle and the poor quality of life experienced currently are easily associated with them in the literature. Despite reaching a high number of people, it is non-trivial to figure out when someone is in his emotional threshold; especially when connecting body sensors, there is no alternative to collect data. Furthermore, monitoring emotional state conditions continually requires money and time. Our approach to collect human data is the analysis of text messages gathered from email or social networks chats, blogs, SMS’s, and other fast communication mechanisms popular at present. This approach here proposed and discussed is useful to measure up the current emotional state (stress, fatigue, etc.) of a person in a non-invasive manner, transparent, cheap, simple to use, and easy to carry around through mobile devices usage. To achieve this objective, the idea is to teach the computer to identify cues left in text messages which reveal the emotional state of the author. By using machine learning and text mining, several messages previously collected from different sources are analysed to create a model which classifies the emotional state. Later, using this classification model, new text messages can be analysed to classify the current emotional state. After performed different techniques to extract emotions from texts, these information were used to create an emotional profile that was used in classification tasks to identify diseases such as depression, or predict individual or group behaviours, achieving 98% precision in depression detection. Keywords: Machine Learning, Natural Language Processing, Sentiment Analysis vii LIST OF FIGURES 23 Right-Angled Triangle ................................. 55 24 WMD Example. Adapted from [94] ........................... 56 25 Similarity values. Adapted from [94] .......................... 56 26 Model’s architecture .................................. 61 27 Learning Module ................................... 61 28 RequestClassification pipeline ............................. 64 29 RequestRegression pipeline .............................. 66 30 PredictEmotionalLevels pipeline ............................ 68 31 Data Preparation pipeline ............................... 71 32 Emotional Profile pipeline ............................... 73 33 Emotional Profile pipeline example ........................... 73 34 Personal lexicon creation pipeline ........................... 74 35 Time Series Personal Model Builder pipeline ...................... 76 36 Classification Model module pipeline ......................... 77 37 Preprocessing tasks .................................. 82 38 Preprocessing text example .............................. 83 39 Polarities distribution by category ........................... 83 40 Polarities distribution by author ............................ 84 41 Lexicon expansion process .............................. 89 42 Lexicon polarities ................................... 91 43 Proportions ...................................... 91 44 Dataset creation process ............................... 96 45 Preprocessing pipeline ................................ 98 46 Preprocessing tasks .................................. 105 47 Correlations by author ................................. 108 48 Dataset’s creation pipeline .............................. 113 49 Lexicon expansion process .............................. 114 50 Preprocessing tasks .................................. 115 51 Plutchik’s wheel of emotions ............................. 122 52 Preprocessing tasks .................................. 124 53 Dataset created .................................... 125 54 Outliers identification ................................. 126 55 Clusters of information ................................ 127 xiv List of Tables 1 Example of synsets .................................. 18 2 ANEW values example ................................. 20 3 EmoLex lexicon .................................... 21 4 Dictionary Lookup example .............................. 47 5 Co-occurrence matrix ................................. 48 6 Levels of relationship ................................. 56 7 EmoLex lexicon snapshot ............................... 74 8 Training dataset example ............................... 76 9 Posts authors ..................................... 81 10 Polarities by author .................................. 84 11 Basic emotions average per author .......................... 85 12 Correlation between polarities and emotions ...................... 85 13 Detailed accuracy results for non-preprocessed and preprocessed texts ......... 86 14 Lexicon comparison .................................. 90 15 Bill Gates’ speech analysis .............................. 92 16 Donald Trump speech analysis ............................ 92 17 Correlations between AmountErrors and emotions ................... 99 18 Algorithms correlations and their Root Mean Squared Error(RMSE) ........... 100 19 Ranges of AmountErrors per emotions ......................... 101 20 Tweets authors .................................... 104 21 Polarities analysis from authors and their top 5 audience ................ 106 22 Basic emotions per author .............................. 107 23 Basic emotion’s frequency average of audience’s author ................ 107 xv LIST OF TABLES 24 Correlation between basic emotion’s authors and frequency average basic emotion’s top audiences ...................................... 107 25 Correlation between basic emotion’s authors ...................... 108 26 Grammatical style for authors and audiences ..................... 109 27 Correlation of grammatical frequency average between authors and audience . . . . . . 109 28 Similarities between authors and audiences ...................... 110 29 Characteristics of the personal lexicon created ..................... 115 30 Algorithms evaluation ................................. 118 31 Emotions in second round’s day ............................ 118 32 Correlations between depressive status and basic emotions .............. 125 33 Correlation between depressive status and intensities ................. 126 34 Benchmark of Machine and Deep Learning algorithms ................. 128 xvi 1 Introduction Every day, a vast number of people take photos, make videos and send texts using their mobile equipment (smartphones, tablets, etc.). Businesses around the world collect data on consumer preferences, purchases and trends. Supported by appropriate regulations, governments collect all sorts of data concerning traffic over the internet to incident reports in police departments. This amount of data is growing fast. According to [33], in 2020 for each minute of the day, users share 150000 messages in Facebook, Amazon ships 6659 packages, WhatsApp users share 41666667 messages and users apply for 69444 jobs in LinkedIn. And this only a slice of the daily data production. The same company predicted in 2018 that in 2020 every person on earth will produce 1.7 Mb of data each second [32]. This massive amount of data is generated from several sources (and not restricted to): a single person, social groups or companies. For instance, personal smartwatches can measure and store the heartbeat; smartphones can calculate travelled distances, iPods can estimate the number of calories burned during the running, websites can store the user’s navigation information. Regarding the data generated by a person and among many other sorts, all texts produced in the context of the so-called Computer Mediate Communications—like blogs, comments as replies to Social Network posts or Newspaper articles, chats, tweets , and so on — can contribute as a source of information characterizing the author. All this individual/personal generated data, does not reveal, in a primary analysis, relevant information. However, after an in-depth analysis, it can provide relevant knowledge about the person involved. Using data to infer information about users is not new. Researching on customer buying behaviour over time can reveal some unsuspected patterns – the most famous example is the relation between diapers and beer sold in larger than usual quantities on Friday nights in a retailer. The hypothesis was that husbands had to shop for diapers for the weekend while in their way home from work - and while there, they would pick up beer for the weekend sports on TV. This relationship allowed the store to locate diapers and beers close to each other so that more husbands might be reminded of the one they were most likely to forget. In science areas like psychology and medicine, the textual information produced by a user can also be an essential source to identify patterns. For [62], expressing emotions can be done through writing, body language, or talking with other people. [48] link negative emotions to increased stress. 1 CHAPTER 1. INTRODUCTION The automatic detection of emotions in texts is becoming essential in many different areas such as educational/edutainment games to collect feedback from users, financial to predict stock market prices and healthcare to detect the mood of patients while in treatment. When handling with emotions, there is common thinking that exists a straight connection between emotions, mood and personal profile, and it is a half-truth because mood expresses emotions. However, the mood is different from the emotional profile (or personality) while the emotional profile of a person stays rigid throughout our life, the mood is more open to change, influenced by the current emotions. In addition the emotional state is a snapshot of the mood in a specific moment, being the emotional states’ collection along the time similar to the emotional profile. 1.1 Motivation Emotions are present in most of our everyday occasions and manifestations during our life, such as in decision making and social relations. The research contributions in this area are significant and can provide theoretical and practical advances in human-machine interaction, and a better understanding of the technology influence has on human development [155], allowing the computer to adapt to people and not the opposite. The study of the emotions identification in texts is inserted in a multidisciplinary context, going from Psychology, through the Mining of Texts and Pattern Recognition to Human-Computer Interaction. The research area, known as Opinion Mining, has been experiencing growth, with many researchers working in automatic opinion evaluation on e-commerce and Opinion portals. The PhD work here discussed aims at presenting a method for the identification of the emotional state through the processing of texts written in English. The emotions to be identified in the texts refer to the emotions proposed in the Plutchik’s wheel of emotions [157]. Neutral texts (without emotion) are also identified by the method. For the evaluation of the proposed method, will be constructed a corpus of text messages of people demonstrating different levels of sentiment and a tool that allows the conduction of experiments with different configurations. The motivation for this work is creating software that analyses the content of messages, extracting the emotions contained into these messages to infer the author’s emotional profile and - using this information - classify the emotional state that the author presents at the writing time. This classifier can be used in many different situations (and not limited to these ones): in a psychological treatment scenario, where a patient needs to be assessed constantly; in the scholarly context, identifying cues about bullying based on the student’s emotional profile changing; in the labour context, helping to identify the workers under risk of stress. However, this follow-up implies constant data collection, which can be considered somewhat invasive. In times when the limits of privacy and how a person’s data are treated are discussed, it is necessary that the people whose texts are under analysis are aware and in agreement with this monitoring. 2 1.2. OBJECTIVE AND RESEARCH QUESTIONS 1.2 Objective and Research Questions The objective of the doctoral project here discussed is to resort to techniques like text mining and machine learning to extract and classify emotional information, from unstructured documents, in order to identify the sentiment contained in the text that can be used to characterise the text’s author emotional profile. Thus, the research questions that will guide the execution of the work are: A. Do emotional labels impact on the accuracy of classifications of the emotional states? B. Is there an abstract model which differentiate the emotions considering personal perspectives ? C. Based on the emotional state of a person, would be possible to predict his actions, choices or some situations which inspire concerning ? To guide the answers for these questions, it were formulated these hypothesis: A. The current emotional state of a person is expressed in his texts when writing; B. The set of emotions detected in a large collection of texts of an author during a large interval represent his emotional profile; C. The emotional state can be classified according to variations with the emotional profile. The main contribution of this project will be an emotional state classifier through text analysis, natural language processing and machine learning algorithms. At a formal description level, the proposal is the creation of an emotional state classifier ES: 𝐸𝑆 =𝑓(𝑇)(1.1) where: 𝑇={𝑡𝑥𝑡1, 𝑡𝑥𝑡2, ..., 𝑡𝑥𝑡𝑛}is a set of texts and 𝑇𝑋𝑇 ={𝑤1,𝑤2, ...,𝑤𝑛}is a set of words, where 𝑤can contain emotional information. 1.3 Document Structure This thesis is organized in 4 parts and begins with an introduction to the context, motivation and objectives in Chapter 1. Part Iincludes Chapters 5to 2and presents the State of the art. Part II just includes one chapter intended to present the PhD proposal. Part III includes Chapters 7to 12, aiming at presenting and discussing the case studies to which the proposed emotional classifier was applied. 3 CHAPTER 1. INTRODUCTION Part IV presents a summary presented and some conclusions as well as and some directions for future work are presented. 4 Part I State of the Art 5 This part introduces the state of art of the theories and technologies that were used during the work. First, it is presented abstract concepts and theories from psychology, such as emotions and the different models to represent them, the human personality and the personal vocabulary as source of personality differentiation. Later, the a set of techniques from Natural Language Processing are presented, in order to explain how the information can be retrieved from texts and modelled to represent the abstract concepts presented earlier. 2 Emotions Although emotions have been studied in several areas of knowledge such as Psychology, Neuroscience, Philosophy and Artificial Intelligence, there is no consensus on the definition of emotion because some issues such as its subjective nature, the divergence of researchers as to its origin, and the term used to describe a wide range of cognitive and physiological states [57]. This lack of consensus reinforces the idea of [47] which claimed that “everyone knows what emotion is until asked to give a definition. Then, it seems no one knows.” For [96], the concept of emotion can vary among several definitions, depending on the area of knowledge from which they arise. In the psychological and behavioural area, emotions can be understood as systemic responses that occur when highly motivated actions are delayed or inhibited. Thus, emotions concern the execution of something relevant to the organism. [29] highlighted the fundamental role of emotions in the process of adaptation of living beings. According to the author, a facial expression indicating emotional states is a form of communication that is efficient and understandable to people, regardless of culture, and these striking characteristics are adaptive in all life forms. In cognitive sciences, according to [28], emotions are body movements or actions visible to third parties. On the other hand, the sentiments are hidden in the organism where they occur, invisible to the public. Sentiments can arise by merely thinking about an event, and imagining what would happen if it would occur. The differentiation presented above allows noticing that emotions in cognition have a much more visible, as well as conscious, role in the day-to-day. For example, the mood is widely used in educational settings as a way of motivating attention, developing affective sentiments towards the taught content, and promoting a more enjoyable learning experience [140]. Different scientific theories of emotion have been created over the years of research in cognitive sciences, each trying to explain the diversity of affect phenomena. These theories gave rise to three main models of emotions: discrete models, also called categorical ones; dimensional models; and models based on appraisal theory (cognitive models). 7 CHAPTER 2. EMOTIONS 2.4 Affective Computing The concept of Affective Computing (AC) was introduced by [155], who defined “the computing that relates to, arises from or deliberately influences emotions.” The affective computing focus is on establishing models, based on physiological and behavioural signals collected by sensors and techniques to perceive, recognise and understand human emotions to provide better feedback. Emotion identification is used in the field of cognitive science [144] having a connection to affective computing enabling computers to recognise emotions [155]. According to [69], the arising of AC is related to the needs to put computers interacting directly, thinking, receiving and transmitting people’s personalities. [155] and [69] emphasise AC as a research area which examines how computational systems can identify, classify, and prove human personality as well as group knowledge in other areas, such as psychology and cognitive science. To achieve this objective, AC in computer investigates how computers could model, recognise, and respond to human behaviours, and thus how to express through an interface computational interaction. The purpose of promoting this characterisation is to contribute to increase the consistency, coherence and credibility of the reactions and computational responses provided during human interaction via humancomputer interface [155]. To improve studies, [164] analysed the behaviour of people through computational agents, using the models of psychologists such as [144], [178] and [167], containing emotional characteristics. These characteristics have contributed to the consistency, coherence, and prediction of emotional response in computer responses. For [137], after [155] the research on performing the analysis of emotions computationally increased significantly, even more when a great variety of environments of interaction between humans and computers arose, such as social media, chatbots, among others. [105] defines Sentiment Analysis (SA) which is embedded in the Affective Computing as the area that analyses the opinions, feelings, evaluations, attitudes and emotions of the people expressed in written text. Under the SA concept, it is possible to find also many different names and tasks, such as Opinion Mining, Opinion Analysis, Opinion Extraction, Sentiment Mining, Subjectivity Analysis, Affect Analysis, Emotion Analysis and Review Mining. In industry, the term Sentiment Analysis is most commonly used, and in academic research both Sentiment Analysis and Opinion Mining are often employed. Regardless, they represent, basically, the same field of study. The term Sentiment Analysis appeared for the first time in [138], as the term Opinion Mining was introduced by [30]. 2.5 Detecting Emotions Challenges For the five human senses (sight, smell, touch, taste and hearing), two of them - sight and hearing - are responsible to transmit the emotions among persons. This transmission uses environments such as texts, 14 2.5. DETECTING EMOTIONS CHALLENGES speeches and images, and according to the environment used, different techniques must be applied to detect these emotions. 2.5.1 Detecting Emotions in Texts Lexicon-based and Machine Learning (ML) approaches are commonly used to solve SA problems in texts. Figure 6shows the two main approaches and how they are subdivided. Figure 6: Approaches for Sentiment Analysis in text. Source: author It is usual to find in the literature hybrid works that use both approaches to identify emotions in texts. [59] presents a work which uses lexicon and ML to identify the six basic emotions. [163] use a lexicon to help in the selection of features and ML algorithms to identify the six basic emotions in Spanish texts. The ML-based approach is divided into supervised ML and unsupervised AM. Supervised methods require a large number of labelled texts to perform the training. Unsupervised methods are an option when there is difficulty in obtaining labelled text. The main algorithms based on supervised ML that are most commonly used in the classification of emotions in texts are presented in Section 2.5.1.2. The lexical approach depends on the availability of an emotional terms lexicon. This approach is subdivided into two other approaches: dictionary-based and corpus-based. In the dictionary-based approach, initially, a small set of emotional terms is collected manually where each term has its associated emotion. This set of words, called seeds, is used to search in dictionaries such as WordNet Affect [188] or Senti- WordNet [43] to explore semantic links, synonyms and antonyms and newly discovered terms are added to the seed list. The iterative process ends when no new terms are found [103]. In the corpus-based approach, there is also a list of emotional terms used to find other emotional terms in a large domain corpus. The objective is to aid in emotional terms searches with specific context guidelines. This can be done using statistical or semantic methods [103]. 15 CHAPTER 2. EMOTIONS 2.5.1.1 Lexicon-based approaches For [66], in NLP-context, lexicons are component of a system that contains information (semantic and/or grammatical) about words or expressions, whereas the term dictionary usually refers to objects (printed books or electronic) intended for human readers, but also accessible by computers. For [6] a lexicon is derived from the examination of a corpus, which in turn is defined in the Oxford English dictionary as an “organ, collection of writings.”There is no minimum or maximum size for corpora, or any specification what it should contain. The manual construction of a lexicon is an arduous task due to the large volume of information and the amount of time that is spent to carry out the steps. For this task, there are efforts in the creation of lexicons through computational techniques, for example, as presented by [149]. Another method for the construction of computational lexicons is the analysis and improvement of existing lexicons. The initial point of any approach to study emotion in a text is the use of specific affective lexicons.[23] are one of the first researchers targeting the problem of the referential structure of the affective lexicon. Affective lexicons are subsets of lexicons which are constructed based on different methodologies and provide bases for most machine learning algorithms. In our comprehension, these subsets are responsible for carrying emotional labels for the words. This vision is shared by Mohammad [134], that defines an affective lexicon as “a list of emotions and words that are indicative of each emotion.” [145] argue that affective lexicons do not only contain terms related to emotion but have other terms and affective conditions (affection, mood and sentiment). Terms such as “affection”and “emotion”are used, sometimes as synonyms. The distinction occurs when the term affection refers to anything whose valence value is positive or negative. Affection has a broader category when compared to emotion. Types of affective condition cause emotions, but not all affective conditions are emotions. At the beginning of studies in affective lexicons, [8] analysed the data selected and considered having affective connotations from [4]. The objective was to develop a method, called “semantics”, which would map a universe of words with affective characteristics. However, were not all words included in the analysis that had affectivity, which “justify that any division between affective concepts is necessarily vague and arbitrary”[8]. There is no pre-defined model for the construction of an affective lexicon. Most of the works have created defined steps and goals from studies to achieve the goal. Other works take lexicons already developed and implemented and make improvements and extensions. The following is a description of some more important lexicons and affective lexicons available: WordNet WordNet1is an extensive English-language lexical database developed by George A. Miller, combining lexicographical information (lexical and semantic relations used to represent the lexical knowledge organisation) and computational resources [51]. [131] defines the vocabulary of a language with a set W with pairs ( f , s ), where a form f is a character string over a finite alphabet and s is a sense from a 1http://wordnet.princeton.edu 16 2.5. DETECTING EMOTIONS CHALLENGES set of meanings. Each form with a sense in a language is called a word in that language. In WordNet, a sense is represented by a set of one or more synonyms. The base has more than 118,000 different words and more than 90,000 words [131]. WordNet is composed of nouns, verbs, adjectives and adverbs grouped into sets of synonyms (synsets), each expressing a distinct concept. These are organised into a set of lexicographers by syntactic category and by other organisational criteria. Adverbs are kept in only one file, while nouns and verbs are grouped according to semantics. Adjectives are divided into descriptive and relational adjectives [130]. Figure 7: WordNet online search Figure 7illustrates the result of an online WordNet query for the word expensive . In the figure, it is possible to visualise the lexical relationship for the word expensive. In similar to , there is the term overpriced , which has the same synset and antonym corresponds to the opposite of the searched word. The word expensive , in the example, has only one sense in WordNet. WordNet Affect WordNet-Affect [188] is an extension of the WordNet database [129], which includes a subset of synsets suitable to represent affective concepts. In particular, it allows WordNet synset to be assigned with one or more affective labels (a-labels). There are also a-labels for concepts representing moods, situations eliciting emotions, or emotional responses. Table 1show some example of synsets. It was extended with a set of additional a-labels (called emotional categories), hierarchically organised to specialise synsets with a-label emotion according to emotional valence: positive, negative, ambiguous, and neutral. The positive valence corresponds to positive emotions, defined as emotional states characterised by the presence of positive hedonic signals. It includes synsets such as joy#1 or enthusiasm#1. Similarly, the negative a-label identifies negative emotions characterised by negative hedonic signals, for example, anger#1 or sadness#1. Synsets representing affective states whose valence depends on semantic context (e.g. surprise#1) were marked with the tag ambiguous. Finally, synsets referring to mental states that are considered affective but are not characterised by valence were marked with the tag neutral. Another valuable property for affective lexicon is the stative/causative dimension. An emotional adjective is considered causative if it refers to some emotion that is caused by the entity represented by the 17 CHAPTER 2. EMOTIONS Table 1: Example of synsets A-label Example of synsets EMOTION noun ’anger’, verb ’fear’ MOOD noun ’animosity’, adjective ’fear’ TRAIT noun ’aggressiveness’, adjective ’competitive’ COGNITIVE state noun ’confusion’, adjective ’dazed’ PHYSICAL state noun ’illness’ HEDONIC signal noun ’hurt’, noun ’suffering’ Emotion-eliciting SITUATION noun ’awkwardness’ Emotional RESPONSE noun ’cold sweat’, verb ’tremble’ BEHAVIOUR noun ’offence’, adjective ’inhibited’ ATTITUDE noun ’intolerance’, noun ’defensive’ SENSATION noun ’coldness’, noun ’feel’ modified noun (e.g. annoying movie). In the same way, an emotional adjective is said stative if it refers to the emotion owned or felt by the subject denoted by the modified noun (e.g. cheerful/happy boy). SentiWordNet SentiWordNet (SWN) is another lexicon, developed by [43] explicitly for collaborate on applications for Data Mining and Opinion Classification. This lexical resource is the result of automated notations in all synsets of WordNet 3.0, with a degree of positivity, negativity and neutrality. Each synset is associated with three numeric values, Pos(s), Neg(s) and Obj(s) that indicate how positive, negative, or objective (neutral) the term contained in the synset is. Each of the three values varies in the range [0.0, 1.0] and their sum is 1.0 for each synset, so Obj (s) + Pos (s) + Neg (s) = 1. Figure 8illustrates the graphical representation adopted by SWN Representing properties related to synset. The edges of the triangle represent one of three classifications (positive, negative and objective) and a pointer (Synset position) points to the highest value classification. Figure 8: SentiWordNet Synset’s properties. Adapted from https://ontotext.fbk.eu/sentiwn. html The method used to develop SWN is derived from the work of [44,45], based on the quantitative 18 2.5. DETECTING EMOTIONS CHALLENGES analysis of terms associated to synsets and on the use of vector representation of resulting terms for semisupervised classification of synsets. The scoring trio in the SWN is derived from the results combination produced by a committee of eight ternary classifiers, with similar levels of precision, but with different classification composition. Each subject classifier differs from the training set and the learning adopted for this set, thus producing distinct classifications resulting from each WordNet synset. The SWN score is given by the ratio of classifiers assigned the corresponding label to the synset. If all ternary classifiers result in assigning the same label to a synset, the labelling will have the highest score for the synset but will have a score proportional to the number of classifiers that assigned it [9,43]. The SWN data lexicon is also available as a data file (.txt). The Figure 9show some examples of the records in SentiWordNet 3.0: Figure 9: SentiWordNet records The POS-ID identifies the synset, PosScore and NegScore values correspond to positivity and negativity pointed out by SWN for the defined synset. The value of objectivity is given by: Obj(s) = 1 - (Pos(s) + Neg(s)). The SynseTerms column corresponds to the spaced terms in the synset, with the grammar class and number corresponding to the sense. The Gloss column describes the meaning of the term. SentiStrength SentiStrength is a lexicon created by [192] aimed to identify sentiment in short texts, containing 2310 sentiment words and word stems obtained from the LIWC, the General Inquirer list of sentiment terms [186] and some ad-hoc additions. It uses a Kleene Star implementation to identify the lexicon with a wildcard at the end of a word. For instance, “amaz*”matches all words starting with “amaz”, such as amazed and amazing. For each token or stem in a text, SentiStrength returns a positive and negative score, ranging from 1 to 5 and -1 to -5 respectively. Matching this, each token or stem in the dictionary receives a positive or negative score within one of these two ranges. Using the tool, the sentence “I really like you but dislike your cold sister ”has as results: I really love [3] [+1 booster word] you but dislike [-3] your cold [-2] sister 19 CHAPTER 2. EMOTIONS So, the final results score 4 - strong positive sentiment, and score -5 - strong negative sentiment. All words in lexicon have theirs scores previously classified, analysed and evaluated, and the final score sentence is a sum of the individual words’ scores for each polarity. The words that appear in the text, and are not contained in the lexicon, are not analysed and consequently do not interfere with the final classification. For a lexicon sentiment weight scores fine-tune, SentiStrength uses a machine learning approach implementing a specific and proprietary algorithm. The reason for this kind of input for the sentiment weights is that the low frequency of many terms in texts would contribute to a wrong machine learning weights assignment. ANEW American Norms for English Words , or ANEW [14], is a set of 1034 words which measures three emotional dimensions: valence, alertness and dominance. The valence consists in how pleasant or unpleasant a stimulus is perceived. The second dimension, alertness, consists of how stimulated or relaxed a stimulus makes us. The third dimension, dominance, consists in how much in control of a stimulus or dominated by it is perceived. The value for each word in each dimension was obtained from ratings made on a scale of 1 to 9, made by undergraduate students, where a rating of 1 denoted highly negative and 9 denoted highly positive. Table 2demonstrates an example of how the ANEW values are stored. Table 2: ANEW values example Description Valence Mean (SD) Arousal Mean (SD) Dominance Mean (SD) abduction 2.33 (2.13) 6.09 (2.72) 2.76 (2.49) abortion 3.15 (2.39) 5.85 (3.09) 4.00 (2.55) absurd 4.70 (1.30) 4.65 (1.93) 4.70 (1.42) abundance 6.55 (1.90) 5.10 (2.53) 5.55 (2.11) abuse 1.46 (1.03) 6.88 (2.83) 3.81 (3.12) acceptance 8.18 (1.56) 4.86 (3.00) 6.55 (1.99) accident 2.08 (1.29) 6.48 (2.62) 3.92 (2.29) ace 6.14 (2.10) 4.95 (2.33) 6.33 (2.08) EmoLex The EmoLex Word-Emotion Association Lexicon (EmoLex) is a lexicon created by [134] composed of a list of more than 14000 English words and their associations with eight basic emotions (anger, fear, anticipation, trust, surprise, sadness, joy, and disgust) and two sentiments (negative and positive). The annotations were collected using a crowdsourcing Mechanic Turk, and different than the other lexicons, EmoLex shows association scores for the emotions and sentiments as 0 (not associated) and 1 (associated). An example as EmoLex is composed is presented in Table 3. 20 2.5. DETECTING EMOTIONS CHALLENGES Table 3: EmoLex lexicon Word Positive Negative Anger Anticipation Disgust Fear Joy Sadness Surprise Trust aback 0 0 0 0 0 0 0 0 0 0 abacus 0 0 0 0 0 0 0 0 0 1 abandon 0 1 0 0 0 1 0 1 0 0 abandoned 0 1 1 0 0 1 0 1 0 0 abandonment 0 1 1 0 0 1 0 1 1 0 abate 0 0 0 0 0 0 0 0 0 0 abatement 0 0 0 0 0 0 0 0 0 0 abba 1 0 0 0 0 0 0 0 0 0 abbot 0 0 0 0 0 0 0 0 0 1 2.5.1.2 Machine Learning algorithms for sentiment extraction In Machine Learning literature, there are several algorithms developed to deal for different situations, each one having their pros and cons. Below are presented the most used algorithms to handle with sentiment analysis: Naive Bayes The Naive Bayes classifier is widely used in classifying texts because of its computational efficiency and good predictive performance. The Naive Bayes classifier has the “naive”because it assumes that the probabilities are combined independently of each other, that is, the probability that a term in the document is in a specific category is not related to the likelihood of other terms being in this category [181]. Bayesian classifiers use Bayes’ Theorem to classify data. If X is the set of characteristics and Y is the class variable, it is possible to determine their relationship using probabilistically: 𝑃(𝑌|𝑋)=𝑃(𝑋|𝑌).𝑃 (𝑌) 𝑃(𝑋) According to [151], to perform text classification is needed to assign a class c to a document d. 𝑃(𝑐|𝑑)=𝑃(𝑑|𝑐).𝑃 (𝑐) 𝑃(𝑑) Since P(d) does not disturb in the selection of c and to calculate P(d | c) , is considered that the probabilities of each characteristic are independent of the class. Although the hypothesis of independence is necessary for the algorithm formulation, Naive Bayes works appropriately in several applications which such hypothesis cannot be verified, having success in part of the consequence of the versatility. As the hypothesis of independence loses power in a given model, the adjustment of the assumed distribution worsens. However, if both estimated and real distributions agree on the most likely class, the classifier will still perform well [165]. 21 CHAPTER 2. EMOTIONS Support Vector Machines The classification task involves a set of training data. Each instance of the training set contains a “target value”that refers to the class or label. The objective of the Support Vector Machines (SVM) is to produce a model, based on the training data, which predicts the target values (class) of the new data [74]. The main idea of SVM-based classifiers is to construct an optimal hyperplane so that it can separate different classes of data with as much margin as possible. The SVM hyperplanes are determined by a relatively small subset of training examples, which are called support vectors. Figure 10 illustrates an optimal hyperplane for a set of linearly separable data. Figure 10: Support Vector and Margin identification. Adapted from https://medium.com/ mlearning-ai/support-vector-machine-svm-algorithm-a5acaa48fe3a Another relevant feature of SVM is the ability to classify data sets with complex scopes, as in Figure 11. For this, mapping the problem to a different space allows a hyperplane to perform class separation (Figure 12). To the transformation be simplified and computationally less costly, the “kernel trick”[73] is performed, with the user having to choose some transformation kernel functions. Figure 11: Non-linearly separable data. Source: author The SVM classifier presents an intrinsic limitation: the binary segmentation. It is not possible, through the usual methodology, to classify more than two types of elements into a heterogeneous set. To solve this problem, the solution is successive cascade classifications. 22 2.5. DETECTING EMOTIONS CHALLENGES Figure 12: Non-linearly separable data. Source: author In this approach, known as “SVM multiclass”, the elements to be classified can be, at each iteration of the SVM, removed one by one from the original group, as shown in Figure 13. In this one-on-one confrontation process, the SVM lists a suitable match for each iteration, yielding the final one, a result that is qualitatively similar to other multiclass classifiers. Figure 13: SVM Multiclass classification process. Source: author Maximum Entropy Model A maximum entropy model classifier is a probabilistic model that favours classes distribution more uniform which adhere to a specific set of constraints determined by training data. [27] introduce an example in text categorization domain. Given a document 𝑑containing three classes 𝑐1, 𝑐2,𝑐3, if no information is known about the document from the training data, it is possible to claim that the probability of classifying 𝑑in each of the classes is equal, that is, 1/3. However if it has “learned”from the training data that 2/3 of the documents containing the word “sports”belong to class 𝑐1and the document 𝑑contains the word “sports”, it is possible to claim that the document 𝑑classification probability for class 𝑐1is 2/3 and the for classes 𝑐2and 𝑐3is equal to 1/3 each. The sample data provide such characteristics and they will be used to determine the constraints. 23 CHAPTER 3. HUMAN BEHAVIOUR trait identified in the set of all user’s reviews. For the recommendation, the average of each personality trait of all games’ reviews was calculated for each game. Finally, the best game recommendations were ranked by a cosine distance from the user’s personality traits. Other approach using NLP to identify personality was presented by [174], where texts were gathered from Facebook posts in Brazilian Portuguese and the texts author’s personality was identified based on Big Five’s traits. Using preprocessing steps, the texts were represented in vectors, containing the frequency of the words in each Big Five’s trait, according to LIWC. These vectors fed a MultiLayerPerceptron classifier to evaluate the results, and these results are compared to a previous performed analysis, in order to evaluate the algorithm. 3.2 Personal lexicon It is known that for all languages there is a vast set of words - the lexicon - which people can explore and enrich dialogue in a variety of ways. However, when people talk, they use a “personal lexicon”, which is exactly the words that within their language, are chosen by the person who is expressing themselves. Within the vocabulary, there are synonyms, which are different words, but which have the same meaning. In some cases, there are dozens of different words, but with the same meaning. The main question is that for some reason, some people prefer to use some words or others, and what drives these people to make that choice decision? Which leads them to choose the word “interesting” instead of “cool”, for example. Why when someone who is going to travel to a small city prefers to say that it is “quiet” or “comfortable” even “divine place”. It depends on each person and that in some cases, some words remind us of someone, due to the number of times that person uses that word. It is interesting to note how different personal vocabulary is related to people, as there are preferences in choosing words in dialogue. In a conversation, each word is important, so that all the words spoken are not in vain, have great value. They are pronounced precisely because they are the best, the most pleasant or the best way for a person to express themselves. This is like a fingerprint, where the frequency of using those words says a lot about the personality of the user. This personal lexicon is important because it helps to differentiate individuals according to the frequency of use of words. However, this is not the only information that can be extracted from a personal lexicon. In general, through the use of words, it is possible to identify a person’s origin, gender or even where a conversation occurred. In Portuguese, the word “ obrigada ” (thanks) is used only the author is female. If the author is male, the word must be “ obrigado ” (thanks). Moreover, according to the context (country, place, company, etc) where a conversation occurs, it is possible to identify differences in the interpretation of the words used, that is valid only in this context, as presented by [120]. This is the regionalism. Several examples exhibit this situation: the word “ fato ” in Brazilian Portuguese refers to the word “fact” while in Portuguese spoken in Portugal, “ fato ” means “coat”. The Spanish word “ tinto ” in Colombia is 30 3.3. SUMMARY about “coffee” where in Spain, the word is regarding to “red wine”. Due to these differences, in text interpretation in NLP, it is not secure (and certainly impossible) to have an universal lexicon to consult all words, leading to the risk of misunderstanding. To overcome this issue, a useful approach is perform a lexicon expansion. 3.3 Summary In this chapter we presented the concepts of personality and personal lexicon. According to the personality of the person, his vocabulary can vary when comparing to the vocabulary of other person. A calm person certainly use calm word more frequently when compared to an anxious person. For this reason it is important not to generalize the vocabulary for all person, i.e. having a personal vocabulary for each person, representing their basic personality’s bricks. In this work will be used a personal (expanded) representation of an emotional lexicon, in order to individualize the emotions applied into the sentences. 31 4 Text Mining and NLP Text mining, also referred as text data mining or knowledge discovery [46], is an area of computer science research which refers to the process of extracting relevant information from unstructured text documents using techniques from data mining, natural language processing, machine learning, knowledge management and information retrieval. It can be defined as a process to seek and extract useful information from unstructured data sources such as e-mails, HTML files, etc. through the identification and exploration of interesting patterns [50]. Figure 14 gives the overview of text mining process. Figure 14: Text Mining overview. Source: author These data sources are document collections, and the frequently interesting information patterns are found in the unstructured textual data. So, it is a straight deduction that text mining and data mining have similarities. For instance, both systems have features as pre-processing routines, pattern-discovery algorithms, and presentation-layer elements, however, while text mining works on unstructured data, data mining works on data with known and fixed structure. 32 4.1. APPLICATIONS OF TEXT MINING 4.1 Applications of Text Mining While much of the pre-processing tasks in data mining focus in data cleaning, normalizing and creating extensive numbers of table joins in a structured database, in the context of text mining systems, preprocessing operations focus in pattern identification and extraction of representative features for natural language documents. These pre-processing operations transform the unstructured data contained in the documents into a structured intermediate representation of the original document [95]. So, application of Text Mining can enrich some research areas, such as Information Retrieval, Information Extraction, Categorization and Natural Language Processing . 4.1.1 Information Retrieval According to [114] information retrieval (IR) “is finding material (usually documents) of an unstructured nature (usually text) that satisfies an information need from within large collections (usually stored on computers).” In other words, an IR model selects or ranks the set of documents regarding to an user query. Both result text in documents and queries can be formalized by a function that returns a Retrieval Status Value (RSV) for each document of the collection. Most IR systems represent document contents by a set of descriptors, called terms, belonging to a vocabulary V. According to [106], main IR models define the query-document matching a function that weights the query terms occurring in a document according to four main approaches: • The estimation of the probability of user’s relevance 𝑟𝑒𝑙 for each document 𝑑and query 𝑞concerning a set 𝑅𝑞of training documents 𝑃𝑟𝑜𝑏(𝑟𝑒𝑙 |𝑑,𝑞, 𝑅𝑞); • The computation of a similarity function between queries and documents in a vector space𝑆𝐼𝑀(𝑑, 𝑞); • The estimation of the probability of retrieving the document 𝑑given a query 𝑞,𝑝(𝑑|𝑞); • The information carried by the query terms in the document, that is the number of bits necessary to code 𝑋𝑖occurrences of the query terms 𝑡𝑖∈q in the document: −𝑙𝑜𝑔2𝑃𝑟𝑜𝑏(𝑑|𝑋1, ..., 𝑋𝑞). An information retrieval system is not a database system. Despite of having close functionalities, mainly the ability to look for answers to the user given queries searching in large information stores, there are significant differences between them, such as: • Database systems Concurrency control; Recovery; Transaction management; Update; 33 CHAPTER 4. TEXT MINING AND NLP • Information retrieval Unstructured documents; Search based on keywords; Concept of relevance. Due to the large amount of information available in text sources, there are many applications for information retrieval, such as on-line library catalogue systems, online document management systems, and, as mentioned by [65], Web search engines as Google Search Engine. 4.1.2 Information Extraction Extraction process is responsible for identifying existent keywords and relationships in a text. According to [82], “the general goal of information extraction is to discover structured information from unstructured or semi-structured text.” It is done through a process called pattern matching, which searches for predefined sequences in the text. The software infers the relationships between all the identified data to give a meaningful information. For example, given the sentence: In 1993, Palhinha, Toninho Cerezo and Muller scored the goals of São Paulo in the interclub world cup against Milan we can extract the following information, PlayerOf(Palhinha, São Paulo) PlayerOf(Toninho Cerezo, São Paulo) PlayerOf(Muller, São Paulo) Such information can be presented to an end user, or can be used as source for other systems such as search engines and database management systems to provide better services to end users. This process is depicted in Figure 15. 4.1.3 Categorization Categorization involves identifying the main themes of a document and organizing them into a fixed number of predefined categories. Using machine learning techniques, the system “learns”how to classify from examples, performing the category assignment automatically. This is a supervised learning problem. 34 4.1. APPLICATIONS OF TEXT MINING Figure 15: Process of Information Extraction from Texts. Source: author During the categorization process, a computer program will see the document as a “stemmed bag of words”, i.e., a set of individual words where each word is “stemmed”(as will be described at subsection 4.2.2), suitable for the learning algorithm and the classification task. This process of changing the document is part of preprocessing techniques, that is described at section 4.2. Different from information extraction, according to [199] “categorization only counts words that appear and then identifies the main topics that the document covers. Categorization often relies on a glossary for which topics are predefined, and relationships are identified by looking for large terms, narrower terms, synonyms, and related terms.” A good example of classification can be seen in Gmail1or other mailboxes, where the messages are automatically classified in some different categories such as spam, social and promotions. 4.1.4 Natural Language Processing Natural Language Processing (NLP) consists of the development of computational models to perform tasks that rely on informations expressed in some natural language (for example, translation and interpretation of text and human-machine interface) [170]. According to [26], the research in NLP is focused, essentially, on three aspects of communication in natural language: • Sound: phonology; • Structure: morphology and syntax; • Meaning: semantic and pragmatic. Phonology is related to the recognition of sounds that compound the words of a language. Morphology recognizes words regarding primitive units that comprise it (for example ” watched ”→watch + ed). The syntax defines the structure of a sentence, based on how the words are related in the sentence, as 1http://www.gmail.com 35 CHAPTER 4. TEXT MINING AND NLP illustrated in Figure 16. The semantics associates are a meaning with a syntactic structure, regarding the meanings of the words composing it. Finally, pragmatics show how context contributes to meaning (e.g. in the context blockbuster, ” classic ”→refers to old film which won prizes). Figure 16: Syntactic Tree 4.2 Techniques of Text Preprocessing In order to have assertive results in text mining operations, it is necessary to extract the relevant information and avoid the irrelevant information. For this reason, text mining uses various preprocessing techniques to identify and extract structured representations from raw unstructured data sources. According to [50] “preprocessing tasks generally convert the information from each original data source into a canonical format before applying various types of feature extraction methods against these documents to create a new collection of documents fully represented by concepts.” Despite classifying text mining preprocessing technique, the use of most algorithms in text mining preprocessing activities is not restricted to particular tasks, and several quite different algorithms can solve a major part of the problem. Often, the same algorithm is used alone or in combination with other algorithms for different tasks, constituting different techniques. For instance, Hidden Markov models (HMMs) can be used for part-of-speech (POS) tagging and named-entity recognition (NER). In general, each preprocessing technique receives an unstructured document as input and proceeds to add information to the structure by analysis the present features. When finishing, the most important information about meaning-representing features are used for the text mining, whereas the rest is discarded. The major difference between preprocessing techniques is related to the nature of the input representation and the output features. While NLP-based techniques use and produce domain-independent linguistic features, text categorization and information extraction (IE) techniques deal with the domain-specific knowledge. One still unsolved problem is to combine the processes of different techniques instead of combining the results. For instance, POS ambiguities generally can be solved by searching at the syntactic roles of the words. In the same way, 36 4.2. TECHNIQUES OF TEXT PREPROCESSING structural ambiguities can be resolved through domain-specific information. Furthermore, a large part of the text in any document does not contain relevant information but must be processed before being considered useless and discarded in the final stage. It turns the process extremely inefficient. Thus, the processes must be executed in parallel, exchanging information with each other. However, because the algorithms were created for different tasks, it is very difficult to redesign them to run simultaneously. There are some attempts to find an algorithm, or a set of algorithms to perform most of the preprocessing task in a single large step. Preprocessing is a very important step in text mining processes and applications. It is the first step not only for text mining approaches but also in data mining. There are several preprocessing techniques used to extract information from text, and their usage is according to the characteristics of the information desired. Despite some techniques were created in data mining, they are used in text mining approaches, since the same technique can be used for both information extraction, information retrieval, or combined. Some most used techniques are described below. 4.2.1 Tokenization Tokenization is considered one of the grand challenges of NLP and is conventionally interpreted as breaking up “natural language text [...] into distinct meaningful units (or tokens)”[87]. In order to occur more sophisticated processing, the text stream must be split into tinier meaningful constituents. Documents can be split into chapters, sections, paragraphs, sentences, words, and even syllables or phonemes, according to the needs. The most used approach in text mining systems consists in breaking the text into sentences and words, which is called tokenization. Possibly, the most difficult task in identifying sentence in the English language is distinguishing the difference between a period that signals the end of a sentence and a period that is part of a previous token like Mr., Dr., etc. and others. It is common for the tokenizer also to extract token features. These are usually simple categorical functions of the tokens describing some superficial property of the sequence of characters that make up the token. Among these features are types of capitalization, the inclusion of digits, punctuation, special characters, and so on. However, when tokenizing a text, it is important to be aware of some problems as: • Different languages - Languages that do not mark word boundaries (like white spaces) to differentiate the tokens, as Chinese and German, present a challenge because an original word would be broken in 2 or more tokens; • Punctuation - Unless text provide some punctuation, it is hard to find the end-of-sentence. Interpret “apples, bananas, grapes”must be the same as “apples bananas grapes”; 37 CHAPTER 4. TEXT MINING AND NLP • Hyphens - Words that contain hyphens must be considered as a single word, as middle-office while words connected by grammatically required hyphens, such as computer-based, should be considered multiple tokens; • Apostrophes - Different than hyphens, apostrophes must be considered as 2 different words ( “we’re here” ⇒ “we are”“here” ), however, for possessives, the rule is considered as a single word. It would be done carefully to avoid understand mistakes, as “it’s” and “its” ; • Tokens that are not words - Sometimes is needed to interpret other text different than words. For instance, license plate or ZIP codes. In these cases, it will be necessary to customize to handle the situations. 4.2.2 Stemming A stemming algorithm is responsible for obtaining the stem of a word, which is, its morphological root, through clearing the parts of the word that bring grammatical or lexical information. In both cases, these parts do not change the concept which word is related to as the semantic informality has been proven in the literature, especially in languages that are highly inflective [158] and in short documents [93], regarding recall and precision. The purposes of a stemming algorithm can be classified into 3 different approaches: A. Clustering words according to their topic - Words which are derivations from the same stem belong to the same concept from the stem (e.g., drive, driven, driver). These derivations are generated through appended affixes (prefixes, infixes, and/or suffixes) but, in general, and more specifically in English, only suffixes are considered, as generally prefixes and infixes modify the meaning of the word, and stripping them would lead to errors of bad topic determination [77]; B. The possibility of IR process improvement - Expanding the query to obtain more precise results allows it to be refined by replacing the contained terms to their related topics present in the collection, or adding these topics to the original query. This process can be done automatically and transparently to users or the system can propose one or more improved formulations of the query to users letting them decide if any of them is more specific and defines better their information needs. According [200], “even if interactive query expansion is better in principle because the user has more feedback on what is happening, typically it cannot be done directly with the result of stemming, as stems usually are not understandable by humans”; C. Reduction of the dictionary - Once the whole vocabulary contained in the original unprocessed collection of documents can be reduced to a set of topics or stems, it would require less space to store the structures used by an information retrieval system and consequently also would light the computational load of the system. 38 4.2. TECHNIQUES OF TEXT PREPROCESSING In the literature, it is possible to find several different implementations of stemming algorithms. The most known stemming algorithms used are: Lovins stemmer [109], Dawson stemmer [31], Porter stemmer [159], Paice/Husk stemmer [147]. 4.2.2.1 Lovins stemmer The Lovins stemmer algorithm is composed of two steps: suffix removal and treatment of the remaining stem. The suffix identification is made by matching the word’s termination with the longest suffix from a list of 294 suffixes. After matching the suffix, it is applied one of the 35 associated application rules, and the remaining stem is treated to solve some linguistic exceptions (like ending in double d or double t). For example, the word nationally finishes with ationally and is associated with condition B, which relates to “minimum stem length = 3.”If removing ationally would leave a stem of length 1 and consequently would be rejected. But it also has ending ionally with associated condition A. Condition A is “no restriction on stem length”, so ionally is removed, leaving “nat.” 4.2.2.2 Dawson stemmer Dawson stemmer algorithm is an extension of the Lovins algorithm which has a wider list of suffixes [185]. In addition to Lovins stemmer, Dawson stemmer also has a single pass stemmer which makes it performs fast. The suffixes are structured and stored by their lengths and last letters. In fact, they are structured as a set of separated character trees for quick access. So, the benefit of Dawson stemmer is it covers more suffixes compared to Lovins stemmer and Dawson stemmer. Besides that, it also performs fast. However, the weaknesses of Dawson stemmer include its complexity and lacks standard reusable implementation. 4.2.2.3 Porter stemmer Porter stemming algorithm probably is the most known stemming methods. Simple, it has 60 suffixes, two transformation rules, and context-sensitive rule to determine whether a suffix should be removed or not. The algorithm is composed of 5 steps, each one containing specific rules for removing suffixes or transforming the words: the first is responsible for handling inflectional suffixes; the second, third and fourth are responsible for handling derivational suffixes while the fifth is responsible for recoding. In a formal model, their rules are simple can be seen like this: 𝑁𝑆 =𝑓(𝐶, 𝑆)(4.1) where: NS = new suffix C = Condition 39 5 Word Representation The representation of words in natural language processing (NLP) can be considered as one of the basic building blocks because makes possible the understanding of a human language by a machine. According to [197], “a word representation is a mathematical object associated with each word, often a vector. Each dimension’s value corresponds to a feature and might even have a semantic or grammatical interpretation, so we call it a word feature”. 5.1 Word Representation Approaches In the last years, the approaches for word representation gained an increased importance in the NLP processes. From simple techniques of counting word frequencies to identifying the context of words, each approach has pros and cons in their utilization. 5.1.1 Dictionary Lookup Dictionary Lookup is the simplest approach of word representation, consisting in a word ID lookup in a dictionary. Due to their simplicity, it is difficult to find a sophisticated definition about dictionary lookup, being essentially a set of key/value pairs, where the key is an unique word and the value is an unique ID which represents the word. The words contained in the set of keys are collected from a corpus - which can be collection of words, sentences or texts - where the words are preprocessed (using some techniques presented in Section 4.2), hereafter called “ vocabulary ”. Then, for each given word, the dictionary returns the corresponding word’s ID by looking it up in the dictionary. If the word is not present in the dictionary, the dictionary should return an “Out of Vocabulary”code. An example of this kind of dictionary is presented in Table 4. Despite being easier and simple to implement, this approach has some important drawbacks which must be taken into consideration. By considering IDs as integer numbers, the model might assume the existence of relations just considering the order of this IDs. For example, if the dictionary contains entries 46 5.1. WORD REPRESENTATION APPROACHES Table 4: Dictionary Lookup example Word ID planet 1 water 2 motorcycle 3 goal 4 objective 5 Portugal 6 such as 1: “player”and 2: “referee”, the higher ID number might be incorrectly considered as “more important”by the Machine Learning models than the least ID numbers. On the other hand, using the IDs to represent information, such as size measures 1: “small”, 2: “medium”, 3: “large”is suitable for this case because there is a natural ordering in the data. 5.1.2 One Hot Encoding / Bag of Words One hot encoding / Bag of words is a well-known process in NLP that maps the occurrence of all words existent in a corpus into a vector. Thus, it is possible to represent any sentence as a vector of integers. This approach considers that a text can be represented as a list of sentences, and on the other hand, a sentence can be represented as a list of words (or tokens, as presented in Subsection 4.2.1). So, the number of distinct words existent in the text, denotes the word vector size, where each position of the array represents a word at the same index in the set of distinct words (where this set is generally alphabetically sorted). The resulting sentence’s representation is an array of integers containing at each position the frequency of the word in the sentence. This approach is known as Bag of Words model, because it loses the order of how the words appear in the sentence. An example of the One Hot Encoding / Bag of Words is presented in Figure 17. Figure 17: One Hot Encoding / Bag of Words Representation A variation in One Hot Encoding / Bag of Words creation is identifying the relevance of each word in the sentence considering the existent corpus instead of their frequency. This can be achieved using different solutions, however, the most known is the Term Frequency - Inverse Document Frequency (TF-IDF), as presented in Section 4.2.6. 47 CHAPTER 5. WORD REPRESENTATION A drawback of this approach is that the representation of several sentences will produce immense and sparse vectors. When considering large texts, where the number of different words is higher, the representation of each word or sentence in vectors will require large memory for computation, because each vector has the same size as the number of distinct words. Moreover, once that each sentence has a tiny subset of all distinct words, the vectors will have in their majority zero values as dimensions. Other weakness of this approach is due to the positional reference of the words. As the model does not take into consideration the relationship of precedence among the words, different sentences using the same words will be represented as the same vector. For example, the sentences “John loves chocolate and Anna hates to study”and “Anna loves chocolate and John hates to study”will be represented as the same vector. 5.1.3 Word Embeddings The main problem on the representations based on vocabulary - as dictionary lookup and one hot encoding - is that all fail in not to capture the relational structure of the lexicon. The reason for this problem is that the approaches do not consider as relevant the word’s position in the text. So, determining the context in which the words were presented is impossible. However, different from the approaches presented previously, the Word Vectors take into consideration the proximity among words in texts and similarity when representing them. The characteristic of the Word Embeddings is to represent words as features in vectors, where each entry stands for one hidden feature inside the word meaning, allowing to reveal semantic or syntactic dependencies. An initial approach to describe these vectors is creating a co-occurrence matrix, i.e., a matrix containing the number of counts of each token (word) and a flag indicating if the token is the next neighbour in the sentence. For example, considering the sentence “ I love chocolates, but I hate sports ”, a co-occurrence matrix of each word can be described as presented in Table 5. Table 5: Co-occurrence matrix Token I love chocolates but hate sports I0 1 0 1 1 0 love 1 0 1 0 0 0 chocolates 0 1 0 1 0 0 but 1 0 1 0 0 0 hate 1 0 0 0 0 1 sports 0 0 0 0 1 0 So, the word vectors for the sentence above would be: 48 5.1. WORD REPRESENTATION APPROACHES I = [0, 1, 0, 1, 1, 0] love = [1, 0, 1, 0, 0, 0] chocolates = [0, 1, 0, 1, 0, 0] but = [1, 0, 1, 0, 0, 0] hate = [1, 0, 0, 0, 0, 1] sports = [0, 0, 0, 0, 1, 0] These results can provide some useful insights. For instance, the words “ love ” and “ hate ” are neighbours to the nouns “ chocolate ” and “ sports ” as well as is neighbour of “ I ”. These proximities and sequences indicate that these words must be verbs. When using word vectors to expand the datasets, some calculations can provide information about the words used in similar contexts - as presented in Subsection 5.2 - giving us insights to their semantic and syntactic relations. According to [127], “we find that the learned word representations in fact capture meaningful syntactic and semantic regularities in a very simple way. Specifically, the regularities are observed as constant vector offsets between pairs of words sharing a particular relationship. For example, if we denote the vector for word i as xi, and focus on the singular/plural relation, we observe that xapple — xapples ≈xcar — xcars, xfamily — xfamilies ≈xcar — xcars, and so on. Perhaps more surprisingly, we find that this is also the case for a variety of semantic relations”. Yet, as the dimensionality of words increases according to the size of the corpus, proportionally, the matrices will grow in size - remaining sparse and compromising storage efficiency. This problem has been focus of research about optimizing the representation of word vectors. The most known approaches are Word2Vec and GloVe. 5.1.3.1 Word2Vec Word2Vec is an open-source tool, developed by [128], which is used to calculate representations of words as vectors. According to [102], Word2Vec “is a popular choice for pre-training the projection matrix 𝑊∈ R𝑑𝑥|𝑉|where 𝑑is the embedding dimension with the vocabulary 𝑉. As an unsupervised task that is trained on raw text, it builds word embeddings by maximizing the likelihood that words are predicted from their context or vice versa. As an unsupervised task that is trained on raw text, it builds word embeddings by maximizing the likelihood that words are predicted from their context or vice versa.” Word2Vec works by taking a corpus as input and returning word vectors as output. A vocabulary is constructed during the process of learning representations as vectors. The tool has defined in its structure two models to represent the vectors: Skip-Gram model and Continuous Bag of Word (CBOW) model, as presented in Figure 18. Both models use a hidden layer neural network to generate output, and the back propagation algorithm to update, or just weigh, the parameter values while observe new examples. 49 CHAPTER 5. WORD REPRESENTATION Figure 18: Illustration of the Continuous Bag-of-Word (CBOW) and Skip-Gram models. Source: [102] Figure 19: CBOW network. Source [53] In the CBOW model the input is a context (surrounding words) and the output an omitted word, i.e., for this representation, the surrounding words are combined to predict the middle word. It is considered as context the words that are around the target word 𝑤. An example is to use as context the two words before 𝑤and the two words after. In the case of a sentence 𝑤1𝑤2𝑤3𝑤4𝑤5the context of the word 𝑤3 is 𝑤1𝑤2𝑤4𝑤5. Different than the the Bag of Words approach, the CBOW can consider different contexts for a single target word. For example, in the sentences: “Ronaldo scored a goal”and “Neymar scored a goal”, both “Ronaldo”and “Neymar”are contexts for the word “scored”. The processing for different contexts is possible by processing 𝑁times the vector word, where 𝑁is the number of different contexts the word appears in the corpora. Each 𝑁word existent into the corpora will produce a vector 𝑊1, in the context 𝑘. These vectors will feed the hidden layer that will produce a 𝑊2𝑘𝑥𝑛 matrix to the output layer. In the output layer, a softmax function will calculate the probabilities for a resultant word. An example of CBOW processing is presented in Fig. 19. In the Skip-Gram model, the objective is the inverse of CBOW: given a vector representing a single word, 50 5.1. WORD REPRESENTATION APPROACHES Figure 20: Skip-gram network. Source https://towardsdatascience.com/word2vec-skip-gram-model-part- 1-intuition-78614e4d6e0b it can predict its context. In this case, the input is a word that goes through a hidden layer and outputs the most likely context. The objective, in this case, is to identify the weights for each word calculated in the hidden layer given a word. Once the hidden layer uses a Softmax function as activation function, these weights will represent the probability of the words be the neighbours of a given word. A representation of the Skip-Gram model is illustrated in Fig. 20. 5.1.3.2 GloVe According to [154], the Global Vectors for Word Representation (GloVe) “is an unsupervised learning algorithm for obtaining vector representations for words. Training is performed on aggregated global word-word co-occurrence statistics from a corpus, and the resulting representations showcase interesting linear substructures of the word vector space.” Despite both Word2Vec and GloVe generate word vectors based on word neighbourhood, their difference is that GloVe uses the word co-occurrence global yet to generate the word vectors, not relying only on local statistics (local context words) as Word2Vec. The model is based on the idea that the proportions of probabilities of a word co-occurrence matrix can bring some form of meaning that can be translated as a vectors difference. Therefore, the objective is to identify the relation among the words and represent them as word vectors so that their scaled product is equal to the logarithm of the probability of the words’ co-occurrence. As the logarithm of a ratio is equal to the difference in logarithms, this objective associates the proportions of co-occurrence probabilities with vector differences in the vector space of words. It creates word vectors that perform well in word analogy tasks and in similarity and named entity recognition tasks. An example of GloVe processing is presented in Fig.21. 51 CHAPTER 5. WORD REPRESENTATION Figure 21: GloVe processing. Adapted from https://www.kdnuggets.com/2018/04/implementing-deep- learning-methods-feature-engineering-text-data-glove.html 5.2 Text similarity In Natural Language Processing, one of the most important problems is how to handle the similarity of words and texts. Similar texts and words can represent the same information and emotions, and, once it is impossible to know all words for all contexts, knowing if an unknown word or sentence is similar to a known word or sentence increases the probability of the computer “understand” the meaning and emotion of it. So, an answer for the question ”how to determine how ’close’ two texts or words are ?” is fundamental for a good comprehension of a text. A part of these problems occur due to the spoken language richness, where different words have the same meaning and a single word can assume different meanings. There are different reasons for that such as geographical distance and contextual situations. For example, speakers from Portugal and Brazil share the same language - Portuguese - but some words as rapariga ( girl in Portugal and hooker in Brazil) and fato (coat in Portugal and fact in Brazil) illustrate the effect of distance between the location of the speakers. In the art scenario in Brazil, the expression “quebre a perna” (break the leg) is equivalent to “good luck” , however, in other different contexts, this expression is considered an offensive wish. Other potential source of problems occur when considering the distribution of the words in sentences to evaluate if they are similar. For example, the sentences the dog broke the cat’s bed and the cat slept at the dog’s bed are very similar, because they share 4 out of 6 words. However, it does not take into consideration the meaning of the words or the entire sentence. Thus, this closeness must be evaluated both in a surface closeness (considering a lexical similarity) and meaning closeness (semantic similarity). In the literature there are several approaches to measure the similarity between words and texts. In the following sections, some well known techniques to measure the similarities between texts and words will be described. 5.2.1 Jacquard Coefficient According to [191], “the Jacquard coefficient measures the similarity between finite sample sets, and is defined as the size of the intersection divided by the size of the union of the sample sets”. When transposing this definition to NLP scenario, it is straightforward to identify that each sample set represents a sentence and their content is composed of the set of unique words existent on each sentence. 52 5.2. TEXT SIMILARITY For example, in the sentences: • Sentence A - “The boy loves play soccer” • Sentence B - “The girl wants to play her videogame” we have A = { the, boy, loves, play, soccer } B={ the, girl, wants, to, play, her, videogame } So, the Jacquard coefficient for these sentences would be: 𝐽𝑎𝑐𝑞𝑢𝑎𝑟𝑑𝐶𝑜𝑒𝑓 𝑓 𝑖𝑐𝑖𝑒𝑛𝑡(𝐴,𝐵)=𝐴∩𝐵 𝐴∪𝐵=2 10 =0.2 resulting in a similarity of 20% between the sentences. Despite its ease of use, the Jacquard coefficient is considered a “weak” measure of similarity. The weakness of the approach happens because its application is based only on the frequency of words in the texts. However, different words can have the same meaning in a sentence and; even if applied preprocessing techniques of text, such as Stemming and Lemmatization - as presented in sections 4.2.2 and 4.2.3 respectively - the synonyms will not be identified. Furthermore, this approach does not capture the context of the sentences. The sentence “I saw a man on a hill with a telescope” can be interpreted in different ways according to the context which is related to. An example of different interpretations of this sentences are: • The man seen had a telescope; • I used a telescope to saw the man. So, discarding the context when considering the similarity of sentences can bring misunderstandings. 5.2.2 Euclidean Distance The Euclidean Distance is - possibly - the simplest approach to measure the similarity between two texts. It uses Pythagorean Theorem to determine the distance between two points in a plane or in a n-dimensional space. In a generalization for an n-dimension, the Euclidean Distance can be represented as the formula: 𝐷𝑖𝑠𝑡(𝑝,𝑞)=v t𝑛 Õ 𝑖=1 (𝑝𝑖−𝑞𝑖)2 53 CHAPTER 5. WORD REPRESENTATION Figure 22: Euclidean Distance. Source https://morioh.com/p/05256ee15f96 where 𝑛is the number of dimension existent and 𝑝and 𝑞represent points in the space. When considering the Euclidean Distance for textual similarity measurement, the most common approach is to define the set of words in the text as dimensions and the number of their occurrences as the values in the dimension. However, this approach fails because the texts generally have different sizes and words - and consequently different dimensions. So, calculating the Euclidean Distance between texts with different sizes and words will produce unrealistic values. For example, suppose that in 3 different scholar books (Math, Psychology and Philosophy), the words harmony and theory occurs 10, 40 and 70 and 60, 20 and 25 respectively. In a 2D-representation, it is possible to translate this information as presented in Fig. 22. Finally, the Euclidean Distance can be measured as the distance between the points. 5.2.3 Cosine Similarity The Cosine Similarity is one of the most used technique to measure the similarity between texts, being used together with word embeddings. The concept is based on the idea of all texts are represented as vectors - as presented in sections 5.1.2 and 5.1.3, and their similarities are calculated as a product of these vectors. For example, let’s consider two vectors −→ 𝑎and −→ 𝑏representing two words respectively. These vectors can be represented as −→ 𝑎=(𝑎1, 𝑎2, 𝑎3, ...)and −→ 𝑏=(𝑏1,𝑏2,𝑏3, ...), where 𝑎𝑛and 𝑏𝑛are components of the vector. The value of each component can be the occurrence frequency of each word, the TF-IDF value for each word or the word embedding vector and 𝑛is the dimension of the vector. 54 5.2. TEXT SIMILARITY Figure 23: Right-Angled Triangle Based on the mathematical principle that if two elements have some degree of similarity, they are multiple by some scale, it is possible to infer that the similarity between the vectors −→ 𝑎and −→ 𝑏is the product between these two vectors, i.e., the dot product −→ 𝑎.−→ 𝑏. The geometric definition of dot product, is: −→ 𝑎 .−→ 𝑏=||−→ 𝑎||.||−→ 𝑏|| cos 𝜃 When analysing a right-angled triangle, as presented in Fig. 23, being A and B represented by the directions of −→ 𝑎and −→ 𝑏and an angle 𝜃, it is possible to identify that the projection of −→ 𝑎into −→ 𝑏is a multiple of −→ 𝑏. The value of |𝐴|𝑐𝑜𝑠𝜃 is called cosine similarity between −→ 𝑎and −→ 𝑏. So, as higher is the 𝜃angle, the lesser will be the projection of −→ 𝑎into −→ 𝑏. In a situation where the 𝜃=90◦, there will not be a projection from −→ 𝑎into −→ 𝑏, so it is possible to claim that the vectors (and the texts whose they represent) do not have a relationship, as if 𝜃>90◦, the projection will result in a negative value. Thus, the range of values provided by the cosine similarity is from -1 to 1, which is the same range of Pearson’s correlation coefficient (𝑟2). Once the 𝑟2provides a scale of interpretation of how data are related, as presented in Table 6, it is possible to use the same scale to interpret how similar two words are. For example, in Section 5.1.3, the vectors for the words love and hate are: love = [1, 0, 1, 0, 0, 0] hate = [1, 0, 0, 0, 0, 1] To identify how similar the words are, it is necessary to check the cosine similarity between the words - which is 0.5 - and interpret this value according to the Table 6. 55 CHAPTER 6. EMOTIONAL STATE CLASSIFIER A. Collect messages; B. Preprocess all messages; C. Creates and updates a personal vocabulary; D. Calculate the emotional distribution of the messages according to the vocabulary. At the learning stage, the processes use the emotional distribution of the messages to create machine learning models. The models created (one per author in Time Series models and all-authors models in Classification and Regression models) will feed the Presentation Module and provide the output format for the Web API requests. 6.1.2 Web API Initially, the architecture was planned to have front-end and back-end modules, however, during its development, it was realized that there is no need for a front-end module. This led to the creation of a single module to provide the emotional state detection service. Thus, it was decided to create a Web API to provide the detection of the emotional state, enabling any software developer to consume that service and provide this functionality on his software, regardless of the type of device under which the software is running. So, the Web API has methods that receive texts independently from their origins, such as files, social media, smartphone logs, SMS messages, etc. In order to increase the flexibility, both input and response data will communicate in an interoperable format. For this reason, all methods in these categories use JSON as format type for inputs and outputs, enabling the software developer to use the operating system as programming language. After those considerations, four Web API methods were created: • InputTrainingData - Is the entrance door to input data for training; • RequestClassification - Is the method responsible to provide the emotional state classification based on a set of given messages; • RequestRegression - Is the method responsible to return a set of emotional state percentages based on a set of given messages; • PredictEmotionalLevels - Is the method that predicts and returns the level of each Pluchik’s 8 basic emotion, taking into consideration the past level of the emotions. The Web API provides a communication channel with the client software and for this reason, the format of both request and response methods must be known. According to the Web API method, the JSON formats that must be used are different, as presented in next sections. 62 6.1. ARCHITECTURE 6.1.3 InputDataTraining The InputDataTraining is the API method responsible to allow the input of labelled texts from different authors and sources to train the models to predict the emotional state and future emotional levels. The input can be used to provide new data or add data to the existing one, regarding some specific text writer (the author). Its flow contains three different paths that occur separately, and is exactly the learning phase, being responsible to provide all data needed to feed the models to be trained. The flow starts when the messages are received; the those messages are preprocessed by a Data Preparation task to remove unnecessary information and simplify the texts to be processed. After the preprocessing, the flow is divided into 2 paths: the first one starts with the Vocabulary Personalization Module to create / update the personal lexicon of the texts writer (the author). Later, the text messages have their Emotional Profile identified according to the personal vocabulary and finally the information flows to the creation of a Time Series Model, where a time-series model for each author’s emotions is created. Following the second path, information (text messages) flows directly to the Emotional Profile identification to calculate the distribution of each basic emotion in each sentence. These distributions will feed 2 paths: one responsible to create a classification model; and the other responsible to create a regression model. Along the steps described above, the data computed are saved in a database for future researches and follow up the authors emotions over the time. 6.1.3.1 Input and output data formats The InputTrainingData method receives a list 𝑀𝑒𝑠𝑠𝑎𝑔𝑒𝑠 of structures 𝑇𝑒𝑥𝑡 (𝑡𝑥𝑡, 𝑙𝑎𝑏𝑒𝑙, 𝑎𝑢𝑡ℎ𝑜𝑟, 𝑠𝑜𝑢𝑟𝑐𝑒,𝑑𝑎𝑡𝑒𝑡𝑖𝑚𝑒) as parameter to train the Classification Model, the Regression Model and the Time Series Emotional Model. In a formal definition, it receives: 𝑀𝑒𝑠𝑠𝑎𝑔𝑒𝑠 ={𝑡𝑒𝑥𝑡1, 𝑡𝑒𝑥𝑡2, 𝑡𝑒𝑥𝑡3, ...𝑡𝑒𝑥𝑡𝑛} 𝑡𝑒𝑥𝑡𝑖=<𝑡𝑥𝑡, 𝑙𝑎𝑏𝑒𝑙, 𝑎𝑢𝑡ℎ𝑜𝑟, 𝑠𝑜𝑢𝑟𝑐𝑒,𝑑𝑎𝑡𝑒𝑡𝑖𝑚𝑒 >where: 𝑡𝑥𝑡 is the text to be analyzed; 𝑙𝑎𝑏𝑒𝑙 corresponds to the author’s emotional state when produced the text; 𝑎𝑢𝑡ℎ𝑜𝑟 is an id reference for the author of the text; 𝑠𝑜𝑢𝑟𝑐𝑒 is an identification of the source from where the data was inputted; 𝑑𝑎𝑡𝑒𝑡𝑖𝑚𝑒 is the date & time when the message was produced. 63 CHAPTER 6. EMOTIONAL STATE CLASSIFIER An example of the InputTrainingData’s input format is presented below: 1{ 2"Messages":{ 3"Text":[ 4{ 5"datetime":"2020-04-20 15:32:35", 6"source":"1", 7"label":"Depression", 8"author":"1", 9"text":"Sometimes I want to cry without reason" 10 }, 11 { 12 "datetime":"2020-04-22 17:58:10", 13 "source":"1", 14 "label":"Anxiety", 15 "author":"2", 16 "text":"I just want to work after the lockdown" 17 } 18 ] 19 } 20 } The InputTrainingData’s method returns a message in JSON format indicating the status of the process, as presented below: 1{"response":"Sucess"} 6.1.4 RequestClassification The RequestClassification method is the core of this work. It receives a set of text messages and returns the emotional state related to the emotions detected in the texts. In order to identify the author’s emotional state, the pipeline - as presented in Fig. 28 - performs a sequence of 6 steps to classify the emotional state according to the texts received. Figure 28: RequestClassification pipeline 64 6.1. ARCHITECTURE These steps are: 1) The method receives a list 𝑀of messages to be analysed; 2) The Data Preparation preprocess the data; 3) The Emotional Profiler identifies the emotions for each sentence contained in 𝑀; 4) The source’s classification model is loaded; 5) The emotions are grouped and normalized and the emotional state is predicted using the source’s classification model; 6) The information is returned. 6.1.4.1 Input and output data formats The RequestClassification method, receives a list 𝑀of structures𝑇(𝑡𝑒𝑥𝑡,𝑠𝑜𝑢𝑟𝑐𝑒)as parameter to predict the emotional state. In a formal definition, it receives: 𝑀={𝑡1, 𝑡2, 𝑡3, ...𝑡𝑛} 𝑡𝑖=<𝑡𝑥𝑡, 𝑠𝑜𝑢𝑟𝑐𝑒 > where: 𝑡𝑥𝑡 is the original text to be analyzed; 𝑠𝑜𝑢𝑟𝑐𝑒 is an identification of the source from where the data was inputted. An example of the RequestClassification’s request is presented below: 1{ 2"Messages":{ 3"Text":[ 4{ 5"source":"1", 6"text":"Nothing at all in my life is running ok" 7}, 8{ 9"source":"1", 10 "text":"I really want to be happy" 11 } 12 ] 13 } 14 } 65 CHAPTER 6. EMOTIONAL STATE CLASSIFIER The RequestClassification’s response returns a message in JSON format indicating the status of the process, as illustrated below: 1{"classification":"Depression"} 6.1.5 RequestRegression The RequestRegression method is an auxiliary method to provide a more detailed information about the classification. It receives a set of text messages and returns a list of all emotional states and their respective percentage, according to the emotions detected in the texts. In order to identify the percentage of each emotional state in the messages, the pipeline - as presented in Fig. 29 - performs a sequence of 6 steps to calculate the emotional state’s percentage according to the texts received. Figure 29: RequestRegression pipeline These steps are: 1) The method receives a list 𝑀of messages to be analysed; 2) The Data Preparation preprocesses the data; 3) The Emotional Profiler identifies the emotions for each sentence contained in 𝑀; 4) The source’s classification model is loaded; 5) The emotions are grouped and normalized and the emotional state is predicted using the source’s classification model; 6) The information is returned. 6.1.5.1 Input and output data formats The RequestRegression method, receives a list 𝑀𝑒𝑠𝑠𝑎𝑔𝑒𝑠 of structures 𝑇𝑒𝑥𝑡 (𝑡𝑥𝑡, 𝑠𝑜𝑢𝑟𝑐𝑒)as parameter to predict levels of each emotional state. In a formal definition, it receives: 𝑀𝑒𝑠𝑠𝑎𝑔𝑒𝑠 ={𝑡𝑒𝑥𝑡1, 𝑡𝑒𝑥𝑡2, 𝑡𝑒𝑥𝑡3, ...𝑡𝑒𝑥𝑡𝑛} 𝑇𝑒𝑥𝑡𝑖=<𝑡𝑥𝑡, 𝑠𝑜𝑢𝑟𝑐𝑒 > 66 6.1. ARCHITECTURE where: 𝑡𝑥𝑡 is the text to be analysed; 𝑠𝑜𝑢𝑟𝑐𝑒 is an identification of the source from where data was inputted. An example of the RequestRegression’s request is presented below: 1{ 2"Messages":{ 3"Text":[ 4{ 5"source":"1", 6"text":"Nothing at all in my life is running ok" 7}, 8{ 9"source":"1", 10 "text":"I really want to be happy" 11 } 12 ] 13 } 14 } The RequestRegression’s response returns a message in JSON format indicating the level of the each emotional state, in a range from 0 up to 1, as illustrated below: 1{ 2"EmotionalStates":{ 3"EmotionalState":[ 4{ 5"Name":"Depression", 6"Level":"0.84" 7}, 8{ 9"Name":"Happiness", 10 "Level":"0.04" 11 }, 12 { 13 "Name":"Anxiety", 14 "Level":"0.12" 15 } 16 ] 67 CHAPTER 6. EMOTIONAL STATE CLASSIFIER 17 } 18 } 6.1.6 PredictEmotionalLevels The PredictEmotionalLevels provides information about an author’s future emotional levels, taking into consideration the previous emotional levels. This is a relevant information because according to the psychological bibliography, some diseases - such as depression - need to be followed up for a long time prior to be diagnosed. However, it is possible an individual begins to demonstrate depressive signals in the last messages, but he won’t have his emotional state classified as depressive because of the lack of information in the time. For this reason, this method predicts the emotional levels of an individual, allowing to identify individuals with risk of future diseases. In order to predict each basic emotion of an author, the pipeline - as presented in Fig. 30 - performs a sequence of 5 steps to calculate the emotional state’s percentage according to the texts received. Figure 30: PredictEmotionalLevels pipeline These steps are: 1) The method receives the author id; 2) The Time Series personal model is loaded; 3) The most recent last 12 weeks emotions are loaded from the database; 4) The emotions are predicted for the next 4 weeks; 5) The information is returned. 6.1.6.1 Input and output data formats The PredictEmotionalLevels method, receives a structure 𝐴𝑢𝑡ℎ𝑜𝑟 (𝑠𝑜𝑢𝑟𝑐𝑒, 𝑖𝑑)as parameter to predict the user’s future emotional levels. In a formal definition, it receives: 𝐴𝑢𝑡ℎ𝑜𝑟 =(𝑠𝑜𝑢𝑟𝑐𝑒, 𝑖𝑑) 68 6.1. ARCHITECTURE where: 𝑠𝑜𝑢𝑟𝑐𝑒 is the source (Twitter, SMS, WhatsApp) from where the data was inputted; 𝑖𝑑 is the author id that the predictions refers to. An example of the PredictEmotionalLevels’s request is presented below: 1{ 2"source" :"4", 3"id" :"3" 4} The PredictEmotionalLevels’s response returns a message in JSON format containing the distribution of each basic emotion up to 4 weeks, as presented below: 1{ 2"Week1":{ 3"Anger":"0.15", 4"Anticipation":"0.15", 5"Disgust":"0.22", 6"Fear":"0.14", 7"Joy":"0.06", 8"Sadness":"0.18", 9"Surprise":"0.07", 10 "Trust":"0.07" 11 }, 12 "Week2":{ 13 "Anger":"0.05", 14 "Anticipation":"0.13", 15 "Disgust":"0.26", 16 "Fear":"0.13", 17 "Joy":"0.07", 18 "Sadness":"0.21", 19 "Surprise":"0.08", 20 "Trust":"0.7" 21 }, 22 "Week3":{ 23 "Anger":"0.12", 24 "Anticipation":"0.17", 25 "Disgust":"0.17", 26 "Fear":"0.16", 69 CHAPTER 6. EMOTIONAL STATE CLASSIFIER 27 "Joy":"0.09", 28 "Sadness":"0.19", 29 "Surprise":"0.02", 30 "Trust":"0.08" 31 }, 32 "Week4":{ 33 "Anger":"0.08", 34 "Anticipation":"0.10", 35 "Disgust":"0.28", 36 "Fear":"0.17", 37 "Joy":"0.08", 38 "Sadness":"0.16", 39 "Surprise":"0.06", 40 "Trust":"0.07" 41 } 42 } 6.2 Tasks Each method defined in the Web API needs to invoke some tasks to produce the results. Here is presented an overview about these tasks. The most relevant tasks used by the emotional state classification system are: • Data Preparation; • Emotional Profiler; • Vocabulary Personalizer; • Time Series Model Builder; • Classification Model Builder; • Regression Model Builder. They will be described in the next subsections. 70 6.2. TASKS 6.2.1 Data Preparation The objective of Data Preparation is to preprocess the texts received, reducing the set of original words to a set containing only emotional words. This task reduces significantly the size of the dataset to be processed. In general, preprocessing is the first step in NLP approaches being used to extract relevant information from text, relationships and other useful insights which the words can carry on. Figure 31: Data Preparation pipeline The Data Preparation was idealized to perform a pipeline to clean the input text prior to analyse it. The pipeline, as presented in Fig. 31, begins when the data is received. In a formal description, the data received is a set 𝐷𝑇 of sentences 𝑆𝑇 where: 𝐷𝑇 ={𝑠𝑡1,𝑠𝑡2, ...,𝑠𝑡𝑛},𝑛 >0 𝑆𝑇 ={𝑤1,𝑤2, ...,𝑤𝑘}, 𝑘 >0 𝑊𝑘is a word at position 𝑘 The next step in the pipeline saves 𝐷𝑇 in the database to keep its original text prior the processing. At the third step, all messages are analysed to detect known N-Grams (bigrams and trigrams essentially). The objective of this step is avoid that known expressions (such as “be right back”) with more than one word be handled as a set of single words. Through a list of known expressions, all messages are analysed in order to identify the existence of a known expression. If identified, the expression in the sentence is updated to its “ngrammed” version. Then, the sentences are analysed through a part of speech tagger. This process identifies the grammatical categories of the words contained in a sentence. The idea in this process is to keep only nouns, verbs, adverbs and adjectives. This is important because only these grammatical categories can bring emotional information. Moreover, this approach helps to decrease the processing time, because the step of stopwords removing is not necessary since the grammatical category of the most known stopwords are different than nouns, verbs, adverbs and adjectives used in this approach. Later, the remaining sentences are tokenized, i.e., all sentence is considered as an array of words. For each word in this array of words, it lemmatizes the word to a normalized form. This process uses lemmatization instead of stemming because the lexicon’s words rate identification is higher when compared to stemming. So, this step is more important to us because it increases the rate of identification of words in the emotional lexicon. 71 Part III Case Studies 78 This part presents some case studies using emotional information, aiming at demonstrating different real applications of the emotional state classification. This part is a compilation of papers submitted and presented in conferences. Each chapter in this part corresponds to one of those papers, however to avoid repetitive information, the papers were not included directly; they were slightly adapted and the sections regarding to the state of the art and the approach proposed in this Ph.D. work were removed, because their content was presented with more detail in Part I; also suggestions for future work were removed from th last section. However, to keep the context and motivation, or the approach followed to deal with each case study, it is possible that some paragraphs may sound repetitive. The case studies chosen and discussed in the next chapters aim at demonstrate: • How emotional profile can differentiate people; • How to create and represent a personal vocabulary and their individual emotions; • How each one of us tend to be attracted and create good relationships with people with similar emotional profiles; • How the emotions affect the daily routines, and how to detect and forecast them using texts; • How to use emotions to predict a population’s behaviour; • How to use text to classify emotional state individually. 7 Case Study 1 - User identification by emotional profile Since Barack Obama’s election, the politicians are using social media to have a direct contact with their voters and increase its credibility with their posts and comments. On the other hand, this direct channel enables a correct perception by the voters about the politics, creating opinions about the subjects they consider important. This phenomenon is increasingly turning politicians into digital influencers. So, the way as they communicate in social media can be considered their “personal signature”; so their worries about the way how they can be interpreted are equally important. With massive information from social media, the digital influencers and their legion of followers validate, reinforce and amplify news, many times faked. As the main objective of these individuals is be “liked, loved and shared”, it is very important to choose correctly the words contained into their texts, in order to maximize the sentiment raised up in the readers. So, the emotional characteristics contained in the messages make up an “emotional profile”about the author and which, along with the words used in the text, helps to determine the message’s author profile while writing. For example, the following posts are from different authors and deal the same theme - the Paris Climate Agreement - however, the writing styles are different and arouse different emotions. While the first balances positive and negative words in the text, the second mostly uses words with negative emotions: “Today marks a crucial step forward in the fight against climate change, as the historic Paris Climate Agreement officially enters into force. Let’s keep pushing for progress”(Barack Obama); “I’m optimistic we can stop climate change and help those who are being hurt the most by it—all while meeting the world’s energy needs”(Bill Gates). In this case study, it is presented an approach using the author emotional profile in order to improve the authorship identification. 80 7.1. DATA ANALYSIS 7.1 Data analysis In order to predict the authors of a post based on the emotion contained in text, 2100 Facebook posts were collected from 8 different authors of different areas, as presented in Table 9. All data was collected at the same time span, reducing temporal situations interference in the text emotions. In order to compare all information, the posts were manually labelled into 2 categories: politicians and non-politicians. Table 9: Posts authors Author Area Category Barack Obama Politics Politician Bill Gates Business Non-Politician Donald Trump Business Non-Politician Hillary Clinton Politics Politician Jeremy Corbyn Politics Politician Leonardo Di Caprio Entertainment Non-Politician Magic Johnson Sports Non-Politician Theresa May Politics Politician The task of predict the author of a text is composed of several intermediates steps. First, it was needed some preprocessing tasks in order to reduce data size by removing unnecessary text from the original message. Preprocessing is a very important step in text mining processes and applications. It is the first step not only for text mining approaches but also in data mining. There are several preprocessing techniques useful in order to extract information from text, and their usage is according to the characteristics of the information desired. Despite of some techniques were created in data mining, they are useful in text mining approaches, since the same technique can be used for both information extraction, information retrieval, or combined The preprocessing, after the tokenization, was divided in 3 parallel jobs, as showed in Fig. 37: Part of Speech Tagging (POS-T), Named Entity Recognition (NER) and Stopwords Removal. This strategy was used because both POS-T and NER need the text in the original format, in order to return the correct data from the analysis. The POS-T process identifies the text grammatical structure. Concerning text cleaning, only nouns, verbs, adverbs and adjectives were preserved. This is important because only these grammatical categories can bring emotional information. So, in a more formal way, the Tokenization process converts the original text 𝐷in a set of tokens 𝑇={𝑡1, 𝑡2, ..., 𝑡𝑛}where each element contained in 𝑇is part of the original document D. Later, the POS-T labels each token with a semantic information. Later, a process collects all nouns, verbs, adverbs and adjectives in a set P, where 𝑃𝑇={𝑝(𝑇,1), 𝑝(𝑇,2), ..., 𝑝(𝑇,𝑘)}and 0 ≤k≤n and 𝑃𝑇⊂𝑇. 81 CHAPTER 7. CASE STUDY 1 - USER IDENTIFICATION BY EMOTIONAL PROFILE Figure 37: Preprocessing tasks Similarly, NER process identifies names in 3 different categories: “Location”, “Person”and “Organization”. Once identified tokens in one of these categories, they are removed. As a result, a set 𝑁𝑇={𝑛(𝑇,1), 𝑛(𝑇,2), ..., 𝑛(𝑇,𝑗)}is constructed based on identified word category and where 0 ≤j≤ n and 𝑁𝑇⊂𝑇. This step is important to be done in parallel with POS because some locations can be confused with nouns (as Long Beach, for instance). The Stopwords list is a personal predefined set 𝑆𝑊 ={𝑠𝑤1, 𝑠𝑤2, ...𝑠𝑤𝑦}of words, manually created according to several similar lists available on the internet. After the 3 preprocessing tasks finish, the result document 𝑆𝑇 must contain a set of words where 𝑆𝑇 =𝑇′∩𝑃𝑇∩𝑁𝑇. Later, in this set 𝑆𝑇 is applied a stemming process to reduce the words to their word stem in order to consider all inflected words as only one, producing the preprocessed text 𝑃𝑅 ={𝑆𝑇1, 𝑆𝑇2, ..., 𝑆𝑇𝑧}ready to be analysed. For all three tasks - POS-T, NER and Tokenization - the Stanford Core NLP [113] toolkit was used. An example using a real post from Barack Obama of text preprocessing is presented in Fig. 38. 7.2 Polarity analysis The first analysis made was aimed at determining the posts polarities. To achieve this objective, after the preprocessing, all sentences contained in 𝑃𝑅 were compared against EmoLex lexicon [133] in order to identify the positive and negative words contained in the text. This analysis did not take into account the intensity of the polarities neither the emotions. When comparing the posts’ polarities according to their author’s category (politicians and non-politicians), the data did not reveal relevant differences between politician and non-politicians, as showed in the Fig. 39. The same analysis was confirmed using the chi-squared test, where was obtained a value 𝜒2=1, indicating that both polarities data (politicians and non-politicians) are not independent. 82 7.2. POLARITY ANALYSIS Figure 38: Preprocessing text example Figure 39: Polarities distribution by category However, this interpretation may lead to a wrong understanding about the scenario. When comparing the polarities by author, according to Fig. 40, it is possible to conclude that while politicians tend to have their posts in the same area in a normal distribution, non-politicians tends to be in the extremes, i.e., they are blunter than politicians when expressing through Facebook and indicating that each author has its own “emotional signature”in his posts. This information is confirmed in Table 10, which presents the positive and negative polarities by author. 83 CHAPTER 7. CASE STUDY 1 - USER IDENTIFICATION BY EMOTIONAL PROFILE Figure 40: Polarities distribution by author Table 10: Polarities by author Author Positive Negative Barack Obama 0.28 0.13 Bill Gates 0.30 0.11 Donald Trump 0.25 0.16 Hillary Clinton 0.35 0.17 Jeremy Corbyn 0.30 0,13 Leonardo Di Caprio 0.34 0.09 Magic Johnson 0.37 0.06 Theresa May 0.36 0.10 7.3 Lexicon-based emotion analysis In order to analyse the emotions contained into the text, it was used a lexicon-based approach, which consists in comparing the labelled emotion contained into the EmoLex lexicon with the preprocessed texts described earlier. Using the emotions model proposed by Plutchik [157], where all sentiment is composed of a set of 8 basic emotions ( anger , anticipation , disgust , fear , joy , sadness , surprise and trust ), all posts where analysed according to this model and a list of emotions in each post was generated, according to Table 11. Hence, when applying the Person’s correlation coefficient (𝑟2) between polarities and basic emotions, as presented in Table 12, it is possible to point which emotions are related with polarities. In a scale ranging from -1 to 1, emotions related with a high 𝑟2value indicates a strong relation with the polarity (as Anger and negative polarity), while high negative 𝑟2values indicates a strong inverse relationship (as Fear and positive polarity). In our approach, ambiguous emotions are classified when the standard deviation for 𝑟2polarity’s value is less than 10% range (i.e. 0.2). 84 7.4. MACHINE LEARNING-BASED EMOTION ANALYSIS Table 11: Basic emotions average per author Author Anger Anticipation Disgust Fear Joy Sadness Surprise Trust Barack Obama 0.08 0.15 0.03 0.10 0.13 0.05 0.05 0.21 Bill Gates 0.06 0.14 0.04 0.08 0.15 0.06 0.06 0.14 Donald Trump 0.06 0.12 0.02 0.09 0.12 0.10 0.04 0.16 Hillary Clinton 0.14 0.26 0.02 0.07 0.22 0.15 0.12 0.30 Jeremy Corbyn 0.08 0.16 0.03 0.08 0.09 0.08 0.06 0.23 Leonardo Di Caprio 0.04 0.11 0.01 0.07 0.09 0.03 0.03 0.16 Magic Johnson 0.03 0.19 0.03 0.05 0.21 0.04 0.07 0.21 Theresa May 0.06 0.17 0.02 0.06 0.14 0.07 0.07 0.22 Table 12: Correlation between polarities and emotions Polarity Anger Anticipation Disgust Fear Joy Sadness Surprise Trust Positive -0.10 0.49 -0,26 -0.90 0.48 -0.22 0.44 0.40 Negative 0.83 0.27 -0,08 0.60 0.01 0.89 0.34 0.37 In summary, positive and negative emotions are important to describe the author’s emotional pattern, while the neutral emotions do not have significant contribution to achieve this objective. the emotions classified in text according to polarities are: • Positive polarity - Joy; • Negative polarity - Anger, Fear, Sadness; • Ambiguous polarity - Anticipation, Disgust, Surprise, Trust. 7.4 Machine learning-based emotion analysis Once identified the average of each emotion from author, the next analysis was to identify the emotional pattern of the author. To achieve this, it was used an approach based on machine learning (ML) techniques. The first attempt was aimed at identifying the lowest prediction rate author. For this, it was used the same messages with just preprocessing and the authors identification in a ML approach. Once this information was obtained only by texts, this value can be considered the lowest acceptable value, and, in case of decreasing this rate, it may be interpreted as a negative influence of emotions in the authors prediction. In our initial tests, the best rate was presented by a SVM implementation through Weka [67] and a 10-fold cross validation in the whole dataset, with a correct prediction precision of 82% of when predicting authors. 85 CHAPTER 7. CASE STUDY 1 - USER IDENTIFICATION BY EMOTIONAL PROFILE When the lowest prediction rate was identified, the next step was to classify using the emotional information. Using the previous preprocessed texts, polarity values and each basic emotion rate, a new dataset was generated in order to be used in ML process. In our tests, it was used the most relevant algorithms for text classification, as SVM, Naive Bayes, Random Forests, however, using a Naive Bayes Multinomial implementation through Weka and a 10-fold cross validation in the whole dataset, returned a precision of 87.41% of correct predictions when predicting authors. Both results (non-preprocessed and preprocessed) are presented in Table 13. Table 13: Detailed accuracy results for non-preprocessed and preprocessed texts Non-preprocessed texts Preprocessed texts Author Precision Recall F-Measure Precision Recall F-Measure Barack Obama 0.933 0.82 0.776 0.907 0.860 0.883 Bill Gates 0.887 0.874 0.836 0.882 0.944 0.912 Donald Trump 0.317 0.465 0.518 0.761 0.556 0.642 Hillary Clinton 0.571 0.686 0.693 0.676 0.762 0.716 Jeremy Corbyn 0.741 0.824 0.814 0.859 0.836 0.847 Leonardo Di Caprio 0.807 0.782 0.734 0.878 0.876 0.877 Magic Johnson 0.867 0.893 0.867 0.945 0.917 0.931 Theresa May 0.495 0.591 0.588 0.649 0.758 0.699 7.5 Conclusion This case study presents a combination of lexicon-based and machine learning approaches to explore the emotions contained in a text through the best practices in sentiment analysis in order to increase the results’ accuracy in authorship identification. Everyone have particular characteristics of expressing themselves, and these personal characteristics can be expressed in their texts. Once the author’s writing style profile is known, by using the emotional information contained into text helps to increase the accuracy on authorship identification. This claiming is based on the successful predictions rate grown from 82% to 87.41% in our tests, besides the values of precision, recall and f-measure which have increased in the majority of the cases, when using emotional labelled data. This improvement can be interpreted as a very satisfactory result as our proposal. 86 8 Case Study 2 - Lexicon personalization It is common in large countries that people share known words with different meanings. In Portugal, people from Lisbon order a draft beer as “imperial” while in Porto is “fino”, however, in Lisbon “fino” can be a polite person and in Porto “imperial” is about everything related to the Portuguese royalty. These words, pronounced by people from different locations express different emotions, and on the other hand, these emotions express the sentiment that the author wanted to transmit when pronounced them. So, it is essential to know what the author wants to transmit, in order to avoid misunderstandings - commonplace when we travel to different countries which speak the same language. If we do not know the author’s meaning for used words in the text, we primarily will “decode” the words according to our comprehension of them. So it could be a problem! In sentiment analysis, the same problem occurs when applying emotional lexicon to detect the emotions embedded in the text. Once one or more persons create the emotional lexicon, different emotional interpretation can be applied to the words, and other some other cannot be present in the lexicon. So, detecting emotions using an emotional lexicon as support is like a “pieces of different points of view” instead of author’s vision. In this case study we present an approach for creating a personal emotional lexicon based on social media messages, using Natural Language Processing. 8.1 Related work According to Dictionary.com, the term lexicon is defined as: A. a wordbook or dictionary, especially of Greek, Latin, or Hebrew; B. the vocabulary of a particular language, field, social class, person, etc.; C. inventory or record. There are several works of lexicon expansion for diversified objectives, and some are more relevant for the present paper as they have been used as a source for the idea proposed. In this section, we survey these inspiring works. 87 9 Case Study 3 - Impact of emotions in usual tasks In any kind of relationship, a golden rule to avoid problems is not taking decisions under emotional pressure. There are several strategies to do this: from counting to ten before responding an unpolished message until taking a break to “refresh the mind” before the decision. However, there are situations, such as tests, where it is impossible to avoid emotional pressure and its consequences. When in a stressful situation, or under strong emotional conditions, people tend to make mistakes more frequently. This situation happens in any profession, and so being able to predict these errors that are consequences of emotional states is an important approach to plan a strategy to decrease or avoid them. For example, how important would it be for transportation companies to know the drivers’ emotional state before travelling, aiming to reduce the risk of accidents? How important would be for a hospital to predict the errors of a doctor, based on his emotions? Errors differ from profession to profession and also the effect of emotions over the work is different. Different data sets must be collected to identify these errors, and to correlate them with the emotional state of the worker. As writers usually express their emotions in the texts they produce through the bag of words they use in each situations, and the typing errors they do along an editing session ca be measured, we intend to model the relation between emotions and errors, using the computer as a case of study. The purpose of the study here reported is to analyse a big collection of texts annotated with editing data to demonstrate that the relation between errors and emotions can be identified, and quantified in order to predict undesired situations. In this paper, we present an approach using Sentiment Analysis and Machine Learning to characterize the impact of emotions in the number of errors during a typing process. After training the model, it will be used to predict new cases in order to assess it. It is not our intention to claim that this approach is an alternative for predicting errors in all situations, however, we think that the approach will lead further future investigation in this relevant topic. 94 9.1. THEORY OF BASIC EMOTIONS 9.1 Theory of Basic Emotions Basic emotion theorists explain that every human emotion is composed of a set of discrete basic emotions [36,80,156]. Many researchers have identified some basic universal emotions. One of the first attempts is a study by [40] which concluded that there are six basic emotions are Dislike , Happiness , Sadness , Anger , Fear and Surprise . His work is based on the theory that human faces can represent this basic emotion as universal pictures. For [156], every sentiment is composed of a set of 8 basic emotions: Anger , Anticipation , Disgust , Fear , Joy , Sadness , Surprise and Trust , represented as a “wheel of emotions”. Furthermore, the combination of basic emotions results in dyads . Plutchik created rules for building the dyads , defining the primary dyads emotions as the sum of two adjacent basic emotions, as Optimism = Anticipation + Joy . Meanwhile, secondary dyads emotions are composed of emotions that are one step apart on the “emotion wheel”, as Unbelief = Surprise + Disgust . The tertiary emotions are generated from emotions that are two steps apart on the wheel, as Outrage = Surprise + Anger . Other well-known emotions model is the Five Factor Model (as known as Big Five), introduced by [124] which suggests that the personality is composed of 5 independent factors: A. Openness to experience - People with high scores like news and tend to be creative. At the other end of the scale are the conventional and orderly, those who like the routine and have a keen sense of right and wrong; B. Conscientiousness - It measures the level of concentration. Those with high scores are highly motivated, disciplined, committed and trustworthy. Those with low results are undisciplined and easily distracted; C. Extroversion - It measures the sense of well-being, the level of energy, and the ability in interpersonal relationships. High scores mean affability, sociability, and ability to impose oneself. Lows indicate introversion, reservation, and submission; D. Agreeableness - It refers to how we relate to others. Many points indicate a compassionate, friendly and warm person. At the other end are the withdrawn, critical and egocentric; E. Neuroticism - It measures emotional instability. People with high scores on this scale are anxious, inhibited, melancholic and have low self-esteem. Those that get low scores are easy to deal with, optimistic and well-liked with themselves. In this case study, we adopt the Plutchik’s model to represent emotions because we consider more realistic, easy to use and this model allows to represent several different emotions through dyads emotion. Moreover, there are some libraries and lexicons used in this work which represent and process the emotions according to this model. 95 CHAPTER 9. CASE STUDY 3 - IMPACT OF EMOTIONS IN USUAL TASKS 9.2 Related work There are several works using sentiment analysis for diversified objectives, and some are more relevant for the present paper as they have been used as a source for the idea proposed. In this section, we survey these inspiring works. However, predicting typing errors from an emotional analysis is an unexplored field and we have not found specific previous works to reference. The usage of emotional labels for predictions was inspired by the work of [118], which uses emotional labels to improve the authorship identification. This is made using Facebook posts from personalities known and a hybrid approach containing lexicon and machine learning approaches. Moreover, [193] have presented a work to extract sentiment strength from the informal English text, using new methods to exploit the de facto grammars and spelling styles of cyberspace, which contributed with the idea of extract sentiment polarities from text. Finally, the work presented by [125] contributed to the idea of predicting writing performance using affective variables to relate to efficacy expectations. 9.3 Data creation In order to analyse the impact of the emotions during the text writing process, it was necessary to analyse texts containing emotional load and meta-information about its creation. For this purpose, the dataset provided by [10] containing keystroke logs for opinion texts about gun control1was used as the basis for a new dataset creation. To perform the intended analysis we actually needed a text repository with emotional load and editing numerical data for each written piece. The option of a keystroke log is justified by the necessity of gather information about the text creation process. So, in our study all texts are considered written “from beginning to end”, i.e., the first typing step without a posterior text revision phase. This is important for levelling possible errors and editing in a same identifiable pattern. The process of the new datasets creation is performed in 2 steps: Meta-information Creation and Emotional Analysis, as presented in Figure 44. Figure 44: Dataset creation process 1This is a hot, sensible, topic provoking emotive reactions on commenters. 96 9.3. DATA CREATION 9.3.1 Meta-information The Meta-information Creation step analyses the keystroke log and calculates metrics about the text creation. For analysis purposes, we defined some metrics considered important in this study. These metrics are: •TimeText - It represents the time spent during the text writing. It is the amount of time span in milliseconds between press and release for each character and white space key in the keyboard. Punctuations, numbers, and others are discarded; •AveragePerWord - Is the average between the total words in the text and the time spent during typing process; •AmountErrors - It is the number of errors during the typing process. It is important to emphasize that due to dataset limitations that do not store mouse movements or selections, it is impossible to detect all forms of removing characters (for example, single character or block removing). For convenience of this study, it is considered an error each backspace occurrence 2; •AverageErrors - It is the average of the total words in the text and the number of errors during typing process; •TimeBetweenKeys - It is the average time span between the keyboard press; •RepeatedCharacterFrequence - It is the frequency of a character is repeated in the text. A repeated character is considered the same character those have been pressed immediately before and the time between them is at least 15% lower than TimeBetweenKeys. This is important to detect situations when a key is pressed for a long time, repeating the character. 9.3.2 Emotional Analysis The Emotional Analysis step is responsible for identification of each basic emotion according to Plutchik’s model [156]. This model was chosen because there are many libraries to process information according to it and lexicons which contain the basic emotions for each word. To achieve this objective, all sentences are analysed using the EmoLex [133] lexicon. For this analysis, all texts have been submitted to a preprocessing pipeline; at the end of this phase, only the relevant information remained. This pipeline was composed of n-Gram identification, tokenization, stopwords removal, part of speech tagging and named entity removal, as presented in Figure 45. 2We are aware that counting backspaces is not the more adequate way to count errors, because other reasons can lead the writer to backspace and delete characters, and also many errors are made without being detected and corrected. Anyway we feel that there is a clear relation between both. 97 CHAPTER 9. CASE STUDY 3 - IMPACT OF EMOTIONS IN USUAL TASKS Figure 45: Preprocessing pipeline Using the Stanford Core NLP toolkit [113] for these tasks, the preprocessing is divided into 3 parallel tasks. This is important because both Part of Speech Tagging and Named Entity Recognition need the text in the original format in order to identify the information. The preprocessing begins with the N-Gram identification, where a predefined set of n-grams are identified in the text and labelled to be interpreted as a single word. Later, the tokenizer splits the text in a list of words (tokens) and these tokens are syntactically analysed in Part of Speech, where the nouns, verbs, adverbs, and adjectives are identified and stored for future purposes. In parallel, the tokens identified in a predefined stopwords list are removed and the tokens in named entity process are analysed in order to identify names (persons, locations or organizations) and discard them. Later, the common tokens in these processes are stored and the emotions from each preprocessed text are identified through a process in R which queries the EmoLex lexicon [133] and identifies the basic emotions using the Syuzhet package [84]. Finally, all information is stored in a new dataset containing the opinion and preprocessed text (from the original dataset), the 6 metrics created in Meta-Information Creation step, 8 basic emotions percentages and 2 polarities identified in the Emotional Analysis step. 9.4 Data analysis The objective of this analysis is to find some evidence that emotions influence the writing process. In order to achieve this objective, some experiments were performed to relate emotions and writing patterns. 9.4.1 Emotional correlations As initial step, the values for some Plutchik’s basic emotions and defined dyad emotions [156] were calculated in order to provide more sources of information to analyse the data. To calculate these emotions, 98 9.4. DATA ANALYSIS we used the package Syuzhet in R, which analyses the text provided and returns the values of each basic emotion contained into the text, according to the EmoLex lexicon [133]. The dyad emotions were calculated according to the formula below: • Optimism = Anticipation + Joy; • Disapproval = Surprise + Sadness; • Hope = Anticipation + Trust; • Unbelief = Surprise + Disgust; • Anxiety = Anticipation + Fear; • Outrage = Surprise + Anger; • Love = Joy + Trust; • Remorse = Sadness + Disgust; • Guilt= Joy + Fear; • Delight = Joy + Surprise; • Pessimism = Sadness + Anticipation; • Curiosity = Trust + Surprise; • Awe = Fear + Surprise; • Despair = Fear + Sadness; • Pride = Anger + Joy; • Shame = Fear + Disgust; Later, the Pearson correlation (𝑟2) was applied to both each basic emotion and dyad emotions, to obtaining the correlation between the number of backspaces in the writing process3( AmountErrors as presented in subsection 9.3.1) and the emotions, according to Table 17. Table 17: Correlations between AmountErrors and emotions Emotion 𝑟2Emotion 𝑟2Emotion 𝑟2Emotion 𝑟2 Anger 0.35 Optimism 0.30 Pessimism 0.42 Trust 0.36 Anticipation 0.31 Hope 0.39 Awe 0.38 Curiosity 0.37 Disgust 0.26 Anxiety 0.52 Despair 0.38 Pride 0.38 Fear 0.38 Love 0.35 Shame 0.38 Surprise 0.19 Joy 0.23 Guilt 0.41 Disapproval 0.30 Remorse 0.31 Sadness 0.30 Delight 0.25 Unbelief 0.27 Outrage 0.34 Despite no single emotion having a strong correlation, it is possible to identify that among all emotions analysed, anxiety is the most relevant for the number of errors during typing, having a moderate correlation. 9.4.2 Machine learning predictions A machine learning analysis was applied to determine the influence of the meta-information and emotional labels on the number of errors prediction. For this purpose, 5 different scenarios were considered: • Scenario A - Only text and opinion - no meta-information neither emotional labels; • Scenario B - Only meta-information and emotional labels; 3Remember that we are using this measure to compute the errors number. 99 CHAPTER 9. CASE STUDY 3 - IMPACT OF EMOTIONS IN USUAL TASKS • Scenario C - Only meta-information; • Scenario D - Only emotional labels; • Scenario E - All dataset information - text, opinion, meta-information and emotional labels. The dataset used for both training and validation is the same created in subsection 9.3.2. In this analysis, the meta-information AverageErrors was discarded because it has strong correlation with AmountErrors , induced by AmountErrors ≈ AverageErrors ∗ TimeText . For each scenario, the following machine learning algorithms were applied: Linear Regression, SVM, Random Forest and Decision Table. All tests were performed using a 10-fold cross-validation in Weka; the correlation coefficients obtained with each algorithm between AmountErrors and the dimensions analysed in each scenario are shown in Table 18. Table 18: Algorithms correlations and their Root Mean Squared Error(RMSE) Scenario Linear Regression RMSE SVM RMSE Random Forest RMSE Decision Table RMSE Scenario A 0.171 391.28 0.347 208.62 0.429 145.36 0.321 104.78 Scenario B 0.774 99.62 0.769 103.32 0.791 96.67 0.739 106.37 Scenario C 0.777 99.14 0.770 103.08 0.780 98.66 0.739 106.37 Scenario D 0.525 134.10 0.528 137.73 0.492 141.70 0.426 143.54 Scenario E 0.320 437.12 0.696 131.79 0.586 127.88 0.591 129.18 After the tests, the best correlation coefficient for predicting the number of errors was obtained with the Random Forest algorithm for Scenario B (only meta-information and emotional labels). Once identified that the meta-information and emotional labels are an adequate to predict the number of errors, the next step was to identify the patterns for these predictions. For this purpose, all values were discretized into 4 groups and a K-Means algorithm was used to cluster the data (meta-information and emotional labels) into 4 different clusters representing respectively 39%, 17%, 23% and 21% of the information available. In a preliminary analysis, all meta-information was identified with the same value range, and for this reason, it was considered irrelevant for this objective and removed from the visualization. Also, as the purpose of this analysis is to measure the emotional influence in the AmountErrors values, the dimensions Positive and Negative were removed too. Then the relevant information remaining was grouped by AmountErrors and is presented in Table 19, where the range in AmountErros refers to the number of errors identified, while the range for each emotion refers to the number of words containing the emotion in the text. Having in mind the results in Table 19, it is possible to conclude that in general, as higher the emotions are, higher is the impact on the AmountErrors number. 100 9.5. CONCLUSION Table 19: Ranges of AmountErrors per emotions Emotions AmountErrors Anger Anticipation Disgust Fear Joy Sadness Surprise Trust 0.0-204.5 2.5-3.5 0.5-1.5 0.5-1.5 0.0-4.5 0.0-0.5 0.0-1.5 0.0-0.5 2.5-4.5 204.5-256.5 3.5-5.5 1.5-2.5 0.0-0.5 5.5-7.5 1.5-2.5 2.5-3.5 0.5-1.5 4.5-∞ 256.5-340 3.5-5.5 0.5-1.5 1.5-2.5 5.5-7.5 0.5-1.5 3.5-∞0.0-1 2.5-4.5 340-∞5.5-∞2.5-∞2.5-∞7.5-∞2.5-∞3.5-∞2.5-∞4.5-∞ 9.5 Conclusion A typist certainly will have fewer errors than a normal person when typing. However, even this typist will do more mistakes if he is, for instance, anxious or feeling guilty. As a first step in a research direction we want to further explore — the sentiment analysis in different tasks to understand the effect of the worker’s emotional state on his performance, to reduce mistakes — this paper presents a combination of lexicon-based and machine learning approaches to correlate the number of typing errors based on the emotional labels and metrics associated with the text creation (text first typing/editing). That model can be used to predict errors based on the information of the emotional state; in this way we will have a rigorous criterion to recommend people to stop doing some task under some personal states to avoid dangerous faults. Everyone has particular characteristics of expressing himself and these personal characteristics can of course influence that prediction. Maybe on account of that, the study results so far obtained were a bit surprising, and the measured influence of emotions on users tendency to make mistakes is moderate (we were expecting bigger values). In our tests, the best approaches for predicting errors based on human behaviour were obtained using emotional information (emotions inferred from the text lexical analysis)and meta-information (metrics evaluated based on the text creation process) collected during text typing. Clustering the data revealed how the emotions can affect the number of errors. It is a promising result. 101 10 Case study 4 - Determining emotional profiles based in textual analysis Probably, one of the well known and used proverbs is: “Birds of a feather, flock together”. However, what does it mean? In general meaning, it refers that people with common traits, interests and tastes tend to associate and relate with each other, in the same way as birds of the same species flock together. It can be observed in several different human behaviours, where people with common personalities tend to relate to each other. Psychodynamic researchers claim that personality structure is set in childhood. For [175], the individual personality is formed around 2 or 3 years old, mostly through child training practices. [55] argues that when the Oedipal complex is resolved, all basic structures of personality - the id, ego, and superego - are fully developed in opposition to [42] and [108], which believe that personality continues to develop later in life. Sharing the same vision of Erikson and Loevinger, the motivational speaker [166] claimed that “you are the average of the five people you spend the most time with”. Through social media usage - in general microblogging - people (authors) can express their opinion, desires and thoughts to a broad audience - from friends to unknown followers - keeping proximity despite physical distance. However, is this audience interested in the author’s posts because they share the same sentiment, mood or emotions? Also, since software has no childhood, neither id, ego, and superego, is it possible to create an emotional profile based on existing ones, enabling the software “learn” how to have a personality? In this case study, we present an approach for emotional profile creation based on existent emotional profiles, using emotion-based analysis to determine the proximity of the author’s emotional and grammatical writing style with their audience on microblogging. 10.1 Emotion theories In the literature, there are several models that attempt to explain the emergence of emotions and their associated behaviours. The main research theories here surveyed to serve as background to our analytical work are discrete, dimensional and appraisal theories. 102 10.2. RELATED WORK Discrete emotional theories propose the existence of basic emotions that are universally displayed and recognized, grouped into categories and independent. An example of discrete emotional theory is proposed by [157], where all sentiment is composed of a set of 8 basic emotions ( anger , anticipation , disgust , fear , joy , sadness , surprise and trust ). On the other hand, dimensional theories characterize emotions regarding two or three dimensions, generally “arousal” and “valence.” Valence is related to a positive or negative evaluation and is associated with the feeling state of pleasure (vs displeasure). Arousal reflects the general degree of intensity felt. However, using this two-dimensional is confusing to different emotions that share the same values of valence and arousal, as anger and fear . For this reason, it is common to add a third dimension to support this differentiation, as intensity. According to [101] “the third view emphasises the distinct component of emotions, and is often termed the componential view.” Emotional-cognitive psychologists focus their studies mainly on the appraisal process. According to [179], the central idea is that emotions are triggered and differentiated by subjective analysis of an event, situation or object. For instance, Bill and Mike are watching a football game where their teams are playing. Bill’s favourite team wins (event). Mike’s appraisal is that an undesirable event happened. For Bill, the appraisal is that the event is desirable. So, the same event has produced opposite appraisals. In fact, emotions are triggered by the personal interpretation of the annoying or cheerful aspects of an event, the appraisal. 10.2 Related work Due to the extensive usage, sentiment analysis on microblogs can be considered an opinion-rich resource and has been gaining popularity and attracting researchers from other areas to correlate information about specific events (e.g. Christmas, football matches, elections) with the sentiment contained in posts. To perform sentiment analysis on microblogging, according to [150], a straightforward approach is to exploit traditional sentiment analysis models. However, such methods are inefficient because they ignore some unique characteristics of microblog’s data, as emoticons representations. Moreover, there are lots of colloquial terms, abbreviations and misspelt words used in microblogs which leads to heavy preprocessing tasks in order to identify its occurrences and “translate” them to a canonical form to be interpreted correctly. Due to such properties, several models have been developed especially for microblogs sentiment analysis recently. An example of correlations between events and sentiments was proposed by [75], which measures the sentiments on Twitter during a period and compares the correlation between sentiments contained in the text and significant events, including the stock market, elections and Thanksgiving. Also, [91] examined a dataset containing tweets about Michael Jackson’s death in order to analyse how emotion is expressed on Twitter. [141] have analysed the sentiments about politicians, detecting a strong correlation between the aggregated sentiment and manually collected poll ratings. 103 CHAPTER 10. CASE STUDY 4 - DETERMINING EMOTIONAL PROFILES BASED IN TEXTUAL ANALYSIS last 1000 tweets for the same audiences used before, in order to identify the similarity between their texts. Table 28: Similarities between authors and audiences Audiences Author (1) (2) (3) (4) (5) (6) Mean Standard Deviation Elon Musk (1) 0,681% 0,605% 0,629% 0,650% 0,542% 0,536% 0,607% 0,058% Donald Trump (2) 0,728% 1,068% 0,840% 0,833% 0,893% 0,687% 0,842% 0,135% Katy Perry (3) 0,712% 0,613% 0,999% 0,811% 0,623% 1,096% 0,809% 0,201% Alan Shipnuck (4) 0,553% 0,531% 0,738% 0,664% 0,557% 0,573% 0,603% 0,081% Michele Dauber (5) 0,739% 0,745% 0,731% 0,824% 0,926% 0,672% 0,773% 0,089% Floyd Maywheather (6) 0,605% 0,542% 0,846% 0,566% 0,473% 1,430% 0,744% 0,360% Before analysing the texts, they were preprocessed using the same pipeline described in Section 10.3.1 in order to keep the texts in the same structure in for the different analysis. Using the Jaccard distance as metric to analyse the similarity among the texts; initially, we analysed the similarity between each author’s texts and the texts of all audiences, in order to identify which audience is more similar to the author. Once identified the text’s similarity percentage, we calculated the average of each audience, according to the formula: Í𝑛 𝑖=1𝑆𝑀1𝑖+Í𝑛 𝑖=1𝑆𝑀2𝑖+Í𝑛 𝑖=1𝑆𝑀3𝑖+Í𝑛 𝑖=1𝑆𝑀4𝑖+Í𝑛 𝑖=1𝑆𝑀5𝑖 𝑛 Later, for each author, we calculated the mean and standard deviation for the similarity between him and the audiences, as presented in Table 28. This information allowed to identify that, in most cases, the highest similarity average was between the author and his audience. Moreover, the cases where it did not occur, the similarities values of the author’s audience added with standard deviation indicates that the audience’s value is close to the highest value. 10.4 Conclusion This paper presented an analysis of the emotional and grammatical writing styles similarity from authors and their most frequent audiences on microblogs. This approach used lexicon-based techniques to explore the emotions contained in tweets and NLP techniques to identify grammatical excerpts. Once the emotional and grammatical writing styles have very high values, indicating a strong correlation between authors and audiences, it is possible to conclude that both authors and audiences share the same writing style. Moreover, the correlation between authors emotions and the most frequent audiences emotions exhibited in Fig. 47 is high, and as the size of this audience increases, the lower the correlation becomes, confirming Jim Rohn’s claiming. This is a crucial issue because it enables the possibility of chatbots to create an emotional profile based on the interactions received from people or even other systems, creating an identity and interacting with the end user in smooth communication. Combining Generative Adversarial Networks (GANs) and emotional profiles, a new generation of chatbots can create its own “personality” and generate textual responses that fit its emotional profile. 110 11 Case Study 5 - Prediction of election results according to emotional analysis It is undeniable that social media have changed how people contact to each other, enabling them to maintain relationships that previously would be difficult to maintain for various reasons, such as distance, the passage of time, and misunderstandings. Barack Obama used social media as the main platform of his presidential campaign in the United States in 2008, and since then, it is well established that social media created a strong influence on voters’ decisions in that election and many others. Facebook and Twitter are now considered essential tools for any political campaign, along with other social media platforms that have been created since then. The influence of social media increases when candidates with low funding levels and low levels of traditional media exposure try to defeat adversaries with more resources. Social media allow the candidates to post their political platforms as well as inflammatory posts against their opponents. In many cases, political candidates use social media mainly to carry provocative attacks against their opponents. Their followers, in turn, use social media to broadcast their reactions of anger and satisfaction in posts that can be shared thousands of times. In electoral campaigns highly marked by their massive presence on social networks - as was the Brazilian presidential election in 2018 – by using Natural Language Processing (NLP) and Machine Learning (ML) it is possible to identify what voters think and feel about the candidates and their proposals for the various areas of the government. Thus, some interesting research question that arises are: ”How do the emotions about each candidate influence the electoral decision?”and ”Is it possible to predict the result of an election only by knowing what voters “feel” about a candidate?” In this case study, we present an approach to predict the results of the election. As a case study, we collected messages from social media about the Brazilian presidential election of 2018, where we used Sentiment Analysis, NLP and ML to identify which emotions dominated the electorate and their correlations with the number of messages about the candidates and finally predict the results. 111 CHAPTER 11. CASE STUDY 5 - PREDICTION OF ELECTION RESULTS ACCORDING TO EMOTIONAL ANALYSIS 11.1 Related work The analysis of emotions on Twitter to explain elections is not a new approach. Several researchers have already done work in this area, each with different approaches and results. [201] developed a system to analyze the tweets about presidential candidates in the 2012 U.S. election as expressed on Twitter. His approach analyzes the text’s polarities (positive, neutral or negative), the volume of posts and the word most used. This is the same approach used by [72], that trained a Convolutional Neural Network using an annotated lexicon - Sentiment140 - to detect the text’s polarities. These approaches do not go deeper on the reasons of polarities, and thus, does not identify which sentiments influence the voters’ decision, which is the objective of our work. [195] has developed an analysis of tweets for the German elections which, similar to Wang’s work, used the polarities of phrases to analyze the messages. However, unlike the previous work, Tumasjan’s study relates the volume of messages to the final result of the election. This approach is highly influenced by financial questions (as richer the candidate is, more publicity about him can be posted in social media), and for this reason, we did not consider trustworthy. [13] used this same approach, using the data from the Irish general election of 2011, but, different than Tumasjan, he has expanded the model for training by using polls as parameters for training the predictions, which has inspired our work in the training dataset creation. While the existing works focused only on the aspect of the text’s polarities, the work of [121] inspired our decision to consider the basic emotions contained in the text as a factor of influence in the decision of the voter, and use it to predict results. 11.2 Dataset creation Initially, to draw from the data a general idea of the Brazilian voter, it would be necessary to generalize the emotional profile of these voters, regardless of their region. The idea is that, according to the emotions contained in the texts, it would be possible to determine relevant information about the characteristics of the Brazilian voters. Thus, a pipeline was created for dataset creation, as presented in Fig. 48. This pipeline begins with a collection of messages about the candidates. For this purpose, we collected tweets from 145 cities in Brazil, with each state being represented by at least its four largest cities, and delimiting a radius of 30 km for each city. The option for geolocated tweets is to avoid posts from countries different than Brazil, where the author probably would be not able to vote in Brazilian’s election. To select what would be considered relevant or not, we defined that only the tweets containing the main candidates’ names would be collected. Tweets containing two or more candidates’ names were analyzed for all candidates mentioned in the text. Moreover, we considered relevant only tweets - not retweets. This decision was inspired by the necessity to avoid viral posts or the ones from digital influencers. In other words, we wanted to know the opinion from the message’s author about a candidate, not the opinion of an author who the author likes. 112 11.2. DATASET CREATION Figure 48: Dataset’s creation pipeline For gathering the tweets, we developed a script in Python using the official API provided by Twitter, and collected all geolocated messages from the 145 cities mentioned earlier in the period from May 2018 to October 2018, which contained at least one of the following names in their texts: “Bolsonaro”, “Ciro Gomes”, “Marina Silva”, “Alckmin”, “Amoêdo”, “Álvaro Dias”, “Boulos”, “Meirelles”and “Haddad”, divided in two groups: first round and second round. 11.2.1 Out of scope After an initial analysis of the messages collected, we decided not to handle the ambiguity in the texts during the analysis. The reason for choosing not to address this problem was justified by the tiny amount of messages that could lead to erroneous interpretations. Since it was a mandatory requirement for the messages to contain the name of at least one candidate, the nature of the Twitter messages - which limits each post by 280 characters - already considerably inhibited this type of problem. Furthermore, this initial analysis showed that the existence of the candidate’s name in the text made the context of the message as political and egalitarian in the emotional sense, as derogatory nicknames for the leading candidate candidates bring negative emotions. So, we avoided that exacerbated emotional expressions of some candidates affect others. 11.2.2 Lexicon expansion When working with sentiment analysis, a common approach is to use a dictionary-based algorithm to identify the emotional words in texts. However, according to Feldman [49], “the main disadvantage of any dictionary-based algorithm is that the acquired lexicon is domain-independent and hence does not capture the specific peculiarities of any specific domain.”Thus, it is essential to know some particularities about the domain which the texts represent, to avoid misunderstandings and enable analysts to make a better classification of the sentiments contained in the texts. With this problem in mind, we adapted the solution presented by Martins [119], where the texts were represented by a vector of words and these vectors were used to analyze the similarities of the words 113 CHAPTER 11. CASE STUDY 5 - PREDICTION OF ELECTION RESULTS ACCORDING TO EMOTIONAL ANALYSIS contained in an emotional lexicon, to expand it. A major concern when creating these vectors was about the polarization among the candidates. Our idea was that the texts about a candidate do not influence the emotional words of other candidates. For this reason, we adopted the strategy of creating a personal emotional lexicon for each candidate and thus analyzing the candidate’s sentiments individually according to their respective emotional lexicon. Figure 49: Lexicon expansion process An overview of the entire process of lexicon expansion is presented in Fig. 49. 11.2.2.1 Word Vectors The process of lexicon expansion begins with grouping all tweets collected by the candidate’s name, removing their stopwords and creating the word vectors. For this purpose, we developed a script in Python using the Word2Vec algorithm, presented by Mikolov [128], having as parameters: size of 50; window 5 and trained for 200 epochs. Later, the emotional lexicon is introduced, to feed the word vectors with emotional seed words. For this step, we used the EmoLex lexicon [133] to provide the emotional words for the word vectors. The reason for this lexicon’s choice is that it provides emotional words in Portuguese and also contains indications for polarities (positive and negative) and annotations for the eight basic emotions according to Plutchik’s theory [157], which defines sentiments as anger, anticipation, disgust, fear, joy, sadness, surprise and trust . Each word in the emotional lexicon was analyzed in the word vector of each candidate, to identify similarities. For all similar words found with a value higher than 0.7, these words inherited the emotional values from the lexicon’s word and - recursively - were analyzed in the word vector to search for new similarities. For each similar word found in the word vectors, we added this word in a “new emotional lexicon”containing the original emotional lexicon and their respective similarities and emotional annotations according to the word vectors. An important issue to emphasize in this approach is that when finishing the creation of this lexicon, we have a contextual emotional lexicon, because contextual words and its similarities were used in its creation. This context is provided because all messages contain at least one candidate’s names. Thus, the context of the lexicon is about politics. 114 11.2. DATASET CREATION 11.2.2.2 Results When the lexicon expansion process was finished, the result was a set of personal lexicons about politics, containing the basic lexicon data increased by similarities found in the text and the synonyms of the words. The characteristics of each personal lexicon are presented in Table 29. Due to space limitation, Table 29 only presents the top 5 most known politicians, but in our study, all politicians that were candidate were considered in this analysis. Table 29: Characteristics of the personal lexicon created Lexicon Words Anger Anticipation Disgust Fear Joy Sadness Surprise Trust Positive Negative Original Lexicon 13911 8,85% 5,92% 7,48% 10,44% 4,88% 8,46% 3,76% 8,72% 16,36% 23,47% Geraldo Alckmin 15251 8,89% 5,91% 7,50% 10,39% 4,82% 8,45% 3,79% 9,14% 16,56% 23,45% Jair Bolsonaro 22082 9,16% 5,73% 7,63% 10,50% 5,01% 9,24% 3,38% 10,10% 17,49% 24,11% Ciro Gomes 15316 8,95% 6,00% 7,47% 10,31% 4,99% 8,65% 3,77% 9,11% 16,78% 23,50% Fernando Haddad 18264 9,27% 5,70% 7,47% 10,65% 4,87% 8,67% 3,46% 9,19% 17,26% 23,37% Marina Silva 14842 8,76% 5,88% 7,40% 10,37% 4,85% 8,44% 3,76% 8,79% 16,38% 23,32% 11.2.3 Preprocessing After creating a personal lexicon for each candidate, the next step consisted of creating a text preprocessing pipeline to remove unnecessary information from the texts. This pipeline, as presented in Fig. 50, begins with tokenization, which converts the texts into a list of single words, or tokens . Then, the process is divided into two parallel tasks: Part of Speech Tagging (POS-T) and Stopwords Removal. The POS-T process is responsible for identifying grammatical pieces of information for each word in the text, such as adjectives, adverbs and nouns, while the Stopword Removal removes any occurrence in the text of a defined word or list of words. This strategy of paralleling POS-T and Stopwords removal was used because POS-T needs the text in the original format, to classify the words in their respective grammatical categories correctly. Figure 50: Preprocessing tasks Concerning text cleaning, in POS-T, every word in a grammatical category other than noun, verb, adverb or adjective is discarded. This is important because only these grammatical categories carry emotional information that can be used in further steps. So, more formally, the tokenization process 115 CHAPTER 11. CASE STUDY 5 - PREDICTION OF ELECTION RESULTS ACCORDING TO EMOTIONAL ANALYSIS converts the original text 𝐷in a set of tokens 𝑇={𝑡1, 𝑡2, ..., 𝑡𝑛}where each element contained in 𝑇 is part of the original document D. These tokens will feed the POS-T, which will label each token with semantic information. Finally all nouns, verbs, adverbs and adjectives will be collected in a set P, where 𝑃𝑡={𝑝(𝑡,1), 𝑝(𝑡,2), ..., 𝑝(𝑡,𝑘)}and 0 ≤k≤n and 𝑃𝑡⊂𝑇. The Stopwords list is a manual and predefined set 𝑆𝑊 ={𝑠𝑤1, 𝑠𝑤2, ...𝑠𝑤𝑦}of words, intended to avoid the analysis of common and irrelevant words. There are many examples of Stopwords lists on the internet and in libraries for Natural Language Processing (NLP). In our approach, after the Stopwords Removing process, the result list is a set 𝑁=𝑇−𝑆𝑊 . After the parallel preprocessing tasks finish, the result document 𝑆𝑇 must contain a set of words where 𝑆𝑇 =𝑃∩𝑁. Later, in 𝐿𝑀 a lemmatizer process reduces the words to their lemma. This step is important because allows considering all inflected words as only one, producing the set of preprocessed texts 𝑃𝑅 = {𝐿𝑀 (𝑆𝑇1), 𝐿𝑀(𝑆𝑇2), ..., 𝐿𝑀(𝑆𝑇𝑧)}. The final result of this pipeline is a new emotional lexicon that considers the similarities of words used in expressions that cite the candidates, and their synonyms, and that is a personal representation of the sentiments about each candidate. For this preprocessing step, we developed a Python module using Spacy1for automatizing the Tokenization, POS-T, Stopwords Removal and Lemmatization processes. We chose to use this toolkit in the development because it provides support for Brazilian Portuguese in all steps described earlier. 11.2.4 Sentiment Analysis Once we created new personal lexicons for all candidates, the next step in the dataset creation was to analyze the emotions contained in the texts about each candidate. For this purpose, we developed a tool that counts the frequency of each emotional word in a text. The result of this analysis is the final dataset, containing the emotional analysis of each Twitter message for each candidate, on a scale from 0 to 100 for each Plutchik’s primary emotion. This approach - a bag-of-word approach - was adopted because we intended to identify which emotions were more relevant to the voters when deciding their candidate, besides to generate a “candidate fingerprint”through the words used to describe them. Moreover, the absence of emotional corpora about politics in Portuguese restricted the possibility of using other techniques to identify the emotions in our texts. 11.3 Data analysis Once the dataset was created, we attempted to use data analysis to identify some particularities about the data, and how these particularities could explain the results of the elections. We used several techniques 1https://spacy.io/ 116 11.3. DATA ANALYSIS to identify correlations between the results of the elections and the data analyzed. Once we identified the emotions that influenced the first-round results and how they did so, the next objective was to predict the results for the second round. To reach this objective, we decided to use an approach based on machine learning. The goal of this approach was to train a model that could accurately predict the percentage of votes for each candidate based on the emotions previously identified, the percentage of votes cast for each candidate in the first round, and the emotions contained in tweets on the day of the second-round vote. 11.3.1 Training dataset During the creation of a dataset for training the model, an important issue was identified: how to “translate”the emotions into a percentage of votes. Once the first round results were known, the relationship between candidates’ emotional profiles and the percentage of votes cast on that day could also be determined. However, it was necessary to obtain many more examples to train a model. To bypass this obstacle, we chose to use the public information on electoral polls available from public institutes. The chosen institutes were: Instituto Brasileiro de Opinião e Pesquisa (Ibope) 2, Instituto Datafolha 3, Vox Populi 4and Paraná Pesquisas 5which are the most important polling institutes in Brazil. To create the training dataset, we collected the voting intention results of 42 polls for candidates that we had in the dataset, which resulted in 324 examples for training, with 107,039.52 tweets analyzed. Later, knowing the period of each poll, we analyzed the average of each basic emotion for each candidate in the same period from the database. We then transferred these emotions to a new file, indicating the candidate’s name, the number of candidates in the poll, period, emotions, and institute. Despite the number of Tweets messages of each candidate are different, this new dataset contains each candidate’s grouped emotions during the period of each poll. Thus, all candidates had the same number of registers in the dataset. This approach ensured that the most cited candidates in messages did not bias the dataset. 11.3.2 Predicting results After creating the training dataset, the next step was to train a model for predicting the results for the second round. For this purpose, we analyzed five different machine learning algorithms, to identify the best correlation between data and results. In all cases, the dataset was separated 70% for training and 30% for testing, using the Mean Absolute Error (MAE) as errors standard measure to have a comparison basis between traditional pools and twitter Sentiment Analysis. 2http://www.ibope.com.br 3http://datafolha.folha.uol.com.br/ 4http://www.voxpopuli.com.br 5http://www.paranapesquisas.com.br/ 117 CHAPTER 11. CASE STUDY 5 - PREDICTION OF ELECTION RESULTS ACCORDING TO EMOTIONAL ANALYSIS The algorithms (using implementations for R and all tuned for the best fit) chosen for the analysis and their results after training the models are presented in Table 30. Table 30: Algorithms evaluation Algorithm Correlation MAE Simple Linear Regression 0,2639 10,6302 SVM 0,3677 9,3608 Decision Table 0,5385 9,226 Extreme Gradient Boost 0,9096 0,9787 Random Forest 0,8088 6,322 The best result was obtained by an Extreme Gradient Boost algorithm, which had a correlation of 0,9096 (very strong correlation) between the results in the polls and the emotions in the same period, and a mean average error of 0,9787. Once the model was created, the goal was to predict the percentage of votes for each candidate in the second round. In our experiment, we decided to predict the values based only on the emotions expressed on the day of second-round voting until 17:00. This time limitation is because voters could vote only until 17:00. Voters made their decisions based on their emotions during the voting process. Therefore, emotions that were expressed before the second-round election day were not crucial in this analysis. After collecting the tweets for each second-round candidate - Jair Bolsonaro and Fernando Haddad - on October 20 and analyzing tweets about them using the same process presented in section 11.2.3, we got the values presented in Table 31. Table 31: Emotions in second round’s day Candidate Anger Anticipation Disgust Fear Joy Sadness Surprise Trust Jair Bolsonaro 13,14% 11,14% 8,18% 12,71% 12,55% 14,80% 6,97% 20,50% Fernando Haddad 12,39% 13,50% 6,41% 10,67% 14,95% 14,22% 7,57% 20,29% When applying these values to the model created previously, we got a prediction of 54,58% for Jair Bolsonaro and 43,98% for Fernando Haddad and 0,9787% of MAE that can be considered as a correct prevision because the official results for the second round were 55,15% for Jair Bolsonaro and 44,87% for Fernando Haddad, whose values are in the accepted error margin. 11.4 Conclusion Social media have changed the way people interact and express their thoughts about everything. Because of this changing reality and the vast quantity of data available, sentiment analysis is becoming a powerful, fast, and relatively inexpensive tool that is extremely useful for analyzing many different types of scenarios and predicting future results. 118 11.4. CONCLUSION Furthermore, although there have been many studies about the influence of social media on elections, there are not approaches using sentiment analysis to identify voters’ emotions and predict future election results, while taking into account the results of previous studies. The correlation between voters’ emotions and the percentage of votes shows how vital is to know the audience’s sentiments to plan effective strategies for interacting with them. Moreover, the very strong correlations that we found between the basic emotions and poll results’, as well our model’s successful prediction of the second-round results of Brazilians elections, strongly suggest that sentiment analysis can become a viable and reliable alternative to traditional opinion polls, with the advantages of being much faster and less expensive. However, it is important to emphasize that there are no studies yet published about what the acceptable threshold is for replacing traditional polls with sentiment analysis. Also, it has not yet been established how many tweets must be analysed to replace a traditional opinion poll with a sufficient degree of certainty. 119 CHAPTER 12. CASE STUDY 6 - DEPRESSION CLASSIFICATION BASED SOCIAL MEDIA ANALYSIS Figure 54: Outliers identification Table 33: Correlation between depressive status and intensities Intensities Anger Fear Joy Sadness 0.49 0.49 -0.43 0.41 12.3.2 Clustering analysis The objective of the Clustering Analysis is to perform data transformations to understand if and how the data can be grouped. To achieve this, the initial step was to transform the 12-dimension dataset into a 2-dimension dataset for visualizing the data as a scatter plot, and this would be impossible using 12- dimension data. Initially, we performed a Principal Component Analysis (PCA) to reduce the dataset (with no information about depressive classification) dimensionality. The PCA algorithm identified that the most relevant dimensions in the dataset were Fear and Disgust , which can contain 72.33% of the information. 126 12.3. DATA ANALYSIS Next, the dataset resultant from PCA analysis fed the KMeans algorithm used to cluster into 2 categories the data and generated a scatter plot. The resultant graphic is presented in Figure 55. Figure 55: Clusters of information This information is important because it shows that the emotional data about depressive and nondepressive can be divided into 2 distinct categories, and visually distant. 12.3.3 Machine and Deep Learning analysis The next analysis consisted in the creation of a classification model able to identify the depressive emotional profile in messages. To achieve this objective, we used the dataset created in section 12.2.4 in several Machine Learning and Deep Learning algorithms, aiming to identify the best model to classify depression. Some characteristics from the problem (depression classification) and the dataset - as few examples - were relevant in the choice of the algorithms analysed. Algorithms like LDA (Linear Discriminant Analysis) and Fisher Linear Discriminant were discarded because we believe that the problem is not represented by a linear function. Furthermore, due to the few data for training, Machine Learning algorithms based on neural networks and boosting were not considered because they tend to have a better performance when using a big amount of data. However, we analysed these network models, through a Dense Neural Network (DNN) and Convolutional Neural Network (CNN) using a Deep Learning approach. 127 CHAPTER 12. CASE STUDY 6 - DEPRESSION CLASSIFICATION BASED SOCIAL MEDIA ANALYSIS So, in our analysis were considered the following algorithms: Support Vector Machines (SVM), Random Forests, Naive Bayes, DNN and CNN. In our analysis we just considered the algorithm’s results after a tuning process, i.e., each algorithm presents its better results using the best parameters. For the Deep Learning models, we created several different model architectures to evaluate the better results. For DNN, the architecture whose got the best accuracy was a 5-tier neural model, having a dropout of 0.5 between each tier to avoid overfitting, respectively. Regarding CNN architectures, the most accurate was a 5-tier 1-D Convolutional Neural Network, using the same strategy of dropout 0.5 on each tier to avoid overfitting. The accuracy and mean squared error for each algorithm and network architecture is presented in Table 34. Table 34: Benchmark of Machine and Deep Learning algorithms Algorithm Accuracy Mean Squared Error SVM 0.984 0.126 Random Forest 0.8 0.176 Naive Bayes 0.76 0.45 DNN 0.939 0.076 CNN 0.915 0.071 These results show that some Machine Learning algorithms such as SVM and Deep Learning algorithms as DNN can identify the depressive emotional pattern with good accuracy. These results are better than the results observed in Section 12.1, reinforcing that the emotional text analysis to identify depressives can be a promising alternative to help people that are suffering silently. 12.4 Conclusion Day after day, depression is becoming an epidemic disease that affects people of different social levels, cultures and ethnicities. Due to the nature of silence, identifying people who ask for help because of this illness but cannot verbalize that request is quite complicated, and often goes unnoticed even by the person suffering from depression. The use of textual sentiment analysis can help identify the disease as it is a noninvasive method that can be continuously monitored. This is a huge help in the war against depression because it enables us to identify periods of wellness and sadness without a necessity to visit a psychologist, enabling a quick action when necessary. Despite many works in this research area, the results obtained for this approach are promising when compared to the previous efforts, principally when the accuracy of 0.984 on depression classification is presented. However, once the information was data collected from social media, we cannot discard the hypothesis of biased data, because it is not possible to assure that the authors were true when writing their posts. 128 Part IV Summary, Contributions and Future Work 129 13 Conclusion One of the main characteristics that differentiate Human Being from other species in the animal kingdom is his ability to transmit his knowledge over time. Man has always used the elements around him to express his environment, whether in drawings made in caves thousands years ago, in hieroglyphics as in ancient Egypt, or using the existing alphabets. Over time, different ways of communicating were structured and thus the different languages (such as Latin, Coptic, and Ancient Greek) emerged, which in turn evolved and gave rise to other languages, with different textual representations, such as Hindi, Kandi, Cyrillic, Latin, Greek and Arabic (among several other languages), being used today by people over all the world still with the same purpose of the caveman: to transmit knowledge. Through this knowledge transmitted over time, we were able to learn about the people’s life and their beliefs, customs, fears and joys. We learn about Homer’s Odyssey from the Greeks, about the teachings contained in the Hebrew Bible through the Dead Sea Scrolls, about the funeral rituals of the ancient Egyptians in the tombs of the pharaohs. However, when learning through reading, the reader will inevitably be subject to the point of view of the author of the text, which is somewhat dangerous when it comes to fake news. To illustrate this point of view, at the time of writing the author tries to recreate the whole scenario so that the information is more easily understood by the reader through language, using words to describe the facts, emotions and senses in which he is feeling or trying to convey. Thus, when writing a text, the author transmits his emotions in this process. Changing to the present, people have never produced so many texts as today. We are surrounded by textual information that come from websites, blogs, social media, etc. Moreover, the social relations became more physically distant - even more in pandemic times - but closer due to the use of apps such as WhatsApp. And the biggest part of these communication is done by text. So, these texts can be a valuable source of information to identify what people are feeling and classify their emotional state according to their emotions expressed in texts. Observing the basic emotions model (namely the Plutchik’s model), where each individual has a set of 8 basic and universal emotions, when identifying the frequency of use of these emotional words, it was possible to draw a emotional profile of each author. 130 13.1. RESEARCH QUESTIONS & RESULTS AND CONTRIBUTIONS Some issues were taken into account during this work in relation to the effectiveness of this emotional profile to classify the emotional state. First, it was necessary to know whether through the use of this profile it would be possible to differentiate people (in this case, using texts by their respective authors). Once the effectiveness of the emotional profile for differentiating people was verified, it was necessary to improve the model for identifying emotional words, as each author has different emotional characteristics, therefore, it would not be possible to consider that the same word had the same emotional charge for all. Then, we identified that the affinity between people is also identified through emotional profiles. Through the emotional profile, we identified that it was possible to predict people’s behaviours, such as their impacts on daily activities and decisions taken under emotional context. Finally, in the last step, we analysed a set of messages from people with depression together with a set of people who did not have the disease. Through the use of Machine Learning and all steps previously developed, a model was created capable of learning the emotional profile of a depressed person, and thus classifying their emotional state based only on text analysis. 13.1 Research questions & Results and contributions Regarding the main objective that guided this PhD research, which was to create a classifier to identify an author’s emotional state from a set of texts of his authorship, in Section 1.2 were presented some research questions that are revisited and analysed here: •Do emotional labels impact on the accuracy of classifications? Yes. The use of emotional labels in machine learning models increased the accuracy of classification, as demonstrated in the Chapters 7,10 and 12, showing that this information is useful to detect the emotional state. To achieve this conclusion, it was reproduced experiments using as baselines the results obtained from classifications with no emotional labels. Later, the experiments were redone considering the emotional labels and both results were compared; •Is there an abstract model able to represent emotional information from a personal perspective? Yes. The combination of the 8 basic emotions in a normalized distribution - the emotional profile - demonstrated that it is possible to be considered as a personal representation of the author’s emotional characteristics, being used to represent them, as demonstrated in the Chapters 7,8 and 10. This emotional profile is a set of 8 basic emotions according to Plutchik’s model, where each emotion is in a range of 0 and 1 and the sum of all 8 emotions is 1. The emotional profile represents the author’s emotional characteristics expressed in their texts and is different from an author to others. •Based on the emotional state of a person, would be possible to predict his actions or choices? 131 CHAPTER 13. CONCLUSION Yes. It was identified that people that share similar emotional profile tend to do similar errors and attitudes, as demonstrated in Chapter 9and 11. It was possible because people tend to be repetitive in their habits and routines. The study to predict actions was based on the numbers of typing errors when an author types about an emotional topic. It was considered the emotions contained in the texts and the number of errors was correlated with emotions, bringing some interesting results. The prediction of choices was studied when creating an emotional profile of each candidate in Brazilian’s elections using posts in Twitter, and making a regression to predict the percentage of votes. •Through emotional information, is there a correlation between personal writing style and emotional state? Yes. The analysis of the writing style - the emotions contained in the vocabulary used by the author and the grammatical characteristics of the text - have a high correlation with the emotional state of the author, as demonstrated in Chapter 10 and 12. This was possible because the author expresses their emotions in their texts, like a fingerprint. Through the emotional profile identified in texts, is was possible to create a classifier to identify depressive profiles - i.e. authors that have depression - and apply this classifier to identify if a new emotional profile of an author is regarding a depressive or not. For these questions, the development of this PhD research followed some steps, which were portrayed in the case studies. By studying the way in which an author usually expresses himself, it is possible to identify in his texts personality traits that reflect his way of being. In this light, we compared the words frequently used by a given author with an emotional lexicon (under the premise that the author was not masking his emotions), enabling the identification of the most frequently used emotional words. Based on the initial objectives and the achieved results, the main contribution of this PhD work is an approach to classify the emotional state based on text messages. 13.2 Publications During this PhD work, there were published some preliminary efforts which contributed to this work. The publications that outcome from this doctoral work are listed below: • Determining Emotional Profile Based on Microblogging Analysis - Proposal of an approach to define the emotional profile based on text messages. Martins R., Henriques P., Novais P. (2019) Determining Emotional Profile Based on Microblogging Analysis. In: Moura Oliveira P., Novais P., Reis, L. P. (eds) 19th EPIA Conference on Artificial Intelligence. EPIA 2019, Springer - Progress in Artificial Intelligence, Part 2, ISBN 978-3-030-30244- 3, pp 159-171, 2019. https://doi.org/10.1007/978-3-030-30244-3_14. SCImago SJR IF (2019) 0.65 (Q2 - Artificial Intelligence), Indexed: Scopus; 132 13.2. PUBLICATIONS • A sentiment analysis approach to increase authorship identification and Hate Speech Classification in Social Media Using Emotional Analysis - Proposal of an approach using emotional information to improve classifications. Martins R., Almeida J.J., Henriques P., Novais P., A sentiment analysis approach to increase authorship identification. Expert Systems, WILEY-BLACKWELL, Special Issue. ISSN 0266-4720, 2019. https://doi.org/10.1111/exsy.12469. ISI JCR (2017) IF: 1,430 (Q2 - COMPUTER SCIENCE, THEORY & METHODS). SCImago SJR (2017) IF: 0,429 (Q2 - Artificial Intelligence) Martins R., Gomes M., Almeida J. J., Novais P., Henriques P. (2018), Hate Speech Classification in Social Media Using Emotional Analysis. 7th Brazilian Conference on Intelligent Systems. BRACIS 2018, IEEE - Proceedings - 2018 Brazilian Conference on Intelligent Systems, BRACIS 2018, pp 61- 66, 2018. https://doi.org/10.1109/BRACIS.2018.00019. SCImago SJR IF (2020) 0.22, Indexed: IEEE; • Creating a social media-based personal emotional lexicon - Proposal of a tool for expansion of emotional lexicons. Martins R., Almeida J. J., Novais P., Henriques P. (2018), Creating a Social Media-based Personal Emotional Lexicon. 24th Brazilian Symposium on Multimedia and the Web. WebMedia 2018, ACM - Proceedings of the 24th Brazilian Symposium on Multimedia and the Web, pp 261-264, 2018. http://doi.acm.org/10.1145/3243082.3264668. SCImago SJR IF (2020) 0.12, Indexed: ACM; • Domain Identification Through Sentiment Analysis - Proposal of an approach to identify the context where a conversation occurs, based on emotional analysis. Martins R., Almeida J. J., Henriques P., Novais P. (2018) Domain Identification Through Sentiment Analysis. In: De La Prieta F., Omatu S., Fernández-Caballero A. (eds) 15th International Symposium on Distributed Computing and Artificial Intelligence. DCAI 2018, Springer - Advances in Intelligent Systems and Computing, volume 800, ISSN 2194-5357, pp 276-283, 2018. https://doi.org/10.1007/978- 3-319-94649-8_33. SCImago SJR IF (2018) 0.174 (Q3 - Computer Science), Indexed: Scopus; • Predicting Performance Problems Through Emotional Analysis - Proposal of an approach to predict problems based on text analysis and emotional analysis. Martins R., Almeida J. J., Henriques P., Novais P. (2018), Predicting Performance Problems Through Emotional Analysis (short paper). In: Henriques P., Leal P., Leitão A. M., Guinovart X. G. (eds) 7th Symposium on Languages, Applications and Technologies. SLATE 2018, Schloss Dagstuhl– Leibniz-Zentrum fuer Informatik, OpenAccess Series in Informatics (OASIcs), volume 62, ISBN 978- 3-95977-072-9, pp 19:1-19:9, 2018. https://doi.org/10.4230/OASIcs.SLATE.2018.19, SCImago SJR IF (2018) 0.206, Indexed: DBLP; 133 CHAPTER 13. CONCLUSION • Predicting an Election’s Outcome Using Sentiment Analysis - An approach to predict group decisions based on emotional analysis. Martins R., Almeida J. J., Henriques P., Novais P. (2020) Predicting an Election's Outcome Using Sentiment Analysis. In: Rocha A., Adeli H., Reis, L. P., Costanzo S., Orovic I., Moreira F. (eds) 8th World Conference on Information Systems and Technologies. WorldCist 2020, Springer - Advances in Intelligent Systems and Computing, volume 1159, ISBN 978-3-030-45688-7, pp 134-143, 2020. https://doi.org/10.1007/978-3-030-45688-7_14. SCImago SJR IF (2019) 0.184 (Q3 - Computer Science), Indexed: Scopus; • Identifying Depression Clues using Emotions and AI - A case of study about emotional state identification using emotional information. Martins R., Almeida J. J., Henriques P., Novais P. (2021) Identifying Depression Clues using Emotions and AI. In: Rocha A. P., Steels L., Herik H. J. (eds) 13th International Conference on Agents and Artificial Intelligence. ICAART 2021, SciTePress - Proceedings of the 13th International Conference on Agents and Artificial Intelligence, volume 2, ISBN 978-989-758-484-8, pp 1137-1143, 2021. https://doi.org/10.5220/0010332811371143. SCImago SJR IF (2020) 0.13, Indexed: Scopus; 13.3 Future Work Since the approach here proposed to identify emotional states is a totally non-invasive technique, it allows the creation of a system to monitor people at risk, such as depressive crises, panic attacks or anxiety, as it can be associated with the tools that surround people today, like smartphones, computers and personal assistants. If, on the one hand, access to information about people’s emotional state is an important tool for predicting and preventing diseases, on the other hand it opens up a huge potential for actions that are not as noble, such as targeted marketing. Therefore, it is necessary that measures are taken to prevent the collection of this information in an irregular manner, as well as its exploitation. Fortunately, there are several government initiatives on data collection and use that provide greater security in this regard. As a future work, it is possible to point out some promising directions, namely the crossing of information obtained about emotional states with laboratory analyses, in order to identify the impacts of the levels of hormones, vitamins, etc. in people’s emotional profile. Another line of research to be explored from this work is the prediction of human behaviour based on people’s comments, networks and interactions. Thus, by knowing the emotional and social aspects that influence people in their decision-making, it may be possible to predict what behaviours a population can take. 134 Bibliography [1] Z. A. Aghbari. “Array-index: a plug&search K nearest neighbors method for high-dimensional data”. In: Data & Knowledge Engineering 52.3 (2005), pp. 333–352. issn: 0169-023X. doi: https: //doi.org/10.1016/j.datak.2004.06.015. url: https://www.sciencedirect. com/science/article/pii/S0169023X04001260 (cit. on p. 24). [2] E. Agirre and G. Rigau. “Word Sense Disambiguation Using Conceptual Density”. In: Proceedings of the 16th Conference on Computational Linguistics - Volume 1 . Copenhagen, Denmark: Association for Computational Linguistics, 1996, pp. 16–22. doi: 10.3115/992628.992635. url: https://doi.org/10.3115/992628.992635 (cit. on p. 43). [3] E. Agirre and M. Stevenson. “Knowledge Sources for WSD”. In: Word Sense Disambiguation: Algorithms and Applications . Ed. by E. Agirre and P. Edmonds. Dordrecht: Springer Netherlands, 2006, pp. 217–251. isbn: 978-1-4020-4809-8. doi: 10.1007/978- 1- 4020- 4809- 8_8 (cit. on p. 42). [4] G. W. Allport and H. S. Odbert. “Trait-names: A psycho-lexical study.” In: Psychological monographs 47.1 (1936), p. i (cit. on p. 16). [5] M. J. V. Amorim and M. Bercht. “O uso da webcam na educação”. In: RENOTE 7.3 (2009), pp. 519–529 (cit. on p. 25). [6] G. Aston and L. Burnard. The BNC handbook: exploring the British National Corpus with SARA . Capstone, 1998 (cit. on p. 16). [7] J. Atserias et al. “Combining Multiple Methods for the Automatic Construction of Multilingual WordNets”. In: CoRR cmp-lg/9709003 (1997). url: http://arxiv.org/abs/cmp-lg/970 9003 (cit. on p. 43). [8] J. R. Averill. A semantic atlas of emotional concepts . American Psycholog. Ass., Journal Suppl. Abstract Service, 1975 (cit. on p. 16). 135