Word counts¶
The simplest way to describe a collection of posts is to count its words. This notebook splits posts into tokens, counts the tokens, reweights the counts with TF-IDF, and then finds the words that one group of posts uses more than another group.
Sections: Tokenize a post, Normalize and remove stopwords, Tokens in large language models, Count words, Plot the top words, TF-IDF by hand, TF-IDF with scikit-learn, Compare two corpora, Log-odds ratio with a prior.
Packages beyond the standard library: nltk, pandas, pyarrow, matplotlib, scikit-learn, tiktoken.
Install them with uv add nltk pandas pyarrow matplotlib scikit-learn tiktoken (or pip install).
Colab already has the first five, and the next cell installs tiktoken if it is missing.
# The section "Tokens in large language models" needs tiktoken.
# This cell installs it if it is missing.
# pip may print a note about restarting the kernel. A restart is not needed.
import importlib.util
if importlib.util.find_spec("tiktoken") is None:
%pip install -q tiktoken
# 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")
# NLTK keeps its tokenizer models and its word lists in separate data packages.
# These two calls download the packages this notebook needs (about 4 MB).
# They do nothing if the packages are already on the machine.
import nltk
nltk.download("punkt_tab", quiet=True)
nltk.download("stopwords", quiet=True)
Tokenize a post¶
A tokenizer splits a text into tokens. A token is usually a word, a number, or a punctuation mark.
The post below is hand-written. It has a mention, a word with a repeated letter, an emoticon, a hashtag, and a link.
from nltk.tokenize import word_tokenize
s = "@alice this class is soooooo cool!!! :-) #datascience https://example.com"
print(word_tokenize(s))
word_tokenize is a general tokenizer.
It was built for edited text, such as news articles.
Here it breaks the mention, the emoticon, the hashtag, and the link into pieces: @alice becomes @ and alice, and :-) becomes three tokens.
NLTK also has a tokenizer that was written for social media posts, TweetTokenizer.
from nltk.tokenize import TweetTokenizer
print(TweetTokenizer().tokenize(s))
The mention, the emoticon, the hashtag, and the link each stay in one piece.
Three options change the result.
preserve_case=False lowercases the text.
reduce_len=True shortens a letter that repeats more than three times to three letters, so soooooo and soooo become the same token.
strip_handles=True removes mentions.
tokenizer = TweetTokenizer(preserve_case=False, reduce_len=True, strip_handles=True)
tokens = tokenizer.tokenize(s)
print(tokens)
Normalize and remove stopwords¶
Counting works on normalized tokens.
Without normalization, Cool and cool count as two different words.
The tokenizer above already lowercases the text.
Two steps remain: remove the tokens that are not words, and decide what to do with stopwords.
Stopwords are very frequent words that carry little meaning on their own, such as the, is, and to.
NLTK has a list of English stopwords.
from nltk.corpus import stopwords
stop_words = set(stopwords.words("english"))
print(len(stop_words), "stopwords")
print(sorted(stop_words)[:10])
The function below drops a token in three cases.
A token that starts with http is a link.
A token with no letter and no digit is punctuation, an emoticon, or an emoji.
A token in the stopword list is a stopword.
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
normalize(tokens)
Four tokens are left: class, sooo, cool, and #datascience.
Each of these steps is a choice, and each one can be wrong for a given question.
A study of pronouns must keep the stopwords, because i, we, and they are in the list.
A study of emotion must keep the emoticons and the emoji.
Look at what a step removes before you apply it to all of your posts.
normalize(tokens, remove_stopwords=False)
Tokens in large language models¶
A large language model (LLM) also splits a text into tokens before it reads the text. The tokens of an LLM are not words. A token there is a piece of a word: a frequent word is one token, and a rare word is split into several tokens.
The package tiktoken has the tokenizers of the OpenAI models.
The cell below splits the example post with o200k_base, a tokenizer that recent OpenAI models use.
The first call downloads the token list of this tokenizer (3.6 MB).
import tiktoken
enc = tiktoken.get_encoding("o200k_base")
token_ids = enc.encode(s)
llm_tokens = [enc.decode([token_id]) for token_id in token_ids]
print(len(llm_tokens), "tokens")
print(llm_tokens)
print("".join(llm_tokens) == s)
The post has 18 tokens here, and TweetTokenizer split it into 12.
soooooo becomes three tokens, and #datascience becomes #, datas, and cience.
Many tokens start with a space, because this tokenizer keeps the spaces.
The last line prints True: the tokens, joined together, give back the exact post.
The two kinds of tokenizers differ in four ways.
| Word tokenizer (this notebook) | Tokenizer of an LLM | |
|---|---|---|
| A token is | A word, a hashtag, an emoticon | A piece of a word |
| The rules | People write them | Learned from a large amount of text |
| Cleaning | You lowercase the text and remove tokens | Nothing is removed |
| Used for | Counting words | The input of the model, its cost, and its length limit |
Each LLM has its own tokenizer, and you cannot change it. The providers of LLMs count the price and the length limit of a request in tokens, and a post usually has more tokens than words. You do not normalize a text or remove stopwords before you send it to an LLM.
The rest of this notebook counts words, so it uses the tokens of TweetTokenizer.
Count words¶
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, and most tweets have one or two labels.
import pandas as pd
df = pd.read_parquet(data_path)
print(df.shape)
df.dtypes
The columns are text, date, label (a list of 19 zeros and ones), label_name (the list of the topic names of the tweet), and id.
The authors of the dataset replaced the links and the account names in the text with three placeholders:
{{URL}}stands for a link.{{USERNAME}}stands for a mention of an account that is not verified.{@Name@}is a mention of a verified account. The display name of the account stays between the two markers, for example{@Daily Planet@}.
The file also writes the apostrophe as the curly character ’, not as the straight character ' of a keyboard.
No tokenizer knows these placeholders, so check what the tokenizer does with them. The post below is hand-written in the format of the file.
example = "{@Daily Planet@} says the game starts at 8, don’t be late {{USERNAME}} #gameday {{URL}}"
print(tokenizer.tokenize(example))
The result has three problems.
- Each of the first two placeholders becomes four braces and a word, so
urlandusernamewould be counted as words. - The tokenizer reads
@Dailyas a mention and removes it. The second word of the name,planet, stays. - The curly apostrophe splits
don’tintodon,’, andt. The stopword list hasdon'twith a straight apostrophe.
The function clean_text below fixes the text before the tokenizer reads it.
It removes {{URL}} and {{USERNAME}}, because each is the same string in every tweet and says nothing about the content.
It keeps the display name of a verified account as plain text and removes the markers, because the name of a news outlet, a team, or an artist says what the tweet is about.
It replaces the curly apostrophe with the straight one.
The function tokenize then runs the three steps in order: clean the text, tokenize it, and normalize the tokens.
import re
def clean_text(text):
text = text.replace("{{URL}}", " ").replace("{{USERNAME}}", " ")
text = re.sub(r"\{@(.*?)@\}", r"\1", text)
return text.replace("’", "'")
def tokenize(text, remove_stopwords=True):
return normalize(tokenizer.tokenize(clean_text(text)), remove_stopwords)
print(clean_text(example))
print(tokenize(example))
Now count.
Take 500 random tweets, tokenize each one, and count the tokens with collections.Counter.
random_state fixes the sample, so every run takes the same 500 tweets.
from collections import Counter
sample = df.sample(500, random_state=42)
counts = Counter()
for text in sample["text"]:
counts.update(tokenize(text))
print(sum(counts.values()), "tokens,", len(counts), "different words")
counts.most_common(20)
The top of the list has general words, such as new and one, and topic words, such as game and music.
The most frequent word is via.
In this file it is almost always followed by the name of an account, as in the text that the share button of a website writes.
A word like this is frequent because of how the posts were made, not because of what they say.
Most words are rare. In this sample, about 70% of the different words appear only once. A word that appears once or twice says little about the collection, so an analysis usually keeps only the words above a minimum count.
once = sum(1 for c in counts.values() if c == 1)
print(once, "of", len(counts), "words appear only once")
frequent = {word: c for word, c in counts.items() if c >= 5}
print(len(frequent), "words appear 5 times or more")
Plot the top words¶
A bar plot shows the counts of the top words. The bars are horizontal, so the words are easy to read.
import matplotlib.pyplot as plt
top = pd.DataFrame(counts.most_common(20), columns=["word", "count"])
fig, ax = plt.subplots(figsize=(5, 5))
ax.barh(top["word"], top["count"])
ax.invert_yaxis()
ax.set_xlabel("Count in 500 tweets")
ax.spines[["top", "right"]].set_visible(False)
plt.show()
A word cloud shows the same counts as font sizes.
It is harder to read than the bar plot.
A reader cannot compare two font sizes exactly, a long word looks larger than a short word with the same count, and the position of a word means nothing.
The bar plot shows the order of the words and their counts.
If you need a word cloud, the wordcloud package draws one from the same counts.
TF-IDF by hand¶
Raw counts favor the words that are frequent everywhere. TF-IDF (term frequency–inverse document frequency) reweights the count of a word in a document by the number of documents that contain the word.
$$ \mathrm{tf}(t, d) = \frac{f_{t,d}}{\sum_{t' \in d} f_{t',d}} \qquad \mathrm{idf}(t) = \ln \frac{N}{n_t} $$
- $f_{t,d}$ is the count of term $t$ in document $d$.
- The sum under the line adds the counts of all terms $t'$ in document $d$. It is the number of tokens in the document.
- $N$ is the number of documents, and $n_t$ is the number of documents that contain term $t$.
- $\ln$ is the natural logarithm.
The TF-IDF score of term $t$ in document $d$ is $\mathrm{tf}(t, d) \times \mathrm{idf}(t)$.
The three documents below are hand-written. One is about sports, one is about an election, and one is about a phone.
import math
docs = {
"A": "the game was great and the team played great",
"B": "the election was close and the vote count is not final",
"C": "the new phone is out and the camera is great",
}
doc_words = {name: text.split() for name, text in docs.items()}
for name, words in doc_words.items():
print(name, Counter(words).most_common(3))
By raw count, the top word of every document is the.
The idf of a word depends on how many of the three documents contain it.
n_docs = len(doc_words)
doc_freq = Counter()
for words in doc_words.values():
doc_freq.update(set(words))
idf = {word: math.log(n_docs / n) for word, n in doc_freq.items()}
for word in ["the", "and", "great", "was", "game", "election"]:
print(f"{word:10s} in {doc_freq[word]} of {n_docs} documents idf = {idf[word]:.2f}")
A word that is in all three documents has an idf of 0. A word that is in one document has an idf of $\ln 3$, which is 1.10.
def tf_idf(words):
word_counts = Counter(words)
return {word: c / len(words) * idf[word] for word, c in word_counts.items()}
for name, words in doc_words.items():
ranked = sorted(tf_idf(words).items(), key=lambda item: item[1], reverse=True)
print(name, [(word, round(score, 3)) for word, score in ranked])
What to look for in the output:
theandandget a score of 0, because they are in all three documents. No stopword list was needed to remove them.greatis down-weighted, not removed. It appears twice in A, but it is also in C. Its score in A is below the score ofgame, which appears once.- The top words describe each document: a game, an election, a phone.
- TF-IDF knows only that a word is rare. It does not know that a word is meaningful. In B,
notscores as high aselection.
TF-IDF with scikit-learn¶
TfidfVectorizer from scikit-learn does the tokenizing, the counting, and the weighting in one call.
It returns a matrix with one row for each document and one column for each word.
from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer()
matrix = vectorizer.fit_transform(docs.values())
pd.DataFrame(matrix.toarray(), index=list(docs), columns=vectorizer.get_feature_names_out()).round(2).T
The numbers are not the numbers that we computed by hand, and the is not 0.
scikit-learn uses other formulas by default:
- Its idf is $\ln \frac{1 + N}{1 + n_t} + 1$. This value is never below 1, so a word that is in every document keeps a weight.
- Its tf is the raw count $f_{t,d}$, not the count divided by the length of the document.
- It then scales each row so that the squares of its values sum to 1.
With these defaults, the has the second highest score in document A.
The scores of scikit-learn do not remove stopwords for you.
When you report TF-IDF scores, say which formula you used.
Now use real posts. TF-IDF needs documents, and one tweet is too short to be a useful document. Group the tweets by topic label, and join the tweets of each label into one long document. A tweet with two labels goes into two documents.
by_label = df.explode("label_name").dropna(subset=["label_name"])
label_docs = by_label.groupby("label_name")["text"].apply(" ".join)
print(len(label_docs), "documents")
by_label["label_name"].value_counts()
The table shows the number of tweets for each label. The largest labels have more than 1,000 tweets, and the smallest have about 100.
analyzer=tokenize tells the vectorizer to call the tokenize function from above in place of its own tokenizer.
The placeholders and the stopwords are then handled in the same way as before.
vectorizer = TfidfVectorizer(analyzer=tokenize)
matrix = vectorizer.fit_transform(label_docs)
tfidf = pd.DataFrame(matrix.toarray(), index=label_docs.index, columns=vectorizer.get_feature_names_out())
tfidf.shape
The matrix has 19 rows, one for each label, and one column for each different word.
The next two cells show the top 10 words of four labels, first by raw count and then by TF-IDF.
labels = ["sports", "music", "food_&_dining", "gaming"]
pd.DataFrame({
label: [word for word, c in Counter(tokenize(label_docs[label])).most_common(10)]
for label in labels
})
def top_tfidf(scores, labels, n=10):
return pd.DataFrame({
label: scores.loc[label].sort_values(ascending=False).head(n).index
for label in labels
})
top_tfidf(tfidf, labels)
Compare the two tables.
General words such as today, first, and great leave the columns, and words that belong to one topic move up or come in.
The two tables still share most of their words.
The reason is the idf of scikit-learn: it only ranges from 1 to about 3.3 for 19 documents, so the count of a word still decides most of its score.
The stopword list matters a lot here.
The next cell computes the same scores with the stopwords kept.
The top words of these four labels are then stopwords such as the, to, and and.
vectorizer_all = TfidfVectorizer(analyzer=lambda text: tokenize(text, remove_stopwords=False))
matrix_all = vectorizer_all.fit_transform(label_docs)
tfidf_all = pd.DataFrame(
matrix_all.toarray(), index=label_docs.index, columns=vectorizer_all.get_feature_names_out()
)
top_tfidf(tfidf_all, labels)
Compare two corpora¶
TF-IDF describes one document against all the others. Often the question is more direct: we have posts from two groups, and we want the words that one group uses more than the other. This section and the next follow Monroe, Colaresi, and Quinn (2008), Fightin' Words. They show three measures in order, and each one fixes a problem of the one before.
The two groups here come from the topic labels. A tweet can have several labels, so the groups are defined as follows:
- The sports group is the tweets that have the label
sportsand do not have the labelmusic. - The music group is the tweets that have the label
musicand do not have the labelsports.
sports and music are two of the three largest labels, and their subjects are clearly different.
The few tweets that have both labels are left out.
is_sports = df["label_name"].apply(lambda names: "sports" in names)
is_music = df["label_name"].apply(lambda names: "music" in names)
sports = df[is_sports & ~is_music]
music = df[is_music & ~is_sports]
print(len(sports), "tweets in the sports group")
print(len(music), "tweets in the music group")
print((is_sports & is_music).sum(), "tweets with both labels, left out")
Count the words of each group. This time the stopwords stay in, so that we can see what each measure does with them.
The table has one row for each word, with its count in each group and its frequency. The frequency is the count divided by the number of tokens of the group.
def count_words(texts):
word_counts = Counter()
for text in texts:
word_counts.update(tokenize(text, remove_stopwords=False))
return word_counts
counts_sports = count_words(sports["text"])
counts_music = count_words(music["text"])
table = pd.DataFrame({"sports": counts_sports, "music": counts_music}).fillna(0).astype(int)
table["freq_sports"] = table["sports"] / table["sports"].sum()
table["freq_music"] = table["music"] / table["music"].sum()
print(len(table), "different words")
table.sort_values("sports", ascending=False).head(10)
Measure 1: the difference of frequencies. Subtract the frequency of a word in the music group from its frequency in the sports group.
table["difference"] = table["freq_sports"] - table["freq_music"]
ranked = table.sort_values("difference", ascending=False)
print("More frequent in sports:", ranked.head(15).index.tolist())
print("More frequent in music: ", ranked.tail(15).index.tolist()[::-1])
Topic words such as game and music are in the two lists.
Stopwords such as the, in, for, i, and you are there too.
A frequent word has a large difference even when the two groups use it at nearly the same rate, so frequent words dominate this measure.
Removing stopwords first would hide the problem, and it would also remove real differences.
In this data, the music group uses i and you about twice as often as the sports group.
Measure 2: the log-odds ratio. The odds of a word are $f / (1 - f)$, where $f$ is its frequency. The log-odds ratio is the logarithm of the odds in one group divided by the odds in the other group. It is 0 when the two groups use the word at the same rate, positive when the sports group uses it more, and negative when the music group uses it more. It compares rates, so a frequent word has no advantage.
import numpy as np
only_one = (table["sports"] == 0) | (table["music"] == 0)
print(only_one.sum(), "of", len(table), "words appear in only one group")
both = table[~only_one].copy()
odds_sports = both["freq_sports"] / (1 - both["freq_sports"])
odds_music = both["freq_music"] / (1 - both["freq_music"])
both["log_odds_ratio"] = np.log(odds_sports / odds_music)
ranked = both.sort_values("log_odds_ratio", ascending=False)
ranked[["sports", "music", "log_odds_ratio"]].head(10)
ranked[["sports", "music", "log_odds_ratio"]].tail(10)
The stopwords are gone from the top, but the measure has two new problems.
- Most words appear in only one group. Their odds ratio is zero or infinite, so the cell had to leave them out. Some of the clearest words of each group are among them.
- In the two tables, most words have a count of 1 or 2 in the other group. A ratio that is built on a count of 1 is not stable: one more occurrence would cut it in half. Rare words distort this measure.
Log-odds ratio with a prior¶
Monroe, Colaresi, and Quinn solve both problems with a prior. Before we look at the two groups, we assume that each group uses every word at the rate that the word has in a large background collection. In practice, the counts of a background collection are added to the counts of each group.
For one word:
$$ \delta = \ln \frac{y_a + \alpha}{n_a + \alpha_0 - y_a - \alpha} - \ln \frac{y_b + \alpha}{n_b + \alpha_0 - y_b - \alpha} $$
$$ z = \frac{\delta}{\sqrt{\dfrac{1}{y_a + \alpha} + \dfrac{1}{y_b + \alpha}}} $$
- $y_a$ is the count of the word in group A, and $n_a$ is the number of tokens in group A. $y_b$ and $n_b$ are the same for group B.
- $\alpha$ is the count of the word in the background collection, and $\alpha_0$ is the number of tokens in the background collection. The code calls them
aanda_0. - $\delta$ is the log-odds ratio after the background counts are added. The code calls it
delta. - $z$ is $\delta$ divided by its standard error. It is a z-score.
The prior changes three things. A word that is missing from one group no longer has a count of 0, so every word gets a score. A rare word stays close to the background rate, because a few occurrences change little. The z-score is large only when the difference is large compared with its uncertainty.
The method is called the log-odds ratio with an informative Dirichlet prior.
The function below computes it from three Counter objects.
def log_odds_with_prior(counts_a, counts_b, counts_prior):
"""Return the z-score of the log-odds ratio of each word, A against B."""
n_a = sum(counts_a.values())
n_b = sum(counts_b.values())
a_0 = sum(counts_prior.values())
rows = []
for word in set(counts_a) | set(counts_b):
y_a = counts_a.get(word, 0)
y_b = counts_b.get(word, 0)
a = counts_prior.get(word, 0)
delta = math.log((y_a + a) / (n_a + a_0 - y_a - a)) - math.log((y_b + a) / (n_b + a_0 - y_b - a))
std = math.sqrt(1 / (y_a + a) + 1 / (y_b + a))
rows.append({"word": word, "count_a": y_a, "count_b": y_b, "z": delta / std})
result = pd.DataFrame(rows)
return result.sort_values(["z", "word"], ascending=[False, True]).reset_index(drop=True)
The background collection here is all 6,090 tweets of the file. It contains the two groups, so every word of a group has a count above 0 in the background.
counts_all = count_words(df["text"])
result = log_odds_with_prior(counts_sports, counts_music, counts_all)
result.head(15)
result.tail(15).iloc[::-1]
The first table has the words of the sports group, and the second has the words of the music group. What to look for:
- Words that appear in only one group are now ranked. Several of them are at the top of each table.
- No word with a count of 1 or 2 in its own group is at the top. The words at the top are frequent in one group and rare in the other.
- Many of the words are names of teams, leagues, athletes, artists, and songs. The tweets of this dataset were collected from trending topics, so the names that were trending are frequent.
- A few stopwords remain, such as
theon the sports side andiandyouon the music side. These are real differences in how the two groups write. A stopword list would have removed them.
A z-score above 1.96 or below -1.96 is the usual cutoff for a difference that is unlikely to come from chance. Only a small part of the vocabulary passes it. Most stopwords do not.
print((result["z"].abs() > 1.96).sum(), "of", len(result), "words have a z-score beyond 1.96")
result[result["word"].isin(["the", "a", "to", "and", "of", "i", "you"])]
The choice of the background collection matters. With a larger background, the z-score of every word moves toward 0, so fewer words pass the cutoff. Use a collection of the same kind of text as your two groups, for example all the posts that you collected.