You shall know a word by the company it keeps
The distributional hypothesis is the whole foundation: words that appear in similar contexts tend to mean similar things. Doctor and nurse are not close because a linguist said so, but because both appear after the, before names, and alongside verbs of care. Embedding models take that observation literally and turn it into an objective â predict a word's context, or predict a word from its context â then read the learned hidden layer off as the word's meaning.
The move from sparse to dense is the substantive change. A bag-of-words vector for a 50,000-word vocabulary has 50,000 dimensions and is almost entirely zero; an embedding has 100 to 300 dimensions, is dense, and packs related words into neighbouring regions of the space. Because the space is continuous rather than one-hot, similarity becomes a geometric question with a well-defined answer, and interpolation between two words becomes meaningful rather than undefined.
This lesson loads pretrained vectors, probes what they actually encode, examines the analogy arithmetic that made the field famous, and then spends real effort on the ways these evaluations mislead â because the failure modes are more instructive than the headline results.
Sparse counts versus dense coordinates
| Property | Bag of words / TF-IDF | Word embeddings |
|---|---|---|
| Dimensions | One per vocabulary term | Fixed, typically 100â300 |
| Values | Mostly zero | Dense, continuous |
| Similarity | Overlap of shared terms | Geometric, handles paraphrase |
| New word | New column, retrain | Compose from subwords, or skip |
| Interpretability | Each dimension is a word | Dimensions are latent |
| Memory per term | Full row | One fixed-size vector |
| Training signal | Counts | Predictive objective |
The interpretability row is the one people forget. A TF-IDF column can be named â it is invoice â while embedding dimension 147 corresponds to nothing a human can point at. That is not a defect, but it does mean probing requires behavioural tests rather than inspection.
Loading and probing pretrained vectors
A pretrained vocabulary behaves like a lookup table: the id is the row, the vector is the meaning. Everything interesting is a comparison between rows.
import numpy as np
from gensim.models import KeyedVectors
# model = KeyedVectors.load_word2vec_format(
# "GoogleNews-vectors-negative300.bin", binary=True)
# The snippet below runs on any KeyedVectors-like object:
def probe(model, word, topn=5):
try:
vec = model[word]
except KeyError:
print(f"{word}: out of vocabulary")
return None
print(f"{word} norm={np.linalg.norm(vec):.3f} dim={vec.shape[0]}")
for sim_word, score in model.most_similar(word, topn=topn):
print(f" {score:.3f} {sim_word}")
return vec
def cosine(a, b):
return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))
# probe(model, "physician", 5)
# probe(model, "invoice", 5)
# probe(model, "kubernetes", 5) # often OOV in 2013-vintage vectors
The third call is the useful one. A model trained on 2013 news data has no vector for kubernetes or tiktok, and a pipeline that assumes every token resolves will fail at exactly the moment the vocabulary moves on. Checking out-of-vocabulary rate on your own corpus before adopting any pretrained embedding takes a minute and prevents a much later surprise.
Analogies and what they actually demonstrate
The famous result is arithmetic: king - man + woman returns something near queen. The standard way to evaluate it is to remove the query word from the candidate set, take the cosine-nearest neighbour of the offset vector, and check whether the expected answer appears in the top k.
def analogy(model, a, b, c, topn=5):
"""Solve a is to b as c is to ?"""
if not all(w in model for w in (a, b, c)):
return [("OOV", 0.0)]
offset = model[a] - model[b] + model[c]
results = []
for word, score in model.most_similar(positive=[a, c], negative=[b], topn=topn + 10):
if word not in {a, b, c}:
results.append((word, float(score)))
if len(results) == topn:
break
return results
# print(analogy(model, "king", "man", "woman")) # often 'queen'
# print(analogy(model, "Paris", "France", "Germany")) # often 'Berlin'
# print(analogy(model, "better", "good", "bad")) # frequently wrong
What the task proves is narrower than it appears. Consistently high accuracy indicates that some relation is encoded as a roughly consistent direction in the space, but the popular evaluation set is contaminated: a substantial share of the questions were answerable by three-cosine-similarity alone, without any offset arithmetic at all. Independent replications that removed the high-frequency words and the trivially similar pairs saw accuracy drop sharply. Treat analogy accuracy as a weak qualitative probe, not as a capability claim.
Neighbourhood structure is the reliable signal
Comparing nearest neighbours is harder to game and easier to interpret. If the closest words to stock are shares, equity, and ticker, the vector encodes the financial sense; if they are broth and cube, it encodes the culinary one. Sense conflation is the inherent limitation here â a single vector per word type cannot hold both, and the vector settles wherever the training corpus's usage frequency points.
def neighbourhood_report(model, words, topn=8):
for w in words:
if w not in model:
print(f"{w}: OOV")
continue
near = model.most_similar(w, topn=topn)
print(f"{w:<12} -> " + ", ".join(f"{x}({s:.2f})" for x, s in near))
def compare_sets(model, group_a, group_b):
ca = np.mean([model[w] for w in group_a if w in model], axis=0)
cb = np.mean([model[w] for w in group_b if w in model], axis=0)
return cosine(ca, cb)
# groups of words define a direction; compare their centroids
royalty = ["king", "queen", "prince", "princess"]
tech = ["python", "java", "compiler", "kernel"]
print("royalty vs tech centroid cosine:", round(compare_sets(model, royalty, tech), 3))
Centroid comparison generalises the analogy trick: define a group by listing words, average their vectors, and measure the angle between group centroids. It is far more robust than picking two representatives, because averaging suppresses the idiosyncratic component of each individual word.
Composing larger units from word vectors
A single vector describes a word type, but most queries are about phrases and sentences, so some composition rule is unavoidable. The simplest is averaging: take the vectors of the content words, normalise, and treat the mean as the phrase vector. Averaging is fast, order-blind, and surprisingly effective for topical similarity â machine learning and learning machine land in the same place â but it is exactly as blind to relations as bag-of-words, which means dog bites man and man bites dog remain indistinguishable.
Weighting helps before averaging. Dropping stopwords, or weighting by TF-IDF against the surrounding corpus, prevents the and of from pulling every phrase vector toward the common centre of the space, where the majority of word vectors already sit. A slightly stronger alternative is singular value decomposition of the term-document matrix, which factors the sparse counts into a lower-rank space that behaves much like a trained embedding while remaining fully reproducible from counts alone. When order genuinely matters â negation, argument structure â composition must give way to a sequence encoder, which is precisely the gap the next two lessons in this module close.
| Composition rule | Order sensitive | Cost | Typical quality |
|---|---|---|---|
| Unweighted mean | No | Trivial | Baseline |
| TF-IDF weighted mean | No | Trivial | Better on long phrases |
| SVD on term-document matrix | No | Low | Strong on small corpora |
| Concatenation | Partly | Low | Fixed length required |
| Trained recursive encoder | Yes | Moderate | Needs labels |
| Sequence encoder or transformer | Yes | High | Best available |
Visualisation without deceiving yourself
Projecting 300 dimensions down to two for a scatter plot is a lossy operation, and every method available â t-SNE, UMAP, PCA â distorts the geometry in a characteristic way. t-SNE preserves local neighbourhoods and destroys global structure, so clusters that look separated in the plot may be adjacent in the original space, and distances between clusters carry no meaning whatsoever. Cluster sizes in a t-SNE plot are an artefact of the perplexity parameter rather than a property of the data.
The defensible practice is to visualise only to form hypotheses, then verify each hypothesis numerically in the original space: compute the actual cosine, run a nearest-neighbour query, and report that number. A plot is a communication device for a result you have already established, not the establishment of it.
| Failure mode | What it looks like | Detection |
|---|---|---|
| Sense conflation | One vector for two meanings | Inspect neighbours for each sense |
| Frequency bias | Common words cluster centrally | Check norm against frequency |
| Arity collapse | Every word is equally similar to all | Examine the cosine distribution |
| OOV at serving | Crash or fallback on new terms | Measure OOV rate on real traffic |
| Projection artefact | Clusters that do not exist | Re-verify distances in full space |
| Analogy contamination | Inflated accuracy | Use filtered, deduplicated benchmarks |
đĄReport OOV rate with any embedding result
Common Mistakes
Reading analogy accuracy as a measure of reasoning
Fix: Much of the benchmark is solvable by plain similarity; use filtered sets and report the baseline.
Interpreting t-SNE cluster distances as meaningful
Fix: t-SNE destroys global geometry; verify every claim numerically in the original space.
Assuming a pretrained vocabulary covers your domain
Fix: Measure out-of-vocabulary rate on real traffic before committing, and compose subwords for the gaps.
Averaging two words to define a relation
Fix: Use group centroids over several words instead, which cancels idiosyncratic components.
Best Practices
- Probe a new embedding source with nearest neighbours before trusting any downstream score
- Report OOV coverage alongside every metric that depends on the vocabulary
- Prefer centroid comparisons over single-word offsets when testing a relation
- Validate anything a two-dimensional plot suggests directly in the original vector space
Interview Questions
Q1: What does the distributional hypothesis claim and why does it justify embeddings?
That a word's meaning is determined by the contexts it occurs in, so predicting context forces the model to place semantically similar words at nearby coordinates.
Q2: Why do word analogy benchmarks overestimate embedding quality?
A large share of questions are answerable by nearest-neighbour similarity alone, and the most frequent words dominate accuracy, so raw scores inflate without any genuine relational encoding.
Q3: How do you handle a word missing from a pretrained vocabulary?
Compose its vector from subwords if the model supports it, fall back to an out-of-vocabulary token otherwise, and measure the coverage rate on your real traffic.
Key Takeaways
- Dense vectors replace one-hot columns with a continuous space where similarity is geometric
- Embedding dimensions are latent: nothing is directly interpretable, so evaluation must be behavioural
- Analogy arithmetic shows a relation exists in the space but is a contaminated and weak benchmark
- Nearest-neighbour and centroid probes are the reliable ways to inspect what a vector encodes
- Sense conflation and vocabulary drift are the two structural limits of one-vector-per-word models