Scoring text¶
A scoring tool reads a post and returns one or more numbers, such as a sentiment score or a toxicity score. This notebook uses two kinds of tools. A dictionary gives a score to each word and combines the scores of the words in a post. A classifier is a trained model that reads the whole post. The notebook runs each tool on hand-written sentences first and then on a table of real posts. It then shows how a cutoff turns a score into a label.
Sections: Sentiment with VADER, Score a table of posts, Moral foundations with eMFD, A classifier from Hugging Face, Toxicity with Detoxify, From scores to labels, Hosted scorers that need a key.
Packages beyond the standard library: vaderSentiment, detoxify, transformers, nltk, pandas, pyarrow, matplotlib, requests.
Install them with uv add vaderSentiment detoxify transformers nltk pandas pyarrow matplotlib requests (or pip install).
detoxify and transformers need PyTorch, which is a large package.
Colab has all of them except vaderSentiment and detoxify, and the next cell installs these two there.
Two sections download a model of about 500 MB when they first run: "A classifier from Hugging Face" and "Toxicity with Detoxify". No section needs a GPU.
# Colab does not have vaderSentiment and detoxify, so this cell installs them there.
# pip may print a note about restarting the kernel. A restart is not needed.
# The cell does nothing if the two packages are already installed.
import importlib.util
if importlib.util.find_spec("vaderSentiment") is None:
%pip install -q vaderSentiment
if importlib.util.find_spec("detoxify") is None:
%pip install -q detoxify
# This notebook uses TweetTopic, a public research dataset of 6,090 English tweets
# with topic labels. This cell downloads the file (0.9 MB) from Hugging Face into
# data/ next to this notebook, unless the file is already there. The long string
# in the address is a fixed revision of the dataset, so every run gets the same file.
import pathlib
import urllib.request
data_url = (
"https://huggingface.co/datasets/cardiffnlp/tweet_topic_multi/resolve/"
"dc65379cfc7721f579c97656a1ebdbb80aedad08/"
"tweet_topic_multi/train_all-00000-of-00001.parquet"
)
data_path = pathlib.Path("data") / "train_all-00000-of-00001.parquet"
data_path.parent.mkdir(exist_ok=True)
if not data_path.exists():
urllib.request.urlretrieve(data_url, data_path)
print(data_path, data_path.stat().st_size, "bytes")
Sentiment with VADER¶
VADER (Valence Aware Dictionary and sEntiment Reasoner) is a sentiment tool that was built for social media text. It has two parts: a dictionary, which its authors call a lexicon, and a few rules.
The lexicon gives a score to each of its entries. An entry is a word, an emoticon, or an abbreviation. The score goes from -4 for the most negative entries to 4 for the most positive ones.
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
analyzer = SentimentIntensityAnalyzer()
print(len(analyzer.lexicon), "entries in the lexicon")
for entry in ["happy", "good", "harassment", "lol", ":)", "table"]:
print(entry, analyzer.lexicon.get(entry))
happy and good have positive scores, and harassment has a negative score.
The lexicon knows the abbreviation lol and the emoticon :).
table is not in the lexicon, so it has no score.
VADER treats a word without a score as neutral.
polarity_scores scores a text.
It returns four numbers.
analyzer.polarity_scores("The food is good.")
neg, neu, and pos are the shares of the text that are negative, neutral, and positive.
They sum to 1.
compound is one summary score between -1 (most negative) and 1 (most positive).
Most analyses use compound.
The rules change the score of a lexicon word according to the words and the punctuation around it.
The three sentences below contain the same lexicon word, good.
sentences = [
"The food is good.",
"The food is GOOD!!!",
"The food is not good.",
]
for sentence in sentences:
print(analyzer.polarity_scores(sentence)["compound"], sentence)
Capital letters and exclamation marks raise the score from 0.44 to 0.67.
The word not before good turns the score negative.
These rules are simple patterns. VADER does not understand the sentence. The six sentences below are hand-written, and a person reads each of them without difficulty.
hard_sentences = [
"Great, the bus is late again.",
"I love waiting two hours for a late bus.",
"The service was anything but good.",
"The new album is fire.",
"The defense killed it tonight.",
"This song is a banger.",
]
for sentence in hard_sentences:
print(analyzer.polarity_scores(sentence)["compound"], sentence)
VADER gets all six wrong.
- The first two sentences are sarcastic. VADER sees
greatandloveand returns a positive score. anything but goodis a negation that the rules do not cover, so the score is positive.fireandkilledare praise in these sentences. The lexicon has only their literal, negative meaning.bangeris not in the lexicon, so the score is 0.
What VADER measures: how positive or negative the words of a text are, according to the ratings in its lexicon, with a correction for capital letters, punctuation, and simple negation. What it does not measure: what the author means. It misses sarcasm, new meanings of old words, and every word that is not in the lexicon.
Score a table of posts¶
From here on, the notebook also uses real posts. The file that the first cell downloaded is TweetTopic (Antypas et al., 2022), a research dataset of 6,090 English tweets from 2019 to 2021. Each tweet has labels from a list of 19 topics.
Its authors replaced the links and the account names in the text with three placeholders: {{URL}} for a link, {{USERNAME}} for a mention of an account that is not verified, and {@Name@} for a mention of a verified account, with the display name between the markers.
The file writes the apostrophe as the curly character ’.
clean_text removes the first two placeholders, keeps the display name as plain text, and replaces the curly apostrophe.
The Word Counts notebook explains why.
The cell below takes 500 random tweets and keeps the cleaned text in a new column.
random_state fixes the sample, so every run takes the same 500 tweets.
import re
import pandas as pd
df = pd.read_parquet(data_path)
def clean_text(text):
text = text.replace("{{URL}}", " ").replace("{{USERNAME}}", " ")
text = re.sub(r"\{@(.*?)@\}", r"\1", text)
return text.replace("’", "'")
sample = df.sample(500, random_state=42).reset_index(drop=True)
sample["clean"] = sample["text"].apply(clean_text)
sample.shape
Scoring a table is one call for each row. VADER is fast: 500 tweets take well under a second.
sample["vader"] = [analyzer.polarity_scores(text)["compound"] for text in sample["clean"]]
sample["vader"].describe().round(3)
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(5, 3))
ax.hist(sample["vader"], bins=41, range=(-1.025, 1.025))
ax.set_xlabel("VADER compound score")
ax.set_ylabel("Number of tweets")
ax.spines[["top", "right"]].set_visible(False)
plt.show()
print((sample["vader"] == 0).sum(), "of", len(sample), "tweets have a score of exactly 0")
The histogram has a tall bar at 0. About one tweet in five has a score of exactly 0. Almost all of these tweets contain no lexicon word. A score of 0 from a dictionary means "no evidence", and it does not mean that a person would call the tweet neutral.
The other tweets are more often positive than negative: the median score is above 0.
A common use of a dictionary score is to compare groups of posts. The score of one post is noisy, as the six sentences above show. The mean over many posts is more stable, if the errors do not all go in the same direction. The next cell computes the mean score for each topic label that has 30 tweets or more in the sample. A tweet with two labels counts in two groups.
by_label = sample.explode("label_name").groupby("label_name")["vader"].agg(["count", "mean"])
by_label[by_label["count"] >= 30].sort_values("mean").round(2)
News tweets have the lowest mean score, 0.09. Every other label in the table has a higher mean, and the tweets about arts and about daily life have the highest. This order is plausible, and it is only a first check. Before you report a difference between groups, read a sample of posts from each group with their scores.
Moral foundations with eMFD¶
A dictionary can measure other concepts than sentiment. Moral foundations theory describes moral reasoning with a short list of foundations: care, fairness, loyalty, authority, sanctity, and, in later versions, liberty. The extended Moral Foundations Dictionary (eMFD; Hopp et al., 2021) covers the first five.
Its authors asked a large group of people to read news articles and to highlight the passages that relate to one foundation. The dictionary has 3,270 words from these highlights. For each word and each foundation, it has two numbers:
- A probability, in the columns that end with
_p.care_pis the share of the times that a reader who looked for care highlighted a passage with this word, out of the times that such a reader saw the word. - A sentiment score, in the columns that end with
_sent.care_sentis the mean VADER compound score of the care passages that contain the word.
The next cell downloads the dictionary file (0.6 MB) from the repository of eMFDscore, the scoring tool of the same authors. That repository states the GNU GPL 3.0 license for non-commercial use. The long string in the address is a fixed commit, so every run gets the same file.
emfd_url = (
"https://raw.githubusercontent.com/medianeuroscience/emfdscore/"
"5523d76c25afa65a59ca00e44efe45885499b116/"
"emfdscore/dictionaries/emfd_scoring.csv"
)
emfd_path = pathlib.Path("data") / "emfd_scoring.csv"
if not emfd_path.exists():
urllib.request.urlretrieve(emfd_url, emfd_path)
emfd = pd.read_csv(emfd_path, keep_default_na=False).set_index("word")
print(emfd.shape)
emfd.loc[["killed", "unfair", "flag", "team"]].round(2).T
Each column of the table above is one word.
killed has its highest probability for care, unfair for fairness, and flag for authority.
team has low probabilities for all five foundations.
No word belongs to one foundation only.
This is the main difference from VADER, where each word has one score.
To score a post, the tool of the authors takes the words of the post that are in the dictionary and averages their rows.
The function emfd_scores does the same.
It needs tokens, so the next cell first builds the tokenize function of the Word Counts notebook: the NLTK tweet tokenizer, lowercase, no punctuation, and no stopwords.
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import TweetTokenizer
# The stopword list is a separate NLTK data package (less than 1 MB).
nltk.download("stopwords", quiet=True)
stop_words = set(stopwords.words("english"))
tokenizer = TweetTokenizer(preserve_case=False, reduce_len=True, strip_handles=True)
def normalize(tokens, remove_stopwords=True):
kept = []
for token in tokens:
if token.startswith("http"):
continue
if not any(ch.isalnum() for ch in token):
continue
if remove_stopwords and token in stop_words:
continue
kept.append(token)
return kept
def tokenize(text, remove_stopwords=True):
return normalize(tokenizer.tokenize(clean_text(text)), remove_stopwords)
def emfd_scores(text):
words = [token.lstrip("#") for token in tokenize(text)]
words = [word for word in words if word in emfd.index]
if words:
scores = emfd.loc[words].mean()
else:
scores = pd.Series(0.0, index=emfd.columns)
scores["n_words"] = len(words)
return scores
posts = {
"A": "The soldiers killed two people in the attack.",
"B": "It is unfair that the workers do not get fair pay.",
"C": "The team killed it tonight, what a game!",
}
prob_columns = ["care_p", "fairness_p", "loyalty_p", "authority_p", "sanctity_p"]
pd.DataFrame({name: emfd_scores(text) for name, text in posts.items()}).loc[prob_columns + ["n_words"]].round(2)
The three posts are hand-written. Post A has its highest score for care, and post B for fairness. The scores are small, because each is a mean of probabilities that are mostly near 0.1. Compare the scores of posts with each other, and do not read one score alone.
Post C is about a game.
It still gets a care score well above its other scores, because the dictionary has only one row for killed.
The limits are the same as for VADER: the dictionary counts words, and it does not know what the author means.
The eMFD was also built from news articles, so it lacks many words of social media posts.
Now score the 500 tweets.
moral = sample["text"].apply(emfd_scores)
print((moral["n_words"] == 0).sum(), "of", len(sample), "tweets have no word in the dictionary")
print("Median number of dictionary words in a tweet:", moral["n_words"].median())
moral[prob_columns].mean().round(3)
labeled = sample[["label_name"]].join(moral).explode("label_name")
by_label = labeled.groupby("label_name")[prob_columns].mean()
by_label["tweets"] = labeled["label_name"].value_counts()
by_label[by_label["tweets"] >= 30].sort_values("care_p", ascending=False).round(3)
A tweet has only a few dictionary words, so the score of one tweet depends on very few words. The means of the groups differ only in the second or third decimal place. With 500 tweets, differences of this size can come from chance. Use a dictionary such as the eMFD on many posts, and report the means of groups with their uncertainty.
A classifier from Hugging Face¶
A classifier is a model that was trained on pairs of a text and a label.
It reads the whole text in order, so it can use the context of a word.
Training one needs labeled data, but many trained models are public.
Hugging Face hosts thousands of them, and the transformers package downloads and runs a model by its name.
This section uses cardiffnlp/twitter-roberta-base-sentiment-latest.
Its model card says that it is a RoBERTa model that was trained on about 124 million tweets and then fine-tuned for sentiment on the TweetEval benchmark.
It returns one of three labels: negative, neutral, or positive.
The model card states the license CC BY 4.0.
The first run downloads about 500 MB.
revision fixes the version of the model, so every run uses the same weights.
The call may print a report about two unused weights and a note about a Hugging Face token.
Both can be ignored: the model is public and needs no token.
import os
from transformers import pipeline
# This model stores its weights in an older file format. Without the next line,
# transformers also downloads a converted copy of the weights (another 500 MB).
os.environ["DISABLE_SAFETENSORS_CONVERSION"] = "1"
classifier = pipeline(
"text-classification",
model="cardiffnlp/twitter-roberta-base-sentiment-latest",
revision="3216a57f2a0d9c45a2e6c20157c20c49fb4bf9c7",
)
classifier("The food is not good.")
The result is a label and a score. The score is the probability that the model gives to this label. It says how sure the model is. It does not say how strong the sentiment is.
The next cell runs the classifier on the nine hand-written sentences from the VADER section and shows the VADER score next to each result.
all_sentences = sentences + hard_sentences
pd.DataFrame({
"sentence": all_sentences,
"classifier": [result["label"] for result in classifier(all_sentences)],
"vader": [analyzer.polarity_scores(sentence)["compound"] for sentence in all_sentences],
})
The classifier agrees with VADER on the three food sentences.
It also gets five of the six hard sentences right: the first sarcastic sentence, anything but good, fire, killed it, and banger.
It learned these uses from tweets.
It still reads I love waiting two hours for a late bus. as positive.
What the classifier measures: the label that the annotators of its training data would most likely give to the text. What it does not measure: anything outside its three labels, and anything that its training data does not contain. A model that was trained on tweets from 2018 to 2021 does not know the slang of later years.
Now run it on the 500 tweets.
batch_size sends 32 tweets through the model at a time, and truncation=True cuts a text that is longer than the model can read.
On a recent laptop the cell takes a few seconds.
On a Colab CPU runtime it takes about 2 minutes.
results = classifier(sample["clean"].tolist(), batch_size=32, truncation=True)
sample["roberta"] = [result["label"] for result in results]
sample["roberta_score"] = [result["score"] for result in results]
sample["roberta"].value_counts()
Toxicity with Detoxify¶
Detoxify is an open-source Python library with trained models for toxic comment classification. It runs on your own machine, so it needs no key and has no rate limit, and a CPU is enough. The library has the Apache 2.0 license.
The models were trained on comments from Wikipedia and from news sites.
Human annotators labeled these comments, and Jigsaw released them for three Kaggle challenges.
The model unbiased is a RoBERTa model that was also trained to reduce the bias against comments that mention an identity, such as a religion or a gender.
The first run downloads the model (about 500 MB).
from detoxify import Detoxify
toxicity_model = Detoxify("unbiased")
examples = [
"Thanks for sharing, this is really helpful.",
"I disagree with this policy.",
"You are an idiot.",
"I will find you and hurt you.",
"That was a damn good game.",
]
pd.DataFrame(toxicity_model.predict(examples), index=examples).round(3)
predict takes a list of texts and returns seven scores between 0 and 1 for each text.
The five sentences are hand-written.
- The first two sentences have scores near 0. A disagreement is not toxic.
You are an idiot.has a hightoxicityscore and a highinsultscore.I will find you and hurt you.has a hightoxicityscore and a highthreatscore. The other scores say why a text is scored as toxic.That was a damn good game.is praise, and itstoxicityscore is still about 0.78. Theobscenescore shows the reason: the model reacts to the swear word.
What Detoxify measures: how likely the annotators of its training data would call the text toxic. Their instruction defined a toxic comment as a rude, disrespectful, or unreasonable comment that is somewhat likely to make you leave a discussion. What it does not measure: the intent of the author. The authors of Detoxify list this limit themselves: a text with swear words or insults is likely to get a high score, even when the tone is friendly or the author makes a joke.
Now score the 500 tweets. The function below sends 50 tweets through the model at a time, which keeps the memory use low. On a recent laptop the cell takes 5 to 10 seconds. On a Colab CPU runtime it takes about 3 minutes.
def detoxify_scores(texts, batch_size=50):
parts = []
for start in range(0, len(texts), batch_size):
parts.append(pd.DataFrame(toxicity_model.predict(texts[start:start + batch_size])))
return pd.concat(parts, ignore_index=True)
toxicity = detoxify_scores(sample["clean"].tolist())
sample["toxicity"] = toxicity["toxicity"]
toxicity.describe().round(3)
Most tweets have a toxicity score very close to 0: the median is about 0.001. A small number of tweets have a high score. This is the usual shape of toxicity scores. It is also stronger than usual in this dataset, because its authors removed tweets with abusive words before they published it.
From scores to labels¶
A score is not a label.
A statement such as "4% of the tweets are toxic" needs a rule that turns each score into toxic or not toxic.
The rule is a cutoff, and you choose it.
Start with VADER. Its documentation gives the typical cutoffs for the compound score: a text is positive at 0.05 or above, negative at -0.05 or below, and neutral in between.
def vader_label(score, cutoff=0.05):
if score >= cutoff:
return "positive"
if score <= -cutoff:
return "negative"
return "neutral"
sample["vader_label"] = sample["vader"].apply(vader_label)
sample["vader_label"].value_counts()
These cutoffs are a convention, and other values are possible. The next cell counts the labels for three cutoffs.
pd.DataFrame({
cutoff: sample["vader"].apply(vader_label, cutoff=cutoff).value_counts()
for cutoff in [0.05, 0.2, 0.5]
}).rename_axis(columns="cutoff")
With a cutoff of 0.5, the neutral group is the largest group, and the negative group has fewer than half as many tweets as with a cutoff of 0.05. The tweets did not change. Only the rule did.
Detoxify has no suggested cutoff. The next cell counts the tweets above four cutoffs.
cutoffs = [0.1, 0.2, 0.5, 0.8]
pd.DataFrame({
"tweets above": [(sample["toxicity"] > cutoff).sum() for cutoff in cutoffs],
"percent": [100 * (sample["toxicity"] > cutoff).mean() for cutoff in cutoffs],
}, index=pd.Index(cutoffs, name="cutoff"))
The share of "toxic" tweets is about nine times larger with a cutoff of 0.1 than with a cutoff of 0.8. Every one of these numbers is a correct count. They answer different questions, so a report must state the cutoff.
The counts are also small. With a cutoff of 0.5, the result depends on very few tweets, and a different sample of 500 would give a different number. When the thing that you measure is rare, score more posts.
To choose a cutoff, read the posts around it. The next cell prints the ten tweets with the highest scores. Decide for each one whether you would call it toxic.
top = sample.sort_values("toxicity", ascending=False).head(10).join(toxicity[["insult"]])
for row in top.itertuples():
print("toxicity", round(row.toxicity, 2), "insult", round(row.insult, 2))
print(row.clean)
print()
The first few tweets also have a high insult score.
Below them the scores fall quickly, and the tweets with a score between 0.2 and 0.6 are harder to judge.
You will probably disagree with the model on some of them.
A lower cutoff finds more of the toxic posts and also labels more harmless posts as toxic.
A higher cutoff does the opposite.
The way to choose is to label a sample of posts by hand and to compare your labels with the labels that each cutoff gives.
The last comparison of this section does not need hand labels. VADER and the classifier from Hugging Face both claim to measure sentiment, and both now have a label for each of the 500 tweets. The table has one row for each VADER label and one column for each label of the classifier.
agreement = pd.crosstab(sample["vader_label"], sample["roberta"])
print("The two tools give the same label to", (sample["vader_label"] == sample["roberta"]).sum(), "of", len(sample), "tweets")
agreement
The two tools give the same label to about 6 of 10 tweets. The largest group of disagreements is the tweets that VADER calls positive and the classifier calls neutral. One positive word is enough for VADER, and the classifier needs more.
The table does not say which tool is right. It says that "sentiment" from one tool is not the same measurement as "sentiment" from another tool. State which tool and which cutoff you used, and check the labels against your own hand labels on a sample of your data.
Hosted scorers that need a key¶
Some scorers do not run on your machine. You send each text to the server of a provider, and the server returns the scores. You need an account and an API key. Your posts leave your machine, so check first that the rules for your data allow this.
This section shows two hosted scorers. Each cell runs only if its key is set, and it prints a short message if not. Each example response below is copied from the documentation of the provider. It is not the output of this notebook.
Never write a key into a notebook. The cells read the key from an environment variable. To set one for the current session, run this in a new cell and paste the key into the box:
import getpass
import os
os.environ["OPENAI_API_KEY"] = getpass.getpass()
The first scorer is ModerateHatespeech, a hosted model that flags hateful and toxic comments. A key comes with an account on the site. The request is a JSON object with the key and one text.
import os
import requests
hosted_posts = [
"Thanks for sharing, this is really helpful.",
"You are an idiot.",
]
mhs_key = os.environ.get("MODERATEHATESPEECH_API_KEY")
if mhs_key is None:
print("MODERATEHATESPEECH_API_KEY is not set, so this cell was skipped.")
else:
for post in hosted_posts:
response = requests.post(
"https://api.moderatehatespeech.com/api/v1/moderate/",
json={"token": mhs_key, "text": post},
timeout=30,
)
print(post, response.json())
The documentation gives this example response:
{
"response": "Success",
"class": "flag",
"confidence": "0.993"
}
responseisSuccess, or an error message.classisflagif the model flags the text as toxic, andnormalif not.confidenceis the confidence in the class that was returned, from 0.5 to 1. It is not a toxicity score: anormaltext with a confidence of 0.99 is a text that the model is sure is harmless. The example writes the number as a string, so convert it withfloatbefore you compare it with a cutoff.
The service returns a label and makes the cutoff decision for you.
To use your own cutoff, turn the two fields into one score: the confidence for a flag text, and 1 minus the confidence for a normal text.
The request has a timeout of 30 seconds. If the service does not answer in that time, the cell stops with an error.
The second scorer is the OpenAI Moderation API.
It needs an OpenAI account and a key.
The documentation says that the endpoint is free to use.
The request can hold a list of texts.
omni-moderation-2024-09-26 is a dated version of the model.
With the name omni-moderation-latest, the provider can replace the model, and the scores of the same text can then change.
openai_key = os.environ.get("OPENAI_API_KEY")
if openai_key is None:
print("OPENAI_API_KEY is not set, so this cell was skipped.")
else:
response = requests.post(
"https://api.openai.com/v1/moderations",
headers={"Authorization": f"Bearer {openai_key}"},
json={"model": "omni-moderation-2024-09-26", "input": hosted_posts},
timeout=30,
)
for post, result in zip(hosted_posts, response.json()["results"]):
print(post)
print(" flagged:", result["flagged"])
print(" harassment score:", round(result["category_scores"]["harassment"], 3))
The documentation gives an example response for an image from a war movie. The block below is that example with most of the 13 categories left out. A request for a text returns the same fields.
{
"id": "modr-970d409ef3bef3b70c73d8232df86e7d",
"model": "omni-moderation-latest",
"results": [
{
"flagged": true,
"categories": {
"harassment": false,
"hate": false,
"violence": true
},
"category_scores": {
"harassment": 0.0011643905680426018,
"hate": 3.1999824407395835e-7,
"violence": 0.8599265510337075
},
"category_applied_input_types": {
"harassment": [],
"hate": [],
"violence": ["image"]
}
}
]
}
resultshas one entry for each input, in the same order.category_scoreshas a score between 0 and 1 for each category. The categories are harassment, hate, illicit acts, self-harm, sexual content, and violence, with subcategories.categorieshastrueorfalsefor each category, andflaggedistrueif the model classifies the input as potentially harmful. The documentation does not state the cutoffs behind these values. To use your own cutoff, work withcategory_scores.
This API has no score that is called toxicity.
The closest categories are harassment and hate.
A study that uses it must say which category it used as its measure.
The same code works with the openai package: client.moderations.create(model=..., input=...).
Both hosted scorers are classifiers, like Detoxify. Each one measures the definition of its own provider, and each one needs the same check against hand labels.