Grafik von Johannes Groll – https://unsplash.com/de/@followhansi

Transformation der Sentiment Analysis mit dem Emotion Text Classifier

Sentiment Analysis ist ein immer wichtigerer Teil bei der Auswertung von Nachrichten aus sozialen Netzwerken. Im folgenden Beitrag möchten wir einen Pretrained Transformer vorstellen, welcher auf diese Aufgabe ausgerichtet ist: Der Emotion Text Classifier.

Henrik Bartsch

Henrik Bartsch

Die Texte in diesem Artikel wurden teilweise mit Hilfe künstlicher Intelligenz erarbeitet und von uns korrigiert und überarbeitet. Für die Generierung wurden folgende Dienste verwendet:

Einführung

Im heutigen digitalen Zeitalter ist die Sentiment Analysis wichtiger denn je. Mit dem Aufkommen sozialer Medien und Online-Bewertungen haben Kunden mehr Möglichkeiten als je zuvor, ihre Gedanken und Meinungen über ein Unternehmen mitzuteilen. Dies kann sowohl Segen als auch Fluch sein - während positive Bewertungen und Feedback dazu beitragen können, neue Kunden zu gewinnen, können negative Bewertungen den Ruf eines Unternehmens schädigen und potenzielle Kunden abschrecken.

Hier setzt die Sentiment Analysis an. Durch die Analyse von Kundenfeedback, Social-Media-Beiträgen und anderen Formen von Textdaten können Unternehmen Trends und Muster in der Kundenstimmung erkennen. Sie können diese Informationen nutzen, um Bereiche zu identifizieren, in denen sie sich verbessern können, um auf Kundenanliegen zu reagieren und sogar um neue Chancen für Innovation und Wachstum zu erkennen. Sentiment Analysis ist jedoch nicht nur für Unternehmen nützlich. Sie kann auch in einer Vielzahl von Branchen und Anwendungsfällen eingesetzt werden, von politischen Kampagnen bis hin zum Gesundheits- und Bildungswesen. Beispielsweise können politische Kampagnen die Sentiment Analysis nutzen, um die öffentliche Meinung zu verstehen und ihre Botschaften entsprechend anzupassen. Gesundheitsdienstleister können die Sentiment Analysis nutzen, um Patientenanliegen zu identifizieren und die Patientenergebnisse zu verbessern. Pädagogen können Sentiment Analysis nutzen, um die Meinungen der Schüler zu verstehen und die Bildungsergebnisse zu verbessern.

In diesem Beitrag möchten wir die Gelegenheit nutzen, einen Pretrained Transformer vorzustellen, der für Sentiment Analysis trainiert wurde - den Emotion Text Classifier.

Allgemeine Hinweise zum Artikel

  1. Im Rahmen dieses Artikels wurden Nachrichten verwendet, um die Fähigkeiten des Modells zu veranschaulichen. Aufgrund der zur Verfügung stehenden Zeit wurden die Nachrichten nicht auf ihre inhaltliche Richtigkeit überprüft und können daher fehlerhafte Informationen enthalten.

  2. Darüber hinaus können die Texte je nach Empfänger und dessen Lebensumständen und -erfahrungen unterschiedlich eingeordnet werden. Im folgenden Artikel haben wir unsere Interpretation dargelegt, welche nicht mit den Interpretationen aller Leser:innen übereinstimmen muss.

Beschreibung der Trainingsdaten

Dieser Pretrained Transformer ist eine Modifikation des Emotion-English-DistilRoBERTa-Base Modells. 1 Die Aufgabe dieses Basismodells ist es, anhand von Texteingaben zu klassifizieren, welche Art von Emotion der Benutzer beim Schreiben der Nachricht empfunden hat. Zu diesem Zweck wurde eine Reihe von Datensätzen verwendet, wie z.B. Emotion Dataset (Elvis et al.), GoEmotion (Demszky et al.) oder MELD, (Poria et al.). 1 Damit erhalten Nutzer:innen ein robustes Modell für die Sentimentanalyse. Der Unterschied zwischen diesen beiden Transformatoren besteht darin, dass der Emotion Text Classifier zusätzlich einen weiteren Datensatz verwendet. Bei diesem Datensatz handelt es sich um EmotionLines, der Dialoge aus der Serie Friends verwendet, um die Trainingsdaten zu erweitern. 2

