MLDay 40 of 50Deep Learning
Embeddings
Tokens as Vectors
To a word counter, "won" and "claim" are two unrelated columns. Learning that "won" means spam teaches it nothing about "claim". An embedding gives every word a short list of learned numbers, so words that do the same job end up close together.
The idea
A token is one unit of input: a word here, but it could be a product ID or a user ID. An embedding
is a learned vector for each token: numbers, such as 16. The vectors sit in a table with one row per
token in the vocabulary (the tokens the model knows). Each token gets an ID, and looking up the
token means reading its row. That's PyTorch's nn.Embedding.
The rows start random. Training nudges them like any other weight, through the same loop as D32. Tokens that push the loss the same way get pushed the same way, so they drift into the same direction.
A message has many words, but a classifier wants one vector. The simplest fix is mean pooling: average
the rows of the message's words. A linear layer then turns that average into a spam score. nn.EmbeddingBag
does the lookup and the average in one step.
Close means "pointing the same way", measured by cosine similarity. And an average forgets word order: "dog bites man" and "man bites dog" get the same vector.
A tiny example
Here's a table with four words and :
| Word | Vector |
|---|---|
| won | (2, 1) |
| cash | (4, 1) |
| later | (−2, 3) |
| home | (0, 3) |
Score each message with a linear layer of weights (1, −1) and no bias: dimension 1 minus dimension 2:
| Message | Mean vector | Score | (spam) |
|---|---|---|---|
| won cash | (3, 1) | 3 − 1 = 2 | 0.88 |
| home later | (−1, 3) | −1 − 3 = −4 | 0.02 |
| cash home | (2, 2) | 2 − 2 = 0 | 0.50 |
The score becomes a probability through the sigmoid from D12. "later home" gets the same mean as "home later", so the same score.
The formula
The table holds one row of numbers per token:
| Symbol | Meaning |
|---|---|
| the vocabulary size: how many tokens get a row | |
| the embedding size: numbers per token |
Worked: and give weights.
Cosine similarity compares two vectors by their angle alone:
| Symbol | Meaning |
|---|---|
| two token vectors | |
| the dot product: multiply matching numbers, then add | |
| the vector's length, | |
| 1 means the same direction, 0 a right angle, −1 opposite |
Worked, won and cash: . Won and later: .
Try it
Move 'claim' to where it belongs
Each word is a vector: an arrow from the origin to its point. Cosine similarity compares directions only: 1 means the same direction, 0 a right angle, −1 opposite. Drag a point and watch the numbers change.
cos(prize, claim) = -0.22nearest to prize: won (0.96), txt (0.95), cash (0.94)nearest to claim: home (1), later (0.99), tomorrow (0.93)
"claim" starts among the chatty words, at a cosine of −0.22 with "prize". Drag it into the spam group on the right: the cosine climbs to about 1.0, and its nearest neighbours become prize, won and cash or txt. "call" sits between the groups, because friends and spammers both say it.
In code
The real task is Day 22's: the same deduplicated messages and the same stratified split. A slice of the training messages is set aside for validation, to pick the number of epochs. Each message becomes a row of word IDs, padded with 0s.
# script_id: day_040_embeddings/spam_bag
import copy
import os
from pathlib import Path
import pandas as pd
import torch
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
df = pd.read_csv(DATA_DIR / "sms_spam" / "SMSSpamCollection", sep="\t", header=None,
names=["label", "text"], quoting=3).drop_duplicates("text")
y = (df["label"] == "spam").astype(int)
X_train, X_test, y_train, y_test = train_test_split( # Day 22's split
df["text"], y, test_size=0.2, stratify=y, random_state=42)
X_fit, X_val, y_fit, y_val = train_test_split( # validation, from training only
X_train, y_train, test_size=0.2, stratify=y_train, random_state=42)
vec = CountVectorizer(min_df=5).fit(X_fit) # words in 5+ training messages
words = ["<pad>", *vec.get_feature_names_out()] # ID 0 is padding
word_id = {w: i for i, w in enumerate(words)}
tokens = vec.build_analyzer() # Day 20's word splitter
def encode(texts, length: int = 160) -> torch.Tensor:
ids = torch.zeros(len(texts), length, dtype=torch.long) # 0s pad short messages
for row, text in enumerate(texts):
known = [word_id[w] for w in tokens(text) if w in word_id] # unknown words are dropped
ids[row, :len(known)] = torch.tensor(known, dtype=torch.long)
return ids
X_fit_ids, X_val_ids, X_test_ids = encode(X_fit), encode(X_val), encode(X_test)
print(f"V = {len(words):,}; {len(X_fit):,} fit, {len(X_val)} validation, {len(X_test):,} test messages")
print(tokens(X_fit.iloc[0])[:5], "->", X_fit_ids[0, :5].tolist())
print("test messages with no known word:", int((X_test_ids == 0).all(dim=1).sum()))
V = 1,213; 3,308 fit, 828 validation, 1,035 test messages
['got', 'like', 'lt', 'gt', 'can'] -> [439, 587, 615, 444, 195]
test messages with no known word: 10
The model is the table plus one linear layer. padding_idx=0 keeps the padding out of the average. The
loss is log loss on the raw score (D33). Adam
runs at lr=1e-2, ten times Phase 4's usual step: each word is in few messages, so its row gets few
updates. At 1e-3, eight epochs leave the validation loss at 0.29. The loop keeps the epoch with the lowest validation loss (early stopping, from
D25).
# script_id: day_040_embeddings/spam_bag
torch.manual_seed(42)
model = nn.Sequential(
nn.EmbeddingBag(len(words), 16, mode="mean", padding_idx=0), # V x 16 table; mean of the rows
nn.Linear(16, 1), nn.Flatten(0)) # one spam score per message
print("table:", tuple(model[0].weight.shape), "=", model[0].weight.numel(), "weights")
loader = DataLoader(TensorDataset(X_fit_ids, torch.tensor(y_fit.to_numpy(), dtype=torch.float32)),
batch_size=64, shuffle=True, generator=torch.Generator().manual_seed(42))
loss_fn = nn.BCEWithLogitsLoss() # sigmoid + log loss in one step
optimizer = torch.optim.Adam(model.parameters(), lr=1e-2)
y_val_t = torch.tensor(y_val.to_numpy(), dtype=torch.float32)
best = float("inf")
for epoch in range(1, 9):
model.train()
for xb, yb in loader:
loss = loss_fn(model(xb), yb)
loss.backward()
optimizer.step()
optimizer.zero_grad()
model.eval()
with torch.no_grad():
val_loss = loss_fn(model(X_val_ids), y_val_t).item()
print(f"epoch {epoch}: validation loss {val_loss:.4f}")
if val_loss < best:
best, best_state = val_loss, copy.deepcopy(model.state_dict())
model.load_state_dict(best_state)
table: (1213, 16) = 19408 weights
epoch 1: validation loss 0.2452
epoch 2: validation loss 0.1124
epoch 3: validation loss 0.0810
epoch 4: validation loss 0.0735
epoch 5: validation loss 0.0705
epoch 6: validation loss 0.0710
epoch 7: validation loss 0.0721
epoch 8: validation loss 0.0736
The model from epoch 5 is kept. Now score the test messages once, next to Day 22's two models, refitted on all the training messages. PR-AUC is Day 13's area under the precision-recall curve.
# script_id: day_040_embeddings/spam_bag
with torch.no_grad():
scores = {"Embedding bag": torch.sigmoid(model(X_test_ids)).numpy()}
for name, pipe in {"Naive Bayes": make_pipeline(CountVectorizer(), MultinomialNB()),
"TF-IDF + LogReg": make_pipeline(TfidfVectorizer(), LogisticRegression())}.items():
scores[name] = pipe.fit(X_train, y_train).predict_proba(X_test)[:, 1]
for name, p in scores.items():
print(f"{name:<16} test PR-AUC {average_precision_score(y_test, p):.3f}")
Embedding bag test PR-AUC 0.946
Naive Bayes test PR-AUC 0.965
TF-IDF + LogReg test PR-AUC 0.954
The embedding bag comes last, though not by much. It also trained on fewer messages: 3,308, not 4,136, since the rest picked the epoch. On a few thousand short messages, plain word counts are hard to beat. The bag's real gain is the vectors themselves. Here are each word's nearest neighbours by cosine:
# script_id: day_040_embeddings/spam_bag
table = nn.functional.normalize(model[0].weight.detach(), dim=1) # every row scaled to length 1
for w in ["won", "txt", "later", "tomorrow"]:
cos = table @ table[word_id[w]] # cosine with every word
cos[word_id[w]] = -1 # skip the word itself
print(f"{w:<9}", ", ".join(f"{words[i]} {cos[i]:.2f}" for i in cos.topk(4).indices))
pair = ["call now to claim your prize", "your prize to claim now call"]
with torch.no_grad():
print("same words, new order:", torch.sigmoid(model(encode(pair))).numpy().round(4))
won claim 0.86, http 0.82, delivery 0.79, charged 0.79
txt content 0.80, mob 0.79, standard 0.79, won 0.78
later plans 0.80, too 0.79, dead 0.77, movie 0.75
tomorrow probably 0.80, staying 0.76, in 0.75, wants 0.72
same words, new order: [0.9975 0.9975]
The spam words found each other, and so did the chatty ones. But "later" sits next to "dead", not "soon". The only signal was spam or not, so the vectors learned how spammy a word is, not what it means. The scrambled message scores exactly the same.
Quick check
Quick check
1. Word A's vector is (1, 1) and word B's is (3, 3). What is their cosine similarity?
2. Why do 'call now to claim your prize' and 'your prize to claim now call' get the same score?
3. After training on spam vs. not spam, 'later' sits close to 'dead'. Why?
Next
D41: Self-Attention from Scratch lets each word's vector change with the words around it, so order and context count again.
Data: SMS Spam Collection v.1 (UCI Machine Learning Repository, dataset 228), CC BY 4.0; cite Almeida, T. A., Gómez Hidalgo, J. M. and Yamakami, A. (2011), "Contributions to the Study of SMS Spam Filtering: New Collection and Results", Proceedings of the 2011 ACM Symposium on Document Engineering.