Word vectors¶
A word embedding gives each word a vector, which is a list of numbers. Words that are used in similar contexts get vectors that are close to each other. This notebook loads pre-trained GloVe vectors with Gensim, and then uses them to find related words, to do calculations on words, to compare posts by meaning, and to place words on a scale between two anchor words.
Sections: Load pre-trained vectors, Find related words, Calculations on vectors, Compare texts by meaning, Place words on a scale.
Packages beyond the standard library: gensim, nltk, numpy, pandas, pyarrow.
Install them with uv add gensim nltk numpy pandas pyarrow (or pip install).
Colab has all of them except gensim, and the next cell installs it there.
# Colab does not have gensim, so this cell installs it there.
# pip may print a note about restarting the kernel. A restart is not needed.
# The cell does nothing if gensim is already installed.
import importlib.util
if importlib.util.find_spec("gensim") is None:
%pip install -q gensim
# 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")
Load pre-trained vectors¶
Training an embedding needs a very large collection of text. Most projects download vectors that someone else trained. Gensim can download several sets of vectors by name.
glove-wiki-gigaword-100 is a set of GloVe vectors that were trained on Wikipedia and on news text.
It has 400,000 lowercase words, and each word has a vector of 100 numbers.
The first call downloads a file of about 130 MB into the folder gensim-data in your home directory.
Every call then reads that file, which takes 15 to 20 seconds on a recent laptop.
It can take a minute or more on a free Colab runtime.
Load the vectors once, in this cell, and reuse the variable glove.
import gensim.downloader as api
glove = api.load("glove-wiki-gigaword-100")
print(len(glove), "words,", glove.vector_size, "numbers for each word")
glove["king"][:10]
The cell above shows the first 10 of the 100 numbers of king.
A single number has no meaning that a person can read.
What matters is how close two vectors are.
The usual measure is the cosine similarity of two vectors $u$ and $v$.
$$ \cos(u, v) = \frac{u \cdot v}{\lVert u \rVert \, \lVert v \rVert} $$
- $u \cdot v$ is the dot product: multiply the two numbers at each position, and add the products.
- $\lVert u \rVert$ is the length of $u$: the square root of the sum of its squared numbers.
The value is 1 when two vectors point in the same direction, and it is near 0 when two words are unrelated.
print("movie, film:", glove.similarity("movie", "film"))
print("movie, bus: ", glove.similarity("movie", "bus"))
Find related words¶
most_similar returns the words whose vectors are closest to the vector of a word.
glove.most_similar("scam", topn=10)
The list has other forms of the word, such as scams, and words with a related meaning, such as fraud.
One use is to extend a keyword list for a data collection. Start from a few keywords, list their neighbors, and add the ones that fit. Read every candidate before you add it. A neighbor is a related word, not always a word with the same meaning. Words with opposite meanings are often close, because they are used in the same contexts.
print("good, bad:", glove.similarity("good", "bad"))
The vocabulary is fixed.
Every word is lowercase, and a word that is not in the vocabulary raises a KeyError.
Check with in first.
These vectors were trained on text from 2014 and earlier, so newer words are missing, and so are hashtags.
for word in ["movie", "Movie", "covid", "#music"]:
print(word, word in glove)
Calculations on vectors¶
Vectors can be added and subtracted.
The best-known example is king - man + woman, which gives a vector close to queen.
In most_similar, the words in positive are added and the words in negative are subtracted.
glove.most_similar(positive=["king", "woman"], negative=["man"], topn=5)
The same calculation with the vectors themselves:
vector = glove["king"] - glove["man"] + glove["woman"]
glove.similar_by_vector(vector, topn=5)
By hand, the closest word to the result is king itself, and queen is second.
most_similar leaves out the words of the question, so it returns queen first.
The result of the calculation is near the vector of queen.
It is not equal to it.
The same calculation works for other relations, such as a country and its capital.
glove.most_similar(positive=["paris", "germany"], negative=["france"], topn=3)
Compare texts by meaning¶
A text can have a vector too. The simplest one is the average of the vectors of its words. Two texts that use words with similar meanings then have similar vectors, even when they share no word.
The function text_vector tokenizes a text, drops the stopwords and the punctuation, and averages the vectors of the remaining words.
It removes the # of a hashtag, so #music is read as music.
It skips every word that is not in the vocabulary.
import nltk
import numpy as np
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 text_vector(text):
words = []
for token in tokenizer.tokenize(text):
token = token.lstrip("#")
if not any(ch.isalnum() for ch in token):
continue
if token in stop_words or token not in glove:
continue
words.append(token)
if not words:
return None
return np.mean([glove[word] for word in words], axis=0)
def cosine(a, b):
return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))
The three posts below are hand-written. A and B say the same thing with different words. C is about something else.
posts = {
"A": "the movie was great",
"B": "the film was excellent",
"C": "the bus was late",
}
vectors = {name: text_vector(text) for name, text in posts.items()}
for a, b in [("A", "B"), ("A", "C"), ("B", "C")]:
print(a, "and", b, round(cosine(vectors[a], vectors[b]), 2))
A and B have the highest similarity.
A bag of words cannot see this: after the stopwords the and was are removed, no two of the three posts share a word, so every pair has a similarity of 0.
The two unrelated pairs do not score 0 with word vectors. Compare the scores with each other, and do not read one score alone.
Now use real posts.
The file that the first cell downloaded is TweetTopic (Antypas et al., 2022), a research dataset of 6,090 English tweets with topic labels.
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.
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_vectors = [text_vector(clean_text(text)) for text in sample["text"]]
has_vector = [vector is not None for vector in sample_vectors]
print(has_vector.count(False), "of", len(sample), "tweets have no word in the vocabulary")
Stack the vectors into one matrix with a row for each tweet, and scale every row to length 1. The cosine similarity between a query and all the tweets is then one matrix product.
sample = sample[has_vector].reset_index(drop=True)
matrix = np.vstack([vector for vector in sample_vectors if vector is not None])
matrix = matrix / np.linalg.norm(matrix, axis=1, keepdims=True)
matrix.shape
most_similar_posts computes the vector of a query and returns the tweets with the highest similarity.
The query below is hand-written.
def most_similar_posts(query, n=5):
query_vector = text_vector(query)
scores = matrix.dot(query_vector / np.linalg.norm(query_vector))
order = np.argsort(-scores)[:n]
return sample.iloc[order].assign(score=scores[order])
query = "the team won the game last night"
for row in most_similar_posts(query).itertuples():
print(round(row.score, 2), row.text)
print()
Read the five tweets. They are about games and matches. None of them repeats the query, and most of them share only one or two words with it.
The topic labels give a check that does not depend on reading. Count the labels of the 25 tweets that are most similar to the query, and compare with the labels of the whole sample.
nearest = most_similar_posts(query, n=25)
pd.DataFrame({
"nearest 25": nearest.explode("label_name")["label_name"].value_counts(),
"whole sample": sample.explode("label_name")["label_name"].value_counts(),
}).fillna(0).astype(int).sort_values("nearest 25", ascending=False).head(8)
All or nearly all of the 25 tweets have the label sports.
In the whole sample, fewer than one tweet in three has it.
Try other queries, for example "listening to the new album on repeat".
The method has limits.
The average ignores the order of the words.
Each word has one vector, so the bank of a river and the bank that holds money share a vector.
A word that is not in the vocabulary is skipped, and for tweets that means many names, new words, and hashtags made of several words.
Place words on a scale¶
Two anchor words define a direction: the vector of one anchor minus the vector of the other. The cosine similarity between a word and this direction says which anchor the word is closer to. A positive score means the first anchor, and a negative score means the second.
The first scale goes from bad to good.
def scale(words, positive, negative):
axis = glove[positive] - glove[negative]
scores = {word: cosine(glove[word], axis) for word in words}
return pd.Series(scores).sort_values(ascending=False).round(2)
words = ["excellent", "wonderful", "nice", "fine", "okay", "sad",
"failure", "disaster", "awful", "terrible", "horrible"]
scale(words, "good", "bad")
The words with a positive meaning are at the top, and the words with a negative meaning are at the bottom. Nobody labeled these words. The order comes from how the words are used in the text that the vectors were trained on.
Kozlowski, Taddy, and Evans (2019), The Geometry of Culture, use this method to study social class. They build a scale from poor to rich and place words such as sports and music styles on it. The next cell does this with one pair of anchors.
words = ["yacht", "mansion", "golf", "tennis", "opera", "jazz", "boxing", "rap",
"banker", "lawyer", "teacher", "nurse", "farmer", "janitor", "bus", "beer"]
scale(words, "rich", "poor")
The result is hard to read.
Some words are where you would expect them, and others are not: yacht is near the middle.
One pair of anchors is noisy, because the difference between rich and poor also contains other differences between these two words.
The paper averages the directions of several anchor pairs that have the same meaning. The noise of the single pairs partly cancels.
def scale_from_pairs(words, pairs):
axis = np.mean([glove[positive] - glove[negative] for positive, negative in pairs], axis=0)
scores = {word: cosine(glove[word], axis) for word in words}
return pd.Series(scores).sort_values(ascending=False).round(2)
pairs = [
("rich", "poor"),
("wealthy", "impoverished"),
("affluent", "destitute"),
("expensive", "inexpensive"),
("luxury", "cheap"),
]
scale_from_pairs(words, pairs)
With five pairs, mansion, banker, golf, and yacht are at the rich end, and janitor and nurse are at the other end.
Two cautions for this method.
- A scale exists for any two anchor words, and every word gets a score. First check the scale with words whose position you know. Then read the words that you want to study.
- The scores describe how words are used in the training text. They include the stereotypes of that text. This is a problem if you read the scores as facts. Some papers use it as a measurement: Garg et al. (2018) measure gender and ethnic stereotypes over 100 years in this way.