Verwendung des Modells

Es gibt zwei verschiedene Möglichkeiten, dieses Modell zu implementieren:

  1. Pipeline: Die Pipeline bietet uns eine besonders einfache Implementierung, die schnell zu realisieren ist. Allerdings geht hier Information verloren, da nur die am höchsten bewertete Emotion ausgegeben wird.

  2. Vollständige Definition: Bei der vollständigen Definition orientieren wir uns an einer Definition, wie wir sie bereits in anderen Beiträgen wie dem Beitrag für T5 verwendet haben. Die Definition des Modells ist hier aufwendiger, aber wir können uns den gesamten Output ansehen, anstatt ihn bereits verarbeitet zu haben. Auf diese Weise können wir die Werte für alle Emotionen einer Nachricht erhalten.

Im Folgenden zeigen wir die Anwendung des Modells beispielhaft für beide Fälle.

Bei der Analyse der Emotionen einer Nachricht kann der Kontext ein notwendiger Faktor für eine korrekte Klassifizierung sein. Wenn z.B. eine Nachricht von einer Social-Media-Seite stammt und verarbeitet werden soll, sollte diese Nachricht im Kontext des Dialogs und nicht als einzelne Nachricht analysiert werden. Im Rahmen dieses Beitrags werden der Einfachheit halber nur einzelne Nachrichten betrachtet.

Pipeline

Um die Pipeline verwenden zu können, importieren wir im ersten Schritt die Klasse pipeline in unser Skript.

emotion-text-classification.py
from transformers import pipeline

Anschließend können wir unsere Pipeline im Modus “sentiment-analysis” für das Modell “michellejieli/emotion_text_classifier” initialisieren. Der eigentliche Transformer und Tokenizer werden automatisch geladen.

emotion-text-classification.py
classifier = pipeline("sentiment-analysis", model="michellejieli/emotion_text_classifier")

Im nächsten Schritt können wir die Pipeline direkt verwenden, um eine Nachricht auf ihre assoziierten Emotionen hin zu analysieren. Dazu muss lediglich die Instanz mit der Nachricht aufgerufen werden:

emotion-text-classification.py
classifier("I love this!")

Unsere Ausgabe dieses Befehls hat nun die Form des Folgenden:

[{'label': 'joy', 'score': 0.9887555241584778}]

Vollständige Definition

Für die vollständige Definition des Modells benötigen wir einige weitere Codezeilen. Wir beginnen hier mit den Imports von transformers und torch.

emotion-text-classification.py
from transformers import AutoTokenizer, AutoModelForSequenceClassification

import torch

Anschließend müssen wir den Tokenizer und den Transformer manuell herunterladen und initialisieren. Dies geschieht mit dem folgenden Code-Snippet:

emotion-text-classification.py
tokenizer = AutoTokenizer.from_pretrained("michellejieli/emotion_text_classifier")
model = AutoModelForSequenceClassification.from_pretrained("michellejieli/emotion_text_classifier")

Der Einfachheit halber definieren wir nun eine Methode, die uns die Auswertung erleichtert. Damit können wir auch später die Auswertung in eine einzige Zeile umwandeln, wie es bei der Pipeline der Fall ist. Um unsere Logits in eine Wahrscheinlichkeitsverteilung umzuwandeln, müssen wir eine Softmax-Activation nach der Verarbeitung verwenden.

emotion-text-classification.py
def evaluate_input(input):
  logits = tokenizer(input, return_tensors='pt')
  outputs = model(**logits).logits
  activation = torch.nn.Softmax(dim=1)
  probs = activation(outputs)

  print(probs)
  print(model.config.id2label[int(probs.argmax())])

Abschließend können wir als Beispiel die gleiche Nachricht wie bei der Pipeline analysieren.

emotion-text-classification.py
evaluate_input("I love this!")

Unsere Ergebnisse sehen wie folgt aus:

tensor([[1.7848e-03, 3.8670e-04, 4.7674e-04, 9.8876e-01, 2.7721e-03, 2.7513e-04,
         5.5491e-03]], grad_fn=<SoftmaxBackward0>)
joy

