Sub topic 19
Evaluating embeddings
This chapter assumes you can train or load word vectors with gensim (see the chapters on training word2vec and using pretrained GloVe vectors). It also assumes you know cosine similarity and basic Python and NumPy. By the end you should be able to run intrinsic tests, set up an extrinsic test, and judge which result to trust.
Why evaluation is hard
An embedding has no single correct answer to compare against. The vectors are a by-product of a prediction task, and nobody cares whether the model predicts context words well. People care whether the vectors help with some other job. That gives two families of evaluation.
- Intrinsic evaluation tests the vectors directly, with cheap, fast checks such as word similarity or analogies.
- Extrinsic evaluation plugs the vectors into a downstream task, such as text classification or named entity recognition, and measures task performance.
Intrinsic tests are quick and make good debugging tools. Extrinsic tests answer the question you actually have, but they are slower and noisier.
Intrinsic: word similarity
Word similarity benchmarks contain word pairs with human ratings of how related they are. Common sets include WordSim-353 and SimLex-999. Each pair has a score, for example tiger, cat rated high and tiger, democracy rated low.
The procedure is:
- Compute the cosine similarity of each pair from your vectors.
- Compare your list of similarities to the human list with Spearman's rank correlation.
Spearman is the standard choice because it compares rankings and ignores scale. Human ratings and cosines live on different scales, so only the ordering is meaningful.
Gensim ships a small copy of WordSim-353, so you can run this without downloading anything extra:
import gensim.downloader as api
from gensim.test.utils import datapath
wv = api.load("glove-wiki-gigaword-50")
pearson, spearman, oov_ratio = wv.evaluate_word_pairs(
datapath("wordsim353.tsv")
)
print("Spearman:", spearman.correlation)
print("Pearson:", pearson.statistic if hasattr(pearson, "statistic") else pearson[0])
print("Out-of-vocabulary pairs (%):", oov_ratio)Read the out-of-vocabulary percentage alongside the correlation. Pairs that contain unknown words are skipped, so a model with a small vocabulary can score well on the few pairs it covers and still be a poor model.
Relatedness versus similarity
The two benchmarks named above measure different things. WordSim-353 mixes relatedness (coffee, cup) with similarity (coffee, tea). SimLex-999 rates strict similarity, so coffee, cup scores low. Embeddings trained on context windows capture both, and a model that scores well on one set can score worse on the other. State which kind your task needs before choosing a benchmark.
Intrinsic: analogies
The analogy task asks a is to b as c is to ? and answers with the nearest vector to b - a + c. The Google analogy set contains semantic questions (capital cities, currencies) and syntactic ones (verb tenses, plurals).
import gensim.downloader as api
from gensim.test.utils import datapath
wv = api.load("glove-wiki-gigaword-50")
score, sections = wv.evaluate_word_analogies(datapath("questions-words.txt"))
print("Overall accuracy:", round(score, 3))
for sec in sections:
total = len(sec["correct"]) + len(sec["incorrect"])
if total:
print(sec["section"], round(len(sec["correct"]) / total, 3))Two details matter when reading these numbers.
- By default the search excludes the three query words from the answer list. Without that exclusion, the nearest vector to
king - man + womanis oftenkingitself, which inflates or ruins results depending on the implementation. - Accuracy needs an exact match to the expected word. A model that returns
queensinstead ofqueengets no credit, so the score is strict.
Analogy accuracy is a popular headline number, but it measures a narrow slice of structure. High analogy accuracy does not guarantee good downstream performance.
Intrinsic: nearest neighbours by hand
Reading the nearest neighbours of a few chosen words is a legitimate and underused check. Pick words in several frequency ranges and several parts of speech, and look at the top ten neighbours for each.
for word in ["frog", "bank", "run", "january"]:
print(word, [w for w, _ in wv.most_similar(word, topn=8)])Look for three things: whether neighbours are meaningful, whether rare words get sensible neighbours or noise, and whether an ambiguous word like bank collapses its senses into one blend.
Extrinsic evaluation
An extrinsic test holds the downstream model fixed and changes only the embeddings. The result tells you which vectors help the task you care about.
A minimal design for text classification:
- Split labeled data into train and test sets before looking at any scores.
- Represent each document as the mean of its word vectors, skipping unknown words.
- Train the same simple classifier, such as logistic regression, once per embedding set.
- Compare test accuracy or F1, across several random seeds.
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score
def doc_vector(tokens, wv):
vecs = [wv[t] for t in tokens if t in wv]
if not vecs:
return np.zeros(wv.vector_size)
return np.mean(vecs, axis=0)
def evaluate(wv, train_docs, train_y, test_docs, test_y):
Xtr = np.array([doc_vector(d, wv) for d in train_docs])
Xte = np.array([doc_vector(d, wv) for d in test_docs])
clf = LogisticRegression(max_iter=1000).fit(Xtr, train_y)
return f1_score(test_y, clf.predict(Xte), average="macro")Call evaluate once per embedding set with identical data splits and compare the scores.
Common errors
- Tuning on the test set. Choosing the embedding dimension, window size, or model by test score, then reporting that score, overstates quality. Hold out a validation set.
- Comparing unequal setups. Different corpus sizes, vocabularies, or dimensions make a comparison about the data, not the algorithm. Match them, or say they differ.
- Ignoring coverage. Report the share of benchmark words or task tokens that the vocabulary covers.
- Trusting one number. A similarity correlation difference of 0.01 on a few hundred pairs is within noise. Train with several seeds and look at the spread.
- Assuming intrinsic scores transfer. The best embedding on analogies is not reliably the best for your classifier.
Decision criteria
| Question | Use |
|---|---|
| Is my training pipeline working at all? | Nearest neighbours and a similarity benchmark |
| Which hyperparameters should I try first? | Similarity correlation on a validation set |
| Which embeddings suit my application? | Extrinsic test on your own task |
| Do I trust a published number? | Check corpus, dimension, coverage, and seeds |
Exercise
A model scores a Spearman correlation of 0.78 on a word similarity set, and the report says 60% of the pairs were out of vocabulary. Another model scores 0.65 with 2% out of vocabulary. Which result is stronger evidence of a good model, and what would you do next?
Show answer
Neither is directly comparable. The first score is computed on only 40% of the pairs, so it may reflect an easy subset. The second covers almost the whole set. Evaluate both models on the same subset of pairs that both cover, then repeat with several seeds, and finally run an extrinsic test on your own task.
Exercise
Why does evaluate_word_analogies exclude the three query words from the candidate answers, and what happens to accuracy if they are included?
Show answer
The nearest vector to b - a + c is often one of the query words themselves, commonly b, because the offset is small relative to the word vectors. If query words are allowed as answers, many questions are answered with a query word and marked wrong, so accuracy drops sharply and no longer measures analogy structure.