Skip to content
ML to LLMs
Cheat sheets

NLP representations

From bag-of-words and TF-IDF to static and contextual embeddings, with trade-offs.

RepresentationVectorCapturesMissesCost
Bag-of-words countssparse, one column per wordwhich words appearorder, meaning, synonymstiny
N-gramssparse, words + short phraseslocal phrases ("not good")long-range ordersmall, more features
TF-IDFsparse, counts × ln⁡(N/DF)\ln(N/\text{DF})distinctive wordsmeaning, synonymstiny
BM25sparse retrieval scoreterm relevance with saturation and length normalizationparaphrasestiny
Static embeddings (Word2Vec, GloVe)dense, one per wordsimilarity of usagecontext (one vector for "bank")small
Contextual embeddings (transformers)dense, one per token occurrencemeaning in contextneeds computelarger
Sentence embeddingsdense, one per textsemantic similarity of whole textsexact terms, numbersmoderate

Key formulas: TF-IDF(t,d)=TF(t,d)×ln⁡NDF(t)\text{TF-IDF}(t,d) = \text{TF}(t,d)\times\ln\frac{N}{\text{DF}(t)}; cos⁡(a,b)=a⋅b∥a∥∥b∥\cos(a,b) = \frac{a\cdot b}{\lVert a\rVert\lVert b\rVert}.

Preprocessing: tokenize; lowercase and normalize for classical models; keep negations; fit vocabularies on training data only. Transformers use their own tokenizer and need no stemming or stop-word removal.

Choosing: start with TF-IDF + logistic regression as the baseline; move to embeddings for semantic similarity or retrieval; use hybrid (BM25 + dense) search in RAG.

Lessons: From text to vectors · Word embeddings · Lab: TF-IDF