Wir sehen nun, dass wir neben der wahrscheinlichsten Emotion auch die Wahrscheinlichkeiten für alle anderen Emotionen analysieren können. Dies ist besonders nützlich, wenn zwei Emotionen in einer Nachricht enthalten sind und keine eindeutige Aussage getroffen werden kann.

In diesem Fall können wir das Ergebnis einfach in einem Diagramm darstellen:

Ergebnisse des Modells

Im Folgenden möchten wir einige Beispiele darstellen, welche wir aus öffentlich zugänglichen sozialen Netzwerken extrahiert haben. Hierdurch können wir uns dem eigentlichen Anwendungsfeld - Informationen aus öffentlichen Quellen - annähern und so vergleichbare Ergebnisse liefern. Hierbei haben wir darauf geachtet, auch Nachrichten aus dem umgangssprachlichen Umfeld zu verwenden, welche beispielsweise grammatikalisch fehlerhafte oder auch unvollständige Sätze verwenden.

Aufgrund der schieren Anzahl an Nachrichten, welche in sozielen Netzwerken täglich gespostet werden, war es uns nicht immer möglich ähnlich komplexe Nachrichten für jede Emotion zu finden und somit eine Vergleichbarkeit des Modells über alle Emotionen zu erreichen. Allerdings haben wir für jede Emotion eine Reihe von Beispielen angefügt, damit sich alle Leser:innen ein Bild von der Performance des Pretrained Transformers machen können.

Wut

We are fucked aren’t we? Quelle

I will never call it X. Fuck you Elon. Quelle

Ekel

I’m so sick of this. I’ve been with my company for about a year now. Remote company which is a plus. Pay is fine. Benefits OK. But what I cannot stand are the customers. I constantly feel like an asshole because the company I work for is dropping the ball on stuff and since I’m the customer facing person I get shit on. Which yes, is sort of the job. But then some of them go complain to the board and it makes it look like I’m not doing shit. It’s super frustrating and I’m just tired of feeling dumb because I’m constantly trying to clean up the messes of other people. And I like being remote and the flexibility this job gives me. But idk I just feel like bad at my job all the time because my job depends on other people doing well. Im just sick of feeling this way. Quelle

It’s so painful. I’m working on this one app, it’s been developing over a year. It’s straight up an algorithm, not AI, but the new guys involved keep referring to it as AI. We keep explaining the difference and there isn’t one in their mind. “But it’s an AI powered engine isn’t it?” No you fucking rubes, it’s a series of calculations and simple if/then decisions made based on those calculations. Nowhere in there are we introducing AI. “But can it have a pirate voice?” Quelle

Yeah people don’t seem to realize professional programmers aren’t writing 200 line snippets. They are writing 200 line changes to a codebase of 200,000+ lines of code that it has to integrate with. I’m really tired of this joke that programmers just copy stuff of stack overflow all day and ChatGPT can do that now. The real world is not a data structures class. Quelle

Dieser Text zeigt recht gut, wie viele Emotionen in einer Meldung zusammenkommen können. Bei dieser Meldung hätte die Pipeline nur sehr ungenaue Ergebnisse geliefert, da viele Informationen nicht berücksichtigt worden wären.

Freude

Today I found out that I passed my Calc II exam with an 88%! I’m happy that I got that high of a score! Quelle

A few years ago graduation was something I would never liked to hear about because I thought I failed and would never be able to be going to finish college, now I’m in my third semester and starting my fourth semester, and my GPA is good.. I have gone so far.., Quelle

I’m so proud of myself and happy to see some money in the bank I finally earned. Back in 2023 and most of 2022 I drank very excessively, didn’t do anything productive and hid in my room practically 24/7. Near the end it got to be such a mess there were 100s of dead maggots on the floor and even on the other half of my previous bed. Now I’m sober, in a clean room, working again, and should have an apartment all to myself very soon! For the first time in a long time I’m finally able to be proud of myself, and even excited for a future that isn’t pouring another cup of whiskey lol. Quelle

We found her about 10 years ago as a stray in NYC and she’s been with us ever since. She got out of a window once and was gone for over 24 hours but she came back, almost knocking at the front door. She’s been my little special buddy for so many years now and knowing I can still scoop her up and give her kisses warms my heart. She’s got the best personality and she’s very friendly and affectionate - basically the ideal cat. Snuggles with me like a teddy bear almost every night. She’s so perfect she has a heart marking on her side! I just needed to happyrant about my wonderful kitty. Gave her some love a moment ago and wanted to share it :) Quelle

