Skip to content
ml-recall

Topic notes

Text Representation & Embeddings

Turning words into vectors — one-hot and bag-of-words counts, embedding layers, word2vec (skip-gram, CBOW, negative sampling), GloVe, fastText subwords and contextual embeddings.

3-min read AI-checked

Practise 47 questions Take a test

Key ideas

Formulas

Worked example

Subsampling with t=10−4t = 10^{-4}: "the" makes up f=1%f = 1\% of the tokens, so each occurrence is dropped with probability 1−10−4/10−2=1−0.1=0.91 - \sqrt{10^{-4}/10^{-2}} = 1 - 0.1 = 0.9; a word with f≤10−4f \le 10^{-4} is never dropped.

Noise distribution: two words with counts 81 and 1 get weights 810.75=2781^{0.75} = 27 and 11, so the frequent word is drawn with probability 27/28≈0.96427/28 \approx 0.964 instead of 81/82≈0.98881/82 \approx 0.988.

In code

import torch
import torch.nn as nn

torch.manual_seed(0)
emb = nn.Embedding(num_embeddings=5, embedding_dim=3)       # |V| = 5, d = 3
ids = torch.tensor([2, 4])                                  # token ids, not strings
one_hot = nn.functional.one_hot(ids, num_classes=5).float()
print(torch.allclose(emb(ids), one_hot @ emb.weight))       # True: lookup = one-hot @ W
bag = nn.EmbeddingBag.from_pretrained(emb.weight, mode="mean")
print(bag(ids.unsqueeze(0)).shape)                          # torch.Size([1, 3]) for any length
print(torch.allclose(bag(ids.unsqueeze(0)), emb(ids).mean(0)))  # True

Common pitfalls

References

  1. Dive into Deep Learning — Sec. 15.1 Word Embedding (word2vec)
  2. Dive into Deep Learning — Sec. 15.2 Approximate Training (15.2.1 Negative Sampling, 15.2.2 Hierarchical Softmax)
  3. Dive into Deep Learning — Sec. 15.3.2 Subsampling and 15.3.4 Negative Sampling
  4. Dive into Deep Learning — Sec. 15.5 Word Embedding with Global Vectors (GloVe)
  5. Dive into Deep Learning — Sec. 15.6.1 The fastText Model
  6. Dive into Deep Learning — Sec. 15.8.1 From Context-Independent to Context-Sensitive
  7. PyTorch documentation: torch.nn.EmbeddingBag — Class description (mode "sum", "mean" or "max"; input = indices into the embedding matrix)
  8. Natural Language Processing with Deep Learning (Ruhr University Bochum, 2025/26) — Lecture 5 handout, frames 'Distributional hypothesis' and 'Limitations of word embeddings (1)' (antonyms)