Robot AI -- Natural Language Processing

Memory tricks that make tokenization, BERT and LLMs click

From bag-of-words to transformer language models -- these memory tricks lock in the NLP pipeline, text representations, core tasks, and the prompt engineering that makes LLMs useful.

Community
📋
NLP Forum
Ask questions · Share tricks
💬
NLP Study Room
Live · Study together now

Or continue to the sub-topics below for more specialized Study Rooms and Forums

Natural Language Processing

Memory Tricks

Proven Mnemonics & Acronyms — fast to learn, hard to forget.

🎥 How Flashcards Work
A quick walkthrough of tap-to-flip, rating, and how card colors track what you're struggling with.
← Back Next →
NLP deck1 of 20
Tap to flip
← →
How well do YOU think you know this?
Easy Medium Hard Harder
Tap to flip back
NLP deck
Easy0
Medium0
Hard0
Harder0
NLP Pipeline
NLP PIPELINE -- Tokenize, Normalize, Represent, Model, Evaluate
RAW TEXT TO PREDICTIONS IN FIVE STEPS
Modern LLMs skip most preprocessing -- trained end-to-end with BPE subword tokenization
Tokenization: split into tokens. Normalization: lowercase, punctuation, contractions. Stop word removal: remove high-frequency low-information words. Stemming/Lemmatization: reduce to root form. Representation: convert to numerical vectors (BoW, TF-IDF, embeddings). Model: ML or DL algorithm. Evaluate: task-specific metric.
Tokenization
Split text into words, subwords, or characters
Normalization
Lowercase, punctuation handling, contraction expansion
Lemmatization
Returns actual dictionary base form (better than stemming)
Modern LLMs
Skip most preprocessing -- end-to-end with BPE tokenization
🎥 Watch Instead
▶
Video coming soon
This lesson's animated video hasn't been made yet — check back soon.
Flashcard
🃏 NLP Pipeline
NLP pipeline — the five steps?
Tap to flip
🃏 Answer
NLP PIPELINE -- Tokenize, Normalize, Represent, Model, Evaluate
TokenizationSplit text into words, subwords, or characters
NormalizationLowercase, punctuation handling, contraction expansion
LemmatizationReturns actual dictionary base form (better than stemming)
Modern LLMsSkip most preprocessing -- end-to-end with BPE tokenization
Tap to flip back
Text Representation
BOW to TF-IDF to Word2Vec to BERT -- from counting words to understanding meaning
FOUR GENERATIONS OF TEXT REPRESENTATION -- EACH MORE POWERFUL
BERT gives same word different vectors based on context -- bank in finance vs bank of river
Bag of Words (BoW): word counts, ignores order and context, sparse. TF-IDF: weights rare domain terms higher, still sparse. Word2Vec/GloVe: dense semantic vectors, king - man + woman = queen, fixed per word. BERT / contextual embeddings: same word gets different embedding based on surrounding context. All modern NLP uses contextual embeddings.
BoW
Word counts -- sparse, ignores order and context
TF-IDF
Weights rare words higher -- still sparse but smarter
Word2Vec
Dense semantic vectors -- arithmetic works, but context-free
BERT / contextual
Same word, different vector based on context -- most powerful
🎥 Watch Instead
▶
Video coming soon
This lesson's animated video hasn't been made yet — check back soon.
Flashcard
🃏 Text Representation
Text representation — BoW to TF-IDF to Word2Vec to BERT?
Tap to flip
🃏 Answer
BOW to TF-IDF to Word2Vec to BERT -- from counting words to understanding meaning
BoWWord counts -- sparse, ignores order and context
TF-IDFWeights rare words higher -- still sparse but smarter
Word2VecDense semantic vectors -- arithmetic works, but context-free
BERT / contextualSame word, different vector based on context -- most powerful
Tap to flip back
BERT vs GPT
BERT reads the whole sentence (bidirectional). GPT reads left-to-right only.
ENCODER FOR UNDERSTANDING -- DECODER FOR GENERATION
BERT cannot generate text. GPT cannot see the right context. Both are excellent at what they do.
BERT (Encoder-only, Bidirectional): sees entire sequence simultaneously, trained on masked language modeling, excellent for classification, NER, question answering, cannot generate text. GPT (Decoder-only, Autoregressive): sees only left context, trained on next-token prediction, excellent for text generation, creative writing, code, conversation. T5/BART: Encoder-Decoder -- best for translation and summarization.
BERT encoder-only
Bidirectional, masked LM, understanding tasks: classification, NER, QA
GPT decoder-only
Left-context only, next-token prediction, generation tasks
T5 and BART
Encoder-Decoder -- translation, summarization, seq2seq tasks
Why GPT dominates now
Scale + emergent few-shot abilities -- can do BERT tasks via prompting
🎥 Watch Instead
▶
Video coming soon
This lesson's animated video hasn't been made yet — check back soon.
Flashcard
🃏 BERT vs GPT
BERT vs GPT — how does each read text?
Tap to flip
🃏 Answer
BERT reads the whole sentence (bidirectional). GPT reads left-to-right only.
BERT encoder-onlyBidirectional, masked LM, understanding tasks: classification, NER, QA
GPT decoder-onlyLeft-context only, next-token prediction, generation tasks
T5 and BARTEncoder-Decoder -- translation, summarization, seq2seq tasks
Why GPT dominates nowScale + emergent few-shot abilities -- can do BERT tasks via prompting
Tap to flip back
Tokenization (BPE)
BPE -- Byte Pair Encoding: merge the most frequent character pair, repeat until vocabulary size reached
NO TRUE OUT-OF-VOCABULARY WORDS WITH SUBWORD TOKENIZATION
750 English words is approximately 1000 tokens -- other languages use more tokens per word
BPE Algorithm: start with character vocabulary, count all character pairs, merge most frequent into new token, repeat until target vocabulary size. Result: common words as single tokens, rare words split into subword units. No true OOV words -- any word can be handled. GPT models: 50K-100K token vocabulary. Token count affects cost, speed, and context window utilization.
BPE algorithm
Merge most frequent character pairs iteratively until target vocab size
No OOV words
Any word can be split into known subword units
Token counting
750 English words ~ 1000 tokens. Other languages: more tokens per word.
Vocabulary size
GPT models: 50K-100K token vocabulary
🎥 Watch Instead
▶
Video coming soon
This lesson's animated video hasn't been made yet — check back soon.
Flashcard
🃏 Tokenization (BPE)
BPE tokenization — how does it build a vocabulary?
Tap to flip
🃏 Answer
BPE -- Byte Pair Encoding: merge the most frequent character pair, repeat until vocabulary size reached
BPE algorithmMerge most frequent character pairs iteratively until target vocab size
No OOV wordsAny word can be split into known subword units
Token counting750 English words ~ 1000 tokens. Other languages: more tokens per word.
Vocabulary sizeGPT models: 50K-100K token vocabulary
Tap to flip back
Prompt Engineering
CLEAR -- Context, Length, Examples, Ask specifically, Role assignment
BETTER PROMPT = BETTER OUTPUT -- PROMPT ENGINEERING IS A SKILL
Chain-of-Thought: adding Let's think step by step dramatically improves reasoning accuracy
Zero-shot: just ask -- no examples. Few-shot: provide 2-5 examples of desired format. Chain-of-Thought (CoT): add Let's think step by step -- improves math, logic, multi-step reasoning. Role prompting: Act as an expert... -- calibrates vocabulary, depth, style. Structured output: Respond in JSON format. RAG: retrieve context to ground LLM in real facts and reduce hallucination.
Zero-shot
Just ask -- no examples needed for simple clear tasks
Few-shot
Give 2-5 examples -- improves consistency and format
Chain-of-Thought
Let's think step by step -- dramatic improvement on reasoning
RAG
Retrieve documents, inject as context -- reduces hallucination
🎥 Watch Instead
▶
Video coming soon
This lesson's animated video hasn't been made yet — check back soon.
Flashcard
🃏 Prompt Engineering
Prompting (CLEAR) — the five elements?
Tap to flip
🃏 Answer
CLEAR -- Context, Length, Examples, Ask specifically, Role assignment
Zero-shotJust ask -- no examples needed for simple clear tasks
Few-shotGive 2-5 examples -- improves consistency and format
Chain-of-ThoughtLet's think step by step -- dramatic improvement on reasoning
RAGRetrieve documents, inject as context -- reduces hallucination
Tap to flip back
NLP Evaluation
BLEU scores translation -- ROUGE scores summaries -- Perplexity scores language models
DIFFERENT TASKS NEED DIFFERENT EVALUATION METRICS
BLEU measures n-gram overlap -- it misses semantic equivalents like automobile vs car
BLEU: n-gram overlap between generated and reference translations. Range 0-1. Correlates with human judgment but misses semantic equivalents. ROUGE: n-gram overlap for summarization. ROUGE-1 (unigrams), ROUGE-2 (bigrams), ROUGE-L (longest common subsequence). Perplexity: how well LM predicts test set -- lower is better. BERTScore: uses embeddings for semantic similarity -- better than n-gram metrics.
BLEU
N-gram overlap for translation -- misses semantic equivalents
ROUGE
N-gram overlap for summarization -- ROUGE-1, ROUGE-2, ROUGE-L
Perplexity
How surprised LM is by test text -- lower = better LM
BERTScore
Semantic similarity via embeddings -- better than BLEU/ROUGE
🎥 Watch Instead
▶
Video coming soon
This lesson's animated video hasn't been made yet — check back soon.
Flashcard
🃏 NLP Evaluation
BLEU vs ROUGE vs perplexity — what does each score?
Tap to flip
🃏 Answer
BLEU scores translation -- ROUGE scores summaries -- Perplexity scores language models
BLEUN-gram overlap for translation -- misses semantic equivalents
ROUGEN-gram overlap for summarization -- ROUGE-1, ROUGE-2, ROUGE-L
PerplexityHow surprised LM is by test text -- lower = better LM
BERTScoreSemantic similarity via embeddings -- better than BLEU/ROUGE
Tap to flip back
Machine Translation
ENCODE source then ATTEND to relevant parts then DECODE to target language
FROM RULE-BASED TO STATISTICAL TO NEURAL TO TRANSFORMER
Parallel corpora are needed for training -- back-translation helps low-resource languages
History: Rule-based (1950s-80s), Statistical phrase-based (1990s-2010s), Neural (2014 -- seq2seq + attention), Transformer (2017 -- surpassed all previous). Modern LLMs competitive for most language pairs. Parallel corpora: same content in two languages needed for training. Back-translation: translate target to source synthetically, use as additional training data.
Rule-based
Hand-crafted grammar rules -- limited coverage
Statistical (SMT)
Phrase-based, learns from parallel corpora
Neural (NMT)
Encoder-decoder + attention -- first major DL NLP breakthrough
Transformer (2017)
Surpassed RNN systems immediately -- now the standard
🎥 Watch Instead
▶
Video coming soon
This lesson's animated video hasn't been made yet — check back soon.
Flashcard
🃏 Machine Translation
Machine translation — how did it evolve?
Tap to flip
🃏 Answer
ENCODE source then ATTEND to relevant parts then DECODE to target language
Rule-basedHand-crafted grammar rules -- limited coverage
Statistical (SMT)Phrase-based, learns from parallel corpora
Neural (NMT)Encoder-decoder + attention -- first major DL NLP breakthrough
Transformer (2017)Surpassed RNN systems immediately -- now the standard
Tap to flip back
Information Retrieval
SPARSE uses keywords -- DENSE uses meaning -- HYBRID uses both
BM25 FOR EXACT TERMS AND SEMANTIC SEARCH FOR MEANING -- COMBINE FOR BEST RESULTS
RAG: retrieve top-K chunks and inject into LLM prompt to ground answers in real facts
Sparse retrieval (BM25, TF-IDF): keyword matching -- fast, interpretable, handles exact terms (names, codes). Dense retrieval: semantic embedding similarity -- finds relevant documents even if keywords differ. Two-stage: BM25 narrows candidates (fast), dense re-ranks (accurate). RAG pipeline: embed documents, store in vector DB, retrieve top-K, inject into LLM prompt.
BM25
Keyword matching -- fast, exact terms, still a strong baseline
Dense retrieval
Semantic embeddings -- finds synonyms and paraphrases
Two-stage pipeline
BM25 narrows, dense re-ranks -- best of both worlds
RAG
Retrieve top-K chunks, inject as LLM context, cite sources
🎥 Watch Instead
▶
Video coming soon
This lesson's animated video hasn't been made yet — check back soon.
Flashcard
🃏 Information Retrieval
Sparse vs dense vs hybrid retrieval?
Tap to flip
🃏 Answer
SPARSE uses keywords -- DENSE uses meaning -- HYBRID uses both
BM25Keyword matching -- fast, exact terms, still a strong baseline
Dense retrievalSemantic embeddings -- finds synonyms and paraphrases
Two-stage pipelineBM25 narrows, dense re-ranks -- best of both worlds
RAGRetrieve top-K chunks, inject as LLM context, cite sources
Tap to flip back
Speech Recognition
ASR = Acoustic Signal to Recognition to transcript -- convert audio to text
WHISPER IS OPEN SOURCE AND NEAR-HUMAN ACCURACY ON ENGLISH
WER = (Substitutions + Deletions + Insertions) / Total words -- lower is better
ASR pipeline: audio signal to features (mel spectrogram) to model to text. Traditional: acoustic model + pronunciation dictionary + language model. Modern end-to-end: CTC or attention encoder-decoder. Whisper (OpenAI 2022): trained on 680K hours of multilingual audio, near-human on English, open-source and free to run locally. WER (Word Error Rate): standard evaluation metric.
Traditional ASR
Acoustic model + pronunciation dictionary + language model
End-to-end (CTC)
Directly map audio features to character sequences
Whisper
680K training hours, multilingual, near-human WER, open-source
WER formula
(Substitutions + Deletions + Insertions) / Total reference words
🎥 Watch Instead
▶
Video coming soon
This lesson's animated video hasn't been made yet — check back soon.
Flashcard
🃏 Speech Recognition
ASR
Tap to flip
🃏 Answer
ASR = Acoustic Signal to Recognition to transcript -- convert audio to text
Traditional ASRAcoustic model + pronunciation dictionary + language model
End-to-end (CTC)Directly map audio features to character sequences
Whisper680K training hours, multilingual, near-human WER, open-source
WER formula(Substitutions + Deletions + Insertions) / Total reference words
Tap to flip back
Coreference
COREFERENCE -- John told Mary he liked her -- who is he and who is her?
IDENTIFY WHICH WORDS IN A TEXT REFER TO THE SAME REAL-WORLD ENTITY
Winograd Schema Challenge: The trophy does not fit because it is too big -- what is too big?
Coreference resolution identifies expressions referring to the same entity. Types: pronouns (he, she, it), noun phrases (the president), proper names (John). Challenge: requires world knowledge and reasoning. Example: The city council refused the protesters a permit because they feared violence -- they = city council, not protesters. Applications: reading comprehension, information extraction, summarization.
Pronouns
He, she, it, they -- must resolve to named entities
Noun phrases
The president, the company -- track across long documents
Winograd Schema
Tests common-sense reasoning for coreference resolution
Applications
Reading comprehension, information extraction, summarization
🎥 Watch Instead
▶
Video coming soon
This lesson's animated video hasn't been made yet — check back soon.
Flashcard
🃏 Coreference
Coreference resolution — what does it solve?
Tap to flip
🃏 Answer
COREFERENCE -- John told Mary he liked her -- who is he and who is her?
PronounsHe, she, it, they -- must resolve to named entities
Noun phrasesThe president, the company -- track across long documents
Winograd SchemaTests common-sense reasoning for coreference resolution
ApplicationsReading comprehension, information extraction, summarization
Tap to flip back
Text Generation Decoding
GREEDY picks top token -- SAMPLING picks randomly -- TEMPERATURE controls creativity
TOP-P NUCLEUS SAMPLING IS THE STANDARD IN PRODUCTION LLM APPLICATIONS
Top-P (nucleus sampling): sample from smallest set of tokens whose cumulative probability exceeds P
Greedy: always pick highest probability token -- deterministic, fast, repetitive. Sampling: randomly sample from distribution -- diverse but can be incoherent. Temperature: below 1 = sharper (conservative), above 1 = flatter (creative). Top-K: sample from top K tokens only. Top-P (nucleus): sample from smallest token set with cumulative probability above P -- adapts to distribution shape, most widely used. Repetition penalty: downweight already-generated tokens.
Greedy
Always pick highest prob -- deterministic but repetitive
Temperature < 1
Sharper distribution -- more conservative, predictable
Temperature > 1
Flatter distribution -- more creative, sometimes incoherent
Top-P (nucleus)
Most widely used -- adapts to actual distribution shape
🎥 Watch Instead
▶
Video coming soon
This lesson's animated video hasn't been made yet — check back soon.
Flashcard
🃏 Text Generation Decoding
Decoding — greedy vs sampling vs temperature?
Tap to flip
🃏 Answer
GREEDY picks top token -- SAMPLING picks randomly -- TEMPERATURE controls creativity
GreedyAlways pick highest prob -- deterministic but repetitive
Temperature < 1Sharper distribution -- more conservative, predictable
Temperature > 1Flatter distribution -- more creative, sometimes incoherent
Top-P (nucleus)Most widely used -- adapts to actual distribution shape
Tap to flip back
🎯 Exam Favorite
TOKENIZATION = Chopping a SENTENCE into LEGO BRICKS before the model reads it
TEXT IN → TOKENS OUT → MODEL READS
Tokenization — the first step in all NLP
Before any NLP model reads text, it must be tokenized — split into tokens. Tokens can be words, subwords, or characters depending on the tokenizer. "unhappiness" might become ["un", "happy", "ness"] — three tokens. Why subwords? They handle rare words and new words gracefully. GPT uses byte-pair encoding (BPE). A typical paragraph becomes 100–150 tokens. Everything in an LLM is measured in tokens — context windows, costs, limits.
🎥 Watch Instead
▶
Video coming soon
This lesson's animated video hasn't been made yet — check back soon.
Flashcard
🃏 🎯 Exam Favorite
Tokenization — what does it do?
Tap to flip
🃏 Answer
TOKENIZATION = Chopping a SENTENCE into LEGO BRICKS before the model reads it
TEXT IN → TOKENS OUT → MODEL READS
Tap to flip back
🧠 Vivid Story
WORD EMBEDDINGS = Giving every word an ADDRESS in a city where similar words live close together
KING − MAN + WOMAN ≈ QUEEN
Word embeddings — meaning as location in space
Word embeddings map each word to a point in high-dimensional space (e.g., 300 numbers). Similar words cluster together — "king" and "queen" are close. The magic: vector arithmetic captures meaning. King − Man + Woman ≈ Queen. Paris − France + Italy ≈ Rome. The model doesn't understand meaning — it learns that words appearing in similar contexts get similar coordinates. Word2Vec, GloVe, and modern contextual embeddings (BERT) all work on this principle.
🎥 Watch Instead
▶
Video coming soon
This lesson's animated video hasn't been made yet — check back soon.
Flashcard
🃏 🧠 Vivid Story
Word embeddings — the city of addresses
Tap to flip
🃏 Answer
WORD EMBEDDINGS = Giving every word an ADDRESS in a city where similar words live close together
KING − MAN + WOMAN ≈ QUEEN
Tap to flip back
🔑 Key Distinction
BERT reads BOTH DIRECTIONS — GPT reads LEFT TO RIGHT only
BIDIRECTIONAL vs AUTOREGRESSIVE
BERT vs GPT — two fundamentally different Transformer approaches
Both BERT and GPT are Transformer-based but trained differently. BERT: trained by masking random words and predicting them using context from both left AND right — bidirectional. Best for understanding tasks (classification, named entity recognition, question answering). GPT: trained to predict the next word reading left to right — autoregressive. Best for generation tasks (writing, completing text, chatting). BERT is the reader; GPT is the writer.
🎥 Watch Instead
▶
Video coming soon
This lesson's animated video hasn't been made yet — check back soon.
Flashcard
🃏 🔑 Key Distinction
BERT vs GPT — which direction does each read?
Tap to flip
🃏 Answer
BERT reads BOTH DIRECTIONS — GPT reads LEFT TO RIGHT only
BIDIRECTIONAL vs AUTOREGRESSIVE
Tap to flip back
💡 Concept Anchor
NAMED ENTITY RECOGNITION = The model HIGHLIGHTS the nouns that ARE something — people, places, orgs
NER — FIND THE WHO, WHERE, AND WHAT
Named Entity Recognition (NER) — finding the important nouns
NER identifies and classifies named entities in text: People (Barack Obama), Organizations (Google, WHO), Locations (Paris, Antarctica), Dates (March 12, 2024), and more. It's one of NLP's most practical tasks — used in news analysis, medical records, financial documents, and search engines. A sentence like "Apple announced in Cupertino that Tim Cook signed a deal with Samsung" yields: Apple (ORG), Cupertino (LOC), Tim Cook (PERSON), Samsung (ORG).
🎥 Watch Instead
▶
Video coming soon
This lesson's animated video hasn't been made yet — check back soon.
Flashcard
🃏 💡 Concept Anchor
Named entity recognition — what does it find?
Tap to flip
🃏 Answer
NAMED ENTITY RECOGNITION = The model HIGHLIGHTS the nouns that ARE something — people, places, orgs
NER — FIND THE WHO, WHERE, AND WHAT
Tap to flip back
📅 Quick Reference
RAG = OPEN BOOK EXAM — the model looks things up before answering instead of relying on memory
RETRIEVE · AUGMENT · GENERATE
Retrieval-Augmented Generation — why it reduces hallucinations
RAG gives LLMs access to a knowledge base at inference time. Instead of relying purely on memorized training data: Retrieve relevant documents from a database, Augment the prompt with that retrieved context, Generate an answer grounded in the retrieved facts. Result: far fewer hallucinations, up-to-date answers, and citations. Think of it as the difference between a closed-book exam (pure LLM) and an open-book exam (RAG). Most enterprise AI systems use RAG.
🎥 Watch Instead
▶
Video coming soon
This lesson's animated video hasn't been made yet — check back soon.
Flashcard
🃏 📅 Quick Reference
RAG — the open-book exam
Tap to flip
🃏 Answer
RAG = OPEN BOOK EXAM — the model looks things up before answering instead of relying on memory
RETRIEVE · AUGMENT · GENERATE
Tap to flip back
⭐ Most Important
TOKENIZE → EMBED → ENCODE → DECODE → GENERATE — the complete NLP pipeline
FIVE STAGES FROM RAW TEXT TO FINAL OUTPUT
The modern NLP pipeline end to end
Every modern NLP system follows this pipeline: Tokenize (split raw text into tokens — subwords), Embed (map each token to a dense vector), Encode (run through transformer layers to build contextual representations — BERT-style), Decode (generate output tokens one at a time — GPT-style), Generate (apply sampling strategy — greedy, beam search, temperature). Understanding each stage lets you diagnose failures: garbled output could be tokenizer, poor coherence could be decoding strategy.
Tokenize
Raw text → token IDs using a learned vocabulary (BPE, WordPiece)
Embed
Token IDs → dense vectors + positional encoding
Encode/Decode
Transformer layers build or generate representations
Generate
Sampling strategy converts logits to final token choices
🐍 Code
from transformers import AutoTokenizer, AutoModel
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
tokens = tokenizer("Hello world", return_tensors="pt")
model = AutoModel.from_pretrained("bert-base-uncased")
outputs = model(**tokens) # contextual embeddings
🎥 Watch Instead
▶
Video coming soon
This lesson's animated video hasn't been made yet — check back soon.
Flashcard
🃏 ⭐ Most Important
The NLP pipeline — from tokenize to generate?
Tap to flip
🃏 Answer
TOKENIZE → EMBED → ENCODE → DECODE → GENERATE — the complete NLP pipeline
TokenizeRaw text → token IDs using a learned vocabulary (BPE, WordPiece)
EmbedToken IDs → dense vectors + positional encoding
Encode/DecodeTransformer layers build or generate representations
GenerateSampling strategy converts logits to final token choices
🐍 Codefrom transformers import AutoTokenizer, AutoModel
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
tokens = tokenizer("Hello world", return_tensors="pt")
model = AutoModel.from_pretrained("bert-base-uncased")
outputs = model(**tokens) # contextual embeddings
Tap to flip back
🎯 Exam Favorite
BLEU measures PRECISION of n-grams · ROUGE measures RECALL of n-grams
BLEU FOR TRANSLATION · ROUGE FOR SUMMARIZATION
NLP evaluation metrics — BLEU vs ROUGE
BLEU (Bilingual Evaluation Understudy): measures how many n-grams in the machine output appear in the reference translation — precision-oriented. Standard for machine translation. Range 0–1 (higher = better). ROUGE (Recall-Oriented Understudy for Gisting Evaluation): measures how many n-grams in the reference appear in the generated summary — recall-oriented. Standard for text summarization. ROUGE-1 (unigrams), ROUGE-2 (bigrams), ROUGE-L (longest common subsequence). Both compare to human reference outputs.
BLEU
Precision of n-grams — machine output vs reference. Used for translation.
ROUGE
Recall of n-grams — reference vs machine output. Used for summarization.
Perplexity
How surprised is the model by test text? Lower = better language model.
🐍 Code
from nltk.translate.bleu_score import sentence_bleu
reference = [["the", "cat", "sat"]]; hypothesis = ["the", "cat", "sat"]
bleu = sentence_bleu(reference, hypothesis)
# For ROUGE: pip install rouge-score
from rouge_score import rouge_scorer
🎥 Watch Instead
▶
Video coming soon
This lesson's animated video hasn't been made yet — check back soon.
Flashcard
🃏 🎯 Exam Favorite
BLEU vs ROUGE — precision or recall?
Tap to flip
🃏 Answer
BLEU measures PRECISION of n-grams · ROUGE measures RECALL of n-grams
BLEUPrecision of n-grams — machine output vs reference. Used for translation.
ROUGERecall of n-grams — reference vs machine output. Used for summarization.
PerplexityHow surprised is the model by test text? Lower = better language model.
🐍 Codefrom nltk.translate.bleu_score import sentence_bleu
reference = [["the", "cat", "sat"]]; hypothesis = ["the", "cat", "sat"]
bleu = sentence_bleu(reference, hypothesis)
# For ROUGE: pip install rouge-score
from rouge_score import rouge_scorer
Tap to flip back
💡 Concept Anchor
FINE-TUNING vs PROMPTING — two ways to customize an LLM for your task
WHEN TO FINE-TUNE · WHEN TO PROMPT
Choosing between fine-tuning and prompt engineering
Prompting: write better instructions, add examples (few-shot), structure your query. Fast, cheap, no training needed. Sufficient for most tasks. Fine-tuning: update the model weights on your specific task data. Needed when: the task requires a consistent style/format the model struggles to follow via prompting, you have thousands of task-specific examples, or you need better performance than prompting achieves. Rule of thumb: always try prompting first. Fine-tune only if prompting hits a ceiling.
Prompting
Fast, cheap, flexible — try this first for every task
Fine-tuning
Better consistency and performance — requires labeled data and compute
LoRA
Efficient fine-tuning — update only 1% of parameters, get 99% of the benefit
🐍 Code
# Prompting — no training required
response = client.messages.create(model="claude-sonnet-4-6",
messages=[{"role":"user","content":"Classify sentiment: I love this!"}])
# Fine-tuning with LoRA (parameter-efficient)
# from peft import LoraConfig, get_peft_model
🎥 Watch Instead
▶
Video coming soon
This lesson's animated video hasn't been made yet — check back soon.
Flashcard
🃏 💡 Concept Anchor
Fine-tuning vs prompting — when to use each?
Tap to flip
🃏 Answer
FINE-TUNING vs PROMPTING — two ways to customize an LLM for your task
PromptingFast, cheap, flexible — try this first for every task
Fine-tuningBetter consistency and performance — requires labeled data and compute
LoRAEfficient fine-tuning — update only 1% of parameters, get 99% of the benefit
🐍 Code# Prompting — no training required
response = client.messages.create(model="claude-sonnet-4-6",
messages=[{"role":"user","content":"Classify sentiment: I love this!"}])
# Fine-tuning with LoRA (parameter-efficient)
# from peft import LoraConfig, get_peft_model
Tap to flip back
🎓 Common Exam Questions
0
Correct
0
Wrong
0
Remaining
🔗 Related Sub-Subjects
🔬 Deep Learning
Transformers, BERT, GPT — the deep learning architectures that power modern NLP.
Deep Learning →
✍️ Prompt Engineering
How to get the best output from LLMs — prompting techniques, RAG, and agents.
Prompt Engineering →
📈 Model Evaluation
BLEU, ROUGE, perplexity — how NLP models are measured and compared.
Model Evaluation →