Neutral

He’s doing what tech companies have always done: rise to prominence by exploiting legal grey areas, bootstrap your product using public data and open research, then loudly call for regulation while lobbying congress to help draft the new legislation. He’s trying to pull up the ladder and freeze out future competitors. The major record labels and tech companies like Google/YouTube did something similar with the DMCA. If you want to set up a service that hosts user-submitted content, you need to implement a hideously expensive infringement detection system to avoid being sued into oblivion. Small companies can’t afford to do that so power stays consolidated with the industry giants. And who lobbied for those requirements? You guessed it. Quelle

I don’t expect much philosophical or moral consistency. I think his position is that AI is potentially dangerous and needs controls and regulation, but also he’s not willing to pump the breaks because he wants money, and someone will do it anyway. He probably knows he’s a hypocrite, but like so many hypocrites today, he doesn’t care. Quelle

This is really it. Is AI going to be able to write better screenplays than a human? Not any time in the near future. That doesn’t mean the hedge fund bros running the industry aren’t going to try to use it to fuck humans out of decent pay to improve their margins. Quelle

Trauer

I have no communication skills. I have no friends, nobody. So alone in life. Quelle

I know that the future of 3D using AI isn’t quite here yet but the truth about that technology is that it’s development is exponential meaning that the rate of its improvement will speed up so it may seem far off but in reality it might be just around the corner. I’ve put so much hard work into learning 3D in the last few years but recently as I’m seeing more and more use of AI I’m starting to feel depressed and demotivated. I know some people will say it’s a way off or there’s nothing to worry about but I genuinely have stopped learning for the past month or so because I feel so discouraged. Does anyone else feel that way? Am I being needlessly pessimistic? Quelle

Überraschung

Wow, this image looks so good! How did you do this?

Dieses Beispiel wurde von uns selbst erstellt und hat daher keine Quellenangabe.

Wow, 10 comments in and I swear no one read the article. I was just listening to NPR talk about this hearing, so this was a good read to accompany it. He’s talking about fears of how AI will devolve society in ways worse than social media. Instead of creating the tech and then realizing the harm, he’s asking the harm be evaluated now and safeguards put in place. His specific example is the upcoming 2024 election. How AI will easily manipulate people, deep fake videos and sound bites that can be created with just a few minutes of input material. Bad actors at home and abroad can easily target and influence voters with hyper targeted content. Trust in society will breakdown. And what happens if a society loses all trust in its institutions? Quelle

Angst

I’m literally speechless WTF!! It all depends on how much time and how much it costs to render these videos, and how resource intensive it is… Quelle

I thought I was safe with my two dogs, but things would go left as time progressed. My mom and brother would only be gone for the weekend and as night time came every night, there would be a certain area in my house that I would get a negative sense of dread around my moms room. my sisters room was completely off limits while she was at work, and all I had was my own room and my mothers. Down the hall around just about in front of the bathroom I would suddenly catch goosebumps for no exact reason, and I thought nothing of it. The Saturday evening things started to worsen as I prepared for bed. I kept my dogs in my room with me every time I slept because of how scary I was and I even put the food bowls in my room until day time. I usually went to the bathroom before sleep so I didn’t have to step foot in that creepy hall in the middle of the night, and that same area as I mentioned before, I didn’t just get goosebumps, but for some reason that area was awfully hot. So I rushed in my room with the tablet that has access to our security systems. I knew something was up because something about that area didn’t make sense I mean, one spot of the house felt very hot but the rest of the house had a cool breeze flowing? I checked our security cameras and just as I expected nothing was there. Sunday night, I gained a powerful urge to check these cameras and so I did. After I checked everything, I put a knife under my pillow. I have the cameras a nice sweep once again. Then something triggered me to go out for whatever reason, I don’t remember. But I couldn’t help but notice my dog not taking her eye off the door. I called her about five times and she wouldn’t move a muscle. I checked out the peephole and saw a very black figure run by. It was so dark that not the cameras or the sensor light could catch it. I grew nauseous with fear and prepared for vomit as I felt it coming. I rushed to my room and tried to dial 911 but I couldn’t, my shivering was severe. Before I knew it, the thing left and I explained it the best I can to my mom but she quickly dismissed it and told me to stop playing with her. My brother reacted the same as expected. But I never stayed by myself ever again. Quelle

