Skip to main content
Quick Reference

NLP Cheatsheet

Natural language processing on one page — tokens, TF-IDF, embeddings, attention, and the traps around UNK, BLEU, and data leakage.

10 sections 10 tables 14 code snippets

Clean the text

Case

text = "Dune, 1965."
text.lower()

A whitespace split

text.split()

The first cuts

StepWhat it changes
NormalizeCase, punctuation, and Unicode. Lowercasing merges "US" and "us"
TokenizeThe units the model actually sees. A later step cannot recover a cut you made here
splitBreaks on whitespace. "Dune," stays one token, comma included
No spacesSome languages do not mark words with spaces, so a space split is the wrong tool
Case cuesNames and acronyms use case. Lowercase after a named-entity step, not before it
Stop wordsDropping "the" helps a bag of words. Dropping "not" can flip a sentiment label

This page is the ideas. spaCy pipelines, training loops, and hosted model APIs are left out.

Subword tokens

A continuation mark

pieces = ["un", "##believe", "##able"]

Apply a saved BPE

# replay the learned merges, in the learned order

How a vocabulary is built

MethodRule
Word tokensAn unseen word becomes one unknown token, and the spelling is discarded
BPE trainingStart from characters. Repeatedly merge the most frequent adjacent pair
BPE on new textReplay that saved merge list. Do not merge whatever is frequent in this one sentence
WordPieceMerges by a likelihood score, not the raw pair count. BERT marks a continuation with ##
SentencePieceReads raw text, spaces included. Unigram starts from a large vocab and deletes pieces
Byte-level BPEThe alphabet is the 256 bytes. An unseen character still has pieces. GPT-2 uses this

Counts and TF-IDF

Fit on the training docs

vec = TfidfVectorizer()
X = vec.fit_transform(train_docs)

What a count can see

PieceDetail
Bag of wordsOne count per term. Word order is gone, so "dog bites man" matches the reversed sentence
Term frequencyHow often the term appears in this document
Inverse document frequencyA term that appears in every document gets a low weight
TF-IDFA weight for search. It is not a meaning
Fit scopeFit on the training documents only. A fit before the split leaks test terms into the weights
transformApply the saved vocabulary to new documents. Unknown terms are ignored

Embeddings

Angle, not length

cosine_similarity(X[0], X[1])

One vector or many

KindDetail
Skip-gramWord2Vec. Predict the nearby words from the target word
CBOWPredict the target word from the nearby words
GloVeFactors a global table of how often words occur together
StaticOne vector per spelling. River and money share the vector for "bank"
ContextualThe same spelling gets a different vector in a different sentence
Cosine1 is the same direction. 0 is perpendicular. A zero vector has no angle

Tags and spans

One person span

tags = ["B-PER", "I-PER", "O"]

Label rules

TaskDetail
Part of speechA grammatical tag per token. A lemmatizer needs it
LemmaThe dictionary form. "better" as an adjective maps to "good"
StemSuffix rules. Fast, and the result can be a non-word
Named entitiesA span plus a type, such as person or place
IOBB starts a span, I continues it, O is outside. A bad boundary fails the span
ScoreToken accuracy looks high because most tags are O. Score the spans

Encoders and decoders

Hide the future

# a decoder token cannot read future tokens

Read both sides

# a BERT token can read the whole sentence

Which model

ModelTraining idea
n-gramThe next word depends on the previous few words. A longer history is a sparse table
EncoderBERT reads the whole sequence and fills in masked tokens
DecoderGPT predicts the next token. A causal mask hides future tokens
BothT5 and translation models encode the source, then decode the target
GreedyTake the best next token. The full sentence can still be worse
BeamKeep a few hypotheses. It raises the odds and still is not a proof of the best sentence

Attention

Scaled dot-product

scores = Q @ K.T / sqrt(d)
weights = softmax(scores)
out = weights @ V

What the three matrices do

PieceDetail
Q, K, VQuery, key, and value. In self-attention all three come from the same sequence
ScoreA dot product. Divide by the square root of the key size before the softmax
SoftmaxMakes weights that sum to 1. A huge dot product turns the row almost one-hot
CostEach position can look at every position. The work grows with the square of the length
Causal maskFuture scores are set to a large negative value, so their weight is 0
HeadsSeveral attentions run, then the results are concatenated. Heads can pick up different links

Tasks

Raw string equality

answer == "1965"

Match the task

TaskA fair check
ClassificationOne label for the text, such as sentiment or topic. Report per-class scores
Sequence labelsOne tag per token. Named entities are spans, not single tokens
SimilarityA model trained to score pairs. A raw class token is a weak similarity feature
TranslationNew text. Shared words with a reference are not the same as a correct meaning
SummarizationShorter text. Copying the source can score well and still add a false claim
Question answeringA span or a generated answer. Raw equality rejects a right answer with different words

Metrics

Fit and surprise

# lower perplexity means the text was more expected

Pick the number that matches

MetricWhat it rewards
AccuracyThe share of correct labels. A rare class can be ignored and the number stays high
PrecisionOf the predicted positives, how many are true
RecallOf the true positives, how many were found
F1The harmonic mean of precision and recall. Macro-F1 treats classes equally
BLEUTranslation n-gram precision, plus a penalty for a short output. A paraphrase can score low
ROUGESummary overlap with a reference. Copying the reference scores well
PerplexitySurprise on held-out text. Lower is a closer fit. Two tokenizers are not comparable

Interview traps

Traps worth memorising

TrapWhat happensPrefer
"Dune,".split()The comma stays glued to the wordA tokenizer that splits punctuation
Lowercase before namesThe case cue for a person or an acronym is goneKeep case until the entity step is done
Merge frequent pairs in this sentenceBPE on new text replays the saved listApply the learned merges in order
One unknown token per new wordThe spelling is discardedSubwords, or byte-level BPE
Bag of words on "dog bites man"The reversed sentence has the same countsAn n-gram, or a model that keeps order
fit_transform on every documentTest terms leak into the vocabulary and the IDFfit on train, transform on test
One vector for "bank"River and money are the same pointA contextual encoder
Token accuracy for entitiesThe outside tag dominates, so the score looks highSpan-level F1
A high BLEUThe words overlap a reference. The meaning can still be wrongA human check, or a metric trained on meaning
answer == "1965"An extra word or a different form failsA normalized match, then a check for paraphrases
Cosine with a zero vectorThe angle is undefinedSkip empty documents
Compare two perplexitiesA different tokenizer changes the numberCompare runs that share one tokenizer

Train weights, then apply them

vec.fit(train_docs)
X_test = vec.transform(test_docs)

Keep the negation

# "not" can flip the label, so leave it in

How to use this page: tokenize the way the model was trained, fit counts on the training set only, and pick a metric that matches the task. A high overlap score is not a proof that the meaning is right.