Sub topic 2
You shall know a word by the company it keeps
This chapter assumes you can read basic Python, count items with collections.Counter, and think of a sentence as a list of tokens. You don't need any embedding math yet. The chapter covers the one idea behind everything that follows: a word's meaning can be approximated from the words that appear near it.
The idea in one sentence
The linguist J. R. Firth wrote in 1957: "You shall know a word by the company it keeps." The same idea is called the distributional hypothesis. It says that words used in similar contexts tend to have similar meanings.
Here is a quick test. Suppose you've never seen the word tezgüino, and you meet these sentences:
- A bottle of tezgüino is on the table.
- Everybody likes tezgüino.
- Tezgüino makes you drunk.
- We make tezgüino out of corn.
You can't look up a definition, but you can guess that it is an alcoholic drink made from corn. You inferred this because the contexts match those of words like beer or wine. A model can do the same with counts.
Why this matters for NLP
Earlier chapters showed that one-hot vectors treat every word as equally different from every other word. They carry no information about meaning. The distributional hypothesis gives us a source of that information that needs no human labelling. Raw text already contains it, because every sentence shows which words co-occur.
This makes the approach self-supervised. The training signal comes from the text itself. Both word2vec and GloVe, which later chapters cover, are different ways of compressing these context statistics into dense vectors.
What "company" means
"Company" has to be turned into something a program can count. The usual choice is a window: the words within a fixed number of positions to the left and right of the target word. A later chapter treats windows and training pairs in detail. For now, a window of 2 means we look at up to two words on each side.
There are other definitions of context:
| Context type | What counts as company | Typical effect |
|---|---|---|
| Small window (1–2 words) | Immediate neighbours | Captures syntactic and functional similarity, such as nouns that follow *the* |
| Large window (5–10 words) | Words in the same neighbourhood | Captures topical similarity, such as *hospital* with *doctor* |
| Whole sentence or document | Any word in the same text unit | Strongly topical, with little grammar |
| Syntactic neighbours | Words linked by a parse relation | Sharper functional similarity, but needs a parser |
The choice changes what "similar" means. A small window puts cat near dog, because both fill the same slots. A large window may put cat near fur and vet.
Counting company in code
This script collects, for each word, a count of the words that appear within two positions of it. Then it lists the context words that two words share.
from collections import Counter
sentences = [
"the cat drinks milk",
"the dog drinks water",
"the cat chases the mouse",
"the dog chases the cat",
"she drives the car",
"he drives the truck",
]
def context_counts(sentences, window=2):
contexts = {}
for sent in sentences:
tokens = sent.split()
for i, word in enumerate(tokens):
lo = max(0, i - window)
hi = min(len(tokens), i + window + 1)
for j in range(lo, hi):
if j != i:
contexts.setdefault(word, Counter())[tokens[j]] += 1
return contexts
ctx = context_counts(sentences)
def shared_contexts(a, b):
return sorted(set(ctx[a]) & set(ctx[b]))
print(shared_contexts("cat", "dog"))
print(shared_contexts("cat", "car"))The output is:
['chases', 'drinks', 'the']
['the']cat and dog share the verbs drinks and chases. cat and car share only the. Even in six sentences, the contexts separate animals from vehicles.
Notice that the appears in both lists. Frequent function words are shared by almost every word, so they say little about meaning. Real systems handle this with weighting or subsampling, which later chapters cover.
Common errors and gotchas
- Confusing "similar contexts" with "same meaning." Good and bad appear in nearly identical contexts ("a very good movie", "a very bad movie"). Distributional methods place them close together even though they are opposites. The hypothesis captures relatedness and substitutability, not synonymy.
- Using too little text. Context statistics are noisy when counts are small. The toy corpus above only works because we built it by hand. Real embeddings need millions or billions of tokens.
- Ignoring tokenization. If "Cat", "cat" and "cats" are separate tokens, their contexts split across three entries. Lowercasing and a consistent tokenizer matter before you count anything.
- Letting frequent words dominate. Raw counts overweight words like the and of. Without correction, they hide the informative contexts.
- Expecting one context definition to fit every task. If your task needs functional similarity, a large topical window can hurt. Treat window size as a setting you tune.
Where this leads
Raw context counts have one drawback. Each word's profile is as long as the vocabulary, so it is large and mostly zeros. The next chapters compress these profiles into short dense vectors. GloVe does this by fitting vectors to global co-occurrence counts. word2vec does it by training a model to predict context words. Both rest on the hypothesis you have just seen.
Exercise
In the toy corpus, add the sentence "the horse drinks water" and rerun shared_contexts("horse", "dog"). Predict the result before you run it. Then explain why "good" and "bad" would look similar to a purely distributional method.
Show answer
horse appears once, in "the horse drinks water", with contexts the, drinks and water. dog has the contexts the, drinks, water, chases and cat, so the shared list is ['drinks', 'the', 'water']. The sentence adds the same verb and object that dog already has. "Good" and "bad" occur in the same slots ("a very __ movie", "it was __"), so their context profiles overlap heavily. The method measures how words are used, not whether they mean the same thing, so antonyms that share usage patterns look similar.