Sub topic 18
Nearest neighbours and analogy queries
This chapter shows how to query a trained embedding space, how an analogy query works internally, and why you should read the results critically. It assumes you know cosine similarity, can load vectors with gensim (from the chapters on training word2vec and using pretrained GloVe), and are comfortable with NumPy.
Nearest neighbours
A nearest-neighbour query takes one word, computes its cosine similarity to every other word vector, and returns the highest scores. It is the quickest sanity check for a new embedding. If "frog" is not close to other animals, something is wrong with the data or the training.
Gensim does this with most_similar. The code below also does it by hand, so you can see what the library computes.
import numpy as np
import gensim.downloader as api
wv = api.load("glove-wiki-gigaword-50")
print(wv.most_similar("frog", topn=5))
def nearest(wv, word, k=5):
vecs = wv.vectors / np.linalg.norm(wv.vectors, axis=1, keepdims=True)
idx = wv.key_to_index[word]
sims = vecs @ vecs[idx]
order = np.argsort(-sims)[: k + 1]
return [(wv.index_to_key[i], float(sims[i])) for i in order if i != idx][:k]
print(nearest(wv, "frog", k=5))Both calls should print the same words and scores. Normalising every row first turns cosine similarity into one matrix-vector product. The query word is excluded because it is always its own nearest neighbour with similarity 1.0.
The neighbours of a word are often not synonyms. They are words that appear in similar contexts. For "frog" you may see plurals, related animals, and rare taxonomic terms. Antonyms such as "hot" and "cold" are also close, because they occur in the same sentence frames.
Analogy queries
An analogy query asks "a is to b as c is to what?". The classic example is man : king :: woman : ?. The method is vector arithmetic. You compute a target vector and return the words closest to it.
target = vec(king) - vec(man) + vec(woman)
answer = the word whose vector has the highest cosine similarity to targetThe input words are excluded from the candidates. Without that rule, the answer is usually one of the inputs, most often "king".
import numpy as np
import gensim.downloader as api
wv = api.load("glove-wiki-gigaword-50")
def analogy(wv, a, b, c, k=3):
"""a is to b as c is to ?"""
unit = lambda w: wv[w] / np.linalg.norm(wv[w])
target = unit(b) - unit(a) + unit(c)
hits = wv.similar_by_vector(target, topn=k + 3)
return [(w, s) for w, s in hits if w not in (a, b, c)][:k]
print(analogy(wv, "man", "king", "woman"))
print(wv.most_similar(positive=["king", "woman"], negative=["man"], topn=3))The two calls should rank the same words. Gensim's most_similar with positive and negative lists averages the unit-length vectors, adding the positive ones and subtracting the negative ones. It then ranks by cosine and drops the input words. This is known as 3CosAdd.
Why the arithmetic can work
Skip-gram with negative sampling and GloVe both push the dot product of two vectors toward a quantity built from co-occurrence statistics. GloVe fits log co-occurrence counts directly, so a difference of two word vectors approximates a ratio of co-occurrence probabilities. If the contexts that separate "king" from "queen" are the same ones that separate "man" from "woman", the offset king - queen and the offset man - woman point in similar directions. That is the geometric idea behind the analogy.
The effect is approximate. It works best for frequent words and for relations that appear consistently in the corpus, such as capital and country, or singular and plural.
Reading the results critically
Analogy demos are selective. These are the common failure modes.
- The inputs dominate. The target is close to
b, because you start fromband move a short distance. Without excluding the inputs, the "answer" is oftenbitself. - Frequency bias. Frequent words tend to appear as neighbours of many things. A correct answer ranked fourth is a miss.
- Relations are uneven. Syntactic and geographic relations work well. Many semantic relations, such as hypernymy and part-whole, work poorly.
- Cherry-picking. Published examples were chosen because they worked. Measure over a full set of questions instead.
- Small corpora. The tiny gensim training example from the earlier chapter cannot produce meaningful neighbours. Three sentences give almost no signal.
Measuring analogy accuracy
Mikolov et al. released a test set of about 19,500 analogy questions, split into semantic and syntactic sections. Gensim ships it as questions-words.txt.
from gensim.test.utils import datapath
import gensim.downloader as api
wv = api.load("glove-wiki-gigaword-50")
score, sections = wv.evaluate_word_analogies(datapath("questions-words.txt"))
print(f"overall accuracy: {score:.3f}")
for sec in sections:
total = len(sec["correct"]) + len(sec["incorrect"])
if total:
print(sec["section"], f"{len(sec['correct']) / total:.2f}")The method returns the overall accuracy and a per-section breakdown. By default it only considers the 300,000 most frequent words and skips questions whose words are missing from the vocabulary. The score therefore depends on vocabulary size, case handling, and how many questions were skipped. Compare models only when you evaluate them the same way. The full treatment of intrinsic and extrinsic evaluation comes in the evaluation chapter.
Practical tips
- Use
topnof 5 to 10 and look at the scores, not only the top word. A top score of 0.55 with a close second place is a weak answer. - Try the query with several related words, for example averaging
kingandqueenas positives, to get a neighbourhood rather than a single point. - Remember that neighbours reflect the training corpus. A news corpus and a medical corpus give different neighbours for "cell".
- Out-of-vocabulary words raise a
KeyError. Checkword in wvbefore querying.
Exercise
You run wv.most_similar(positive=["paris", "germany"], negative=["france"], topn=3). Explain which vector is computed and why the input words are not returned as answers.
Show answer
Gensim averages the unit-length vectors of "paris" and "germany" and subtracts the unit-length vector of "france". The target is roughly paris - france + germany, which should land near "berlin". The three input words are removed from the candidates because the target stays close to the vectors that built it, so without the exclusion an input word would often rank first.
Exercise
A colleague reports 90% analogy accuracy on a custom model, but the evaluation silently skipped most questions because their words were missing from the vocabulary. What is wrong with the claim and how would you fix the evaluation?
Show answer
The accuracy covers only the small subset of questions the model could attempt, so it is not comparable to a score over the full set. Report the number of questions answered versus skipped, or count skipped questions as incorrect, and use the same vocabulary restriction and case handling for every model you compare.