Learning path: Neural Networks from Scratch to Embeddings · Step 8 of 9
Embeddings: Words as Vectors, Cosine Similarity and nn.Embedding
Give every word a short list of numbers where close means similar. One-hot vs dense vectors, 20 real GloVe words on a map, cosine similarity (cat-dog 0.92, cat-car 0.36), king - man + woman, and nn.Embedding.
What you will learn
- Explain why one-hot vectors give words no meaning
- Load real GloVe word vectors and measure closeness with cosine similarity
- Do word maths: king - man + woman lands near queen
- Use nn.Embedding as a trainable lookup table in PyTorch
Before you start
- Basic Python, NumPy and pandas
- Loss and Backpropagation
A network only takes numbers, and our data is words. So every word needs a list of numbers of its own. The question is: which numbers? This article shows the naive answer, why it fails, and the answer neural networks use: embeddings.
One-hot words know nothing
The simplest way is one-hot: each word gets its own column, with a 1 in its own slot and zeros everywhere else. (A bag of words, as in Bag of Words with CountVectorizer, is built the same way: one column per word.)
import numpy as np
one_hot = np.eye(3) # cat, dog, car
print(one_hot)
def cosine(a, b):
n = np.linalg.norm(a) * np.linalg.norm(b)
return float(a @ b / n)
cat, dog, car = one_hot
print("cat vs dog:", cosine(cat, dog))
print("cat vs car:", cosine(cat, car))
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
cat vs dog: 0.0
cat vs car: 0.0
cosine measures how close two vectors are (more on it below). For one-hot, cat is exactly as far from dog as from car. That's not true in real life. And with 400,000 words, every vector would be 400,000 numbers long.
A city map of words
Picture a city with neighbourhoods: Pet Street, Garage Lane, Palace Hill. Words that mean similar things live in the same neighbourhood. Cat, dog and horse on Pet Street. Bus, truck and car on Garage Lane. King, queen and prince on Palace Hill. Close on the map means close in meaning.
Every word has an address. Cat's starts 0.45, -0.5, -0.54 and goes on for 50 numbers. A word's address is its vector, and the whole map is an embedding.
Who draws the map?
Nobody, by hand. Look at this sentence: "The ___ sat on the mat and purred." Cat fits perfectly, dog nearly fits, car doesn't fit at all. That's the word2vec idea: a small network reads millions of sentences, guesses the words around each word, and nudges each word's numbers a little at a time so its guesses improve. Words used in the same places end up with similar numbers.
20 real word vectors
We use pretrained GloVe vectors, learned from Wikipedia and news text: 400,000 words with 50 numbers each. The optional first cell of the notebook downloads them with gensim (a 66 MB download the first time):
# OPTIONAL: needs gensim and a 66 MB download the first time
import contextlib
import io
import gensim.downloader as api
import pandas as pd
with contextlib.redirect_stdout(io.StringIO()): # hides the download bar
glove = api.load("glove-wiki-gigaword-50")
print("vocabulary:", len(glove.key_to_index), "vector size:", glove.vector_size)
best = glove.most_similar(positive=["king", "woman"], negative=["man"], topn=1)
print("king - man + woman:", best[0][0], round(best[0][1], 2))
words = ['cat', 'dog', 'horse', 'cow', 'car', 'truck', 'bus', 'train', 'king', 'queen', 'prince', 'princess', 'man', 'woman', 'boy', 'girl', 'apple', 'banana', 'bread', 'pizza']
pd.DataFrame([glove[w] for w in words], index=words).round(5).to_csv("word_vectors_small.csv")
vocabulary: 400000 vector size: 50
king - man + woman: queen 0.85
That cell saves 20 of the words to word_vectors_small.csv, so everything below runs offline:
import numpy as np
import pandas as pd
import torch
from torch import nn
file = "word_vectors_small.csv"
vec = pd.read_csv(file, index_col=0)
print(vec.shape)
print(vec.loc["cat"].values[:6].round(2))
(20, 50)
[ 0.45 -0.5 -0.54 -0.02 0.22 0.55]
20 words, 50 numbers each. Those are the first six numbers of cat; 44 more follow.
20 real words, squeezed onto a map
50 numbers can't be drawn, so PCA squeezes them into 2:
from sklearn.decomposition import PCA
pca = PCA(n_components=2, random_state=42)
xy = pca.fit_transform(vec.values)
print(xy.shape)
for w, (x, y) in zip(vec.index, xy):
print(f"{w} {x:.2f} {y:.2f}")
(20, 2)
cat 0.21 0.83
dog -0.32 0.44
horse -0.15 -0.05
cow -0.71 1.39
car -2.23 -2.61
truck -3.08 -2.12
bus -2.17 -2.90
train -1.52 -2.65
king 2.81 0.65
queen 3.15 -0.07
prince 2.74 -0.08
princess 3.08 -0.30
man 0.97 -1.03
woman 1.42 -1.12
boy 0.91 -0.76
girl 1.24 -0.85
apple -1.52 2.43
banana -1.25 2.99
bread -1.79 3.55
pizza -1.79 2.28
Here are those 20 points drawn on a map:
The animals form one group and the food words another. The vehicles sit together, far from the rest. The royalty words sit right next to the people words. Nobody told GloVe these groups; they came only from reading text.
How close? Cosine similarity
Cosine similarity is a @ b divided by the two lengths. It checks whether two arrows point the same way: 1 means the same direction, 0 means unrelated.
v = lambda w: vec.loc[w].values
pairs = [("cat", "dog"), ("cat", "horse"),
("cat", "car"), ("car", "truck"),
("apple", "king")]
for a, b in pairs:
sim = cosine(v(a), v(b))
print(f"{a:>5} vs {b:<6} {sim:.2f}")
cat vs dog 0.92
cat vs horse 0.70
cat vs car 0.36
car vs truck 0.92
apple vs king 0.30
Cat and dog: 0.92. Cat and car: only 0.36. Car and truck: 0.92. Apple and king: 0.30. Exactly like our city map.
Maths with words: king - man + woman
Going from man to woman is one step in the space. Take the same step from king, and where do we land?
target = v("king") - v("man") + v("woman")
scores = {}
for w in vec.index:
if w not in ("king", "man", "woman"):
scores[w] = cosine(target, v(w))
top3 = pd.Series(scores).nlargest(3)
for w, s in top3.items():
print(f"{w:<8} {s:.2f}")
queen 0.86
prince 0.76
princess 0.75
Queen, with 0.86. We skip the three input words, then score every other word. Over all 400,000 GloVe words (the optional cell above), the answer is still queen, with 0.85. The step from man to woman really is a direction in the space.
nn.Embedding: a lookup table you can train
Inside a PyTorch network, an embedding is a table with one row per word. It starts with random numbers:
torch.manual_seed(42)
emb = nn.Embedding(num_embeddings=5, embedding_dim=3)
print(emb.weight.shape)
print(emb.weight.data)
torch.Size([5, 3])
tensor([[ 0.3367, 0.1288, 0.2345],
[ 0.2303, -1.1229, -0.1863],
[ 2.2082, -0.6380, 0.4617],
[ 0.2674, 0.5349, 0.8094],
[ 1.1103, -1.6898, -0.9890]])
ids = torch.tensor([0, 2])
print(emb(ids).detach())
print("trainable:", emb.weight.requires_grad)
tensor([[ 0.3367, 0.1288, 0.2345],
[ 2.2082, -0.6380, 0.4617]])
trainable: True
Pass word ids 0 and 2, and rows 0 and 2 come out. Nothing is calculated; it's just a lookup. Because the table is trainable, backpropagation can move every row, step by step, into a good map.
Common mistakes
- Comparing vectors from different embedding models. Each model draws its own map; the numbers only make sense inside one map.
- Using plain distance when you mean direction. Cosine compares directions; it ignores how long the arrows are.
- Forgetting to drop the input words in word maths. The notebook skips king, man and woman before scoring.
- Reading the 2-D PCA map as exact. It squeezes 50 numbers into 2; use cosine on the full vectors for real comparisons.
Quick recap
| Idea | Code | Example |
|---|---|---|
| One-hot has no meaning | np.eye(3) | cat vs dog 0.0, cat vs car 0.0 |
| Dense vectors | GloVe, 50 numbers per word | (20, 50) table |
| Cosine similarity | a @ b / (|a| |b|) | cat-dog 0.92, cat-car 0.36 |
| Word maths | king - man + woman | queen 0.86 |
| Trainable table | nn.Embedding(5, 3) | ids [0, 2] return rows 0 and 2 |
Next: with every word as a vector, how do you find the closest ones in a whole collection? See Similarity Search: Finding the Closest Vectors.
Try it yourself
Compute the cosine of boy and girl, and of boy and bread. Then try prince - man + woman.
The notebook and word_vectors_small.csv are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Convolutional Neural Networks (CNN) Basics: Filters, Feature Maps and Pooling
Next →Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Why Neural Networks: Pixels, One Neuron and Layers
Why pictures need neural networks: a handwritten digit is 784 numbers, one neuron is a weighted sum plus a bias and one small rule, and neurons stack into layers. Worked out on MNIST with NumPy.
The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax
Follow numbers through a tiny 3-2-3 network in NumPy: one matrix product per layer, ReLU inside, softmax at the end, and a count of every weight and bias.
Loss and Backpropagation: How Wrong, and Who Is to Blame
The loss says how wrong the network was; backpropagation says how much each weight is to blame. MSE and cross-entropy, the chain rule by hand on a two-weight chain, then the same gradients from PyTorch autograd.
The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
How training is organised: shuffle, cut into mini-batches, take one step per batch, repeat per epoch. Real MNIST runs compare three learning rates, SGD against Adam, and show the overfitting signal in the validation loss.