Der Text wurde der Einfachheit halber leicht gekürzt, ohne besonders relevante Informationen wegzulassen.

Fehlklassifikationen

Nachdem wir eine Reihe von Texten vorgestellt haben, die gut in verschiedene Bereiche der Emotionen eingeordnet werden konnten, wollen wir uns nun mit einer Reihe von Beispielen befassen, bei denen die Einordnung falsch oder ungenau war. Wir beginnen mit dem folgenden Text und seiner Analyse:

How is a young designer supposed to build own brand and portfolio when their work is just burried under pile of ai generated images? Fine, use ai to speed up some parts of workflow but it still will never be as fast and as efficient as people spamming midjourney images burring your artwork. Quelle

Aufgrund der Länge des Textes handelt es sich hier um einen Auszug.

In diesem Text wurde “Neutral” als vorherrschende Emotion identifiziert. Unserer Meinung nach ist dieser Text jedoch viel stärker von Ärger und Ekel durchzogen, als dies bei Neutral der Fall ist.

Neben diesem Beispiel haben wir ein zweites, eindeutigeres Beispiel vorbereitet.

When I was 5 yrs old, my family and I were living in an apartment which we didn’t find out until we moved that the complex was known to be haunted. The four of us shared a 1 bed and 1 bath. My sister and slept between our parents on one bed. This bed faced the door that we kept wide open. So, on this particular night, I had randomly woke up in the middle of the night. Something in me told to look at the door and there he was, standing still at the door, unmoving. This figure was a tall man in a vintage diving suit with the bowl shaped helmet that encased the head, but I realized he had no head… The circular windows in the helmet where the divers head could be seen, were completely see through. I could see the hallway behind him rather than a silhouette of a head. This freaked me out so much that I hid under my covers but daringly took another peek. He was still there in the exact same position. I looked at the door a third time to make sure I wasn’t crazy or something of my imagination. I was frozen with so much fear that I couldn’t even wake up my parents. I stayed beneath the covers until the sun came up. I couldn’t sleep a wink. That is one of my vivid ghost encounters that will forever haunt me. I have slept with my door completely shut ever since. Quelle

In diesem Text wird die Emotion “Angst” unseres Erachtens deutlich zu schwach bewertet, während hier “neutral” als dominierende Emotion angegeben wird.

Zusammenfassende Ergebnisse

Die hier gezeigten Beispiele erlauben eine Einschätzung der Qualität der Ergebnisse. Unserer Meinung nach sind die hier gezeigten Ergebnisse realistisch und repräsentativ, das Modell hat auch keine Probleme mit Umgangssprache oder unvollständigen Sätzen.

Wir haben auch einige Fehler im Modell aufgezeigt. Es scheint, dass die Emotion “neutral” in verschiedenen Texten als zu hoch eingestuft wurde. Dies verzerrt die Ergebnisse im Allgemeinen leicht, aber in einigen Texten können wir auch eine falsche Klassifizierung erkennen. Dies sollte bei der Verwendung des Pretrained Transformers berücksichtigt werden.

Unserer Meinung nach stellt dieses Modell eine einfache Methode dar, um mit wenig Aufwand möglichst repräsentative Aussagen über die Emotionen von Textverfasser:innen treffen zu können.

TL;DR

In diesem Beitrag haben wir den Emotion Text Classifier vorgestellt - eine Verbesserung des populären Emotion-English-DistilRoBERTa-Base Modells. Hiermit können wir anhand von Textnachrichten die assoziierten Emotionen der Verfasser:innen identifizieren. Dies erleichtert es z.B. Privatpersonen und Unternehmen, ihre Dienste besser auf Feedback auszurichten, indem Feedback bereits bei der Veröffentlichung in verschiedene Emotionen eingeteilt werden kann. Das Modell erzielt im Rahmen dieser Aufgabe qualitativ gute Ergebnisse, wobei die Emotion “neutral” unseres Erachtens manchmal zu stark gewichtet wird. Abgesehen von dieser Eigenschaft scheint uns dieser Transformer eine gute Grundlage für die Analyse von Texten zu sein.

Quellen

Footnotes

  1. huggingface.co 2

  2. huggingface.co