Sub topic 16
Nearest neighbours and analogy queries
Assume you know vectors, dot products, norms, cosine similarity, basic NumPy, and how to train or load a word-embedding model. This chapter focuses on querying embeddings and judging whether the results are meaningful.
Nearest neighbours
A word embedding represents each word as a point in a vector space. To find a word's nearest neighbours, compare its vector with every other word vector. Cosine similarity is commonly used because it measures direction rather than vector length.
A neighbour is useful when the corpus gives the two words similar contexts. For example, a model trained on news may place president, minister, and government near one another. These words are distributionally similar, but they are not necessarily synonyms.
With gensim, most_similar performs this ranking:
import gensim.downloader as api
wv = api.load("glove-wiki-gigaword-50")
print(wv.most_similar("frog", topn=5))The returned scores are cosine similarities. A high score means similar usage patterns, not identical meaning. A word can appear near another because both occur in the same topic or sentence patterns.
Analogy queries
An analogy asks for a word that completes a relationship:
king is to man as woman is to ?
A common embedding operation is:
vector("king") - vector("man") + vector("woman")
The result should be near queen if the learned directions encode that relationship.
print(
wv.most_similar(
positive=["king", "woman"],
negative=["man"],
topn=3,
)
)The positive words are added, and the negative words are subtracted. The query word itself is normally excluded from the results by the library.
| Query type | Operation | What it may capture |
|---|---|---|
| Neighbour | Compare one vector with others | Similar contexts |
| Analogy | Add and subtract vectors | A recurring relation |
Judging results
Inspect several neighbours, not just the first result. Ask whether they share meaning, topic, syntax, or only frequent contexts. Test queries on held-out examples when possible. For an analogy benchmark, measure the proportion of questions whose correct answer appears in the top one or top five results. This intrinsic evaluation checks the vectors directly. A downstream task, such as named-entity recognition or classification, is an extrinsic evaluation and may give a different ranking.
Also check vocabulary coverage. A query fails when a word is absent, and one vector cannot represent all senses of a polysemous word such as bank.
Exercise
Why can "doctor" be a nearest neighbour of "hospital" even though they are not synonyms?
Show answer
Embeddings capture similar contexts. Both words often occur in medical text, so their vectors can be close because of topic association.