6.4 NLP Techniques
6.4 NLP Techniques
Key Concepts
6.4.1 Text Representation Evolution
One-Hot Encoding → Count-Based → Word Embeddings → Contextual Embeddings
(sparse) (TF-IDF) (Word2Vec) (BERT, GPT)One-Hot Encoding
Vocabulary: [cat, dog, bird, fish]
"cat" → [1, 0, 0, 0]
"dog" → [0, 1, 0, 0]
Problems:
- High dimensionality (vocab size)
- No semantic similarity (all words equidistant)
- Sparse vectorsBag of Words / TF-IDF
Document: "the cat sat on the mat"
BoW: Count word occurrences
TF-IDF: Term Frequency × Inverse Document Frequency
TF-IDF(t,d) = TF(t,d) × log(N / DF(t))
Where:
- TF(t,d) = frequency of term t in document d
- DF(t) = number of documents containing term t
- N = total number of documentsLimitations:
- Ignores word order
- No semantic understanding
- High dimensionality
6.4.2 Word Embeddings (Static)
Word embeddings map words to dense, low-dimensional vectors that capture semantic meaning.
Key Properties
Semantic similarity:
cos(king, queen) > cos(king, apple)
Analogies:
king - man + woman ≈ queen
Paris - France + Italy ≈ RomeWord2Vec (2013)
Two architectures for learning word embeddings:
Skip-gram: Predict context words from center word
Input: "cat"
Predict: ["the", "sat", "on", "mat"]
Context
↑
┌────┴────┐
│ Softmax │
└────┬────┘
│
┌────┴────┐
│ Hidden │ ← Word embedding
└────┬────┘
│
┌────┴────┐
│ Input │ ← One-hot "cat"
└─────────┘CBOW (Continuous Bag of Words): Predict center word from context
Input: ["the", "sat", "on", "mat"]
Predict: "cat"
┌─────────┐
│ Softmax │ → "cat"
└────┬────┘
│
┌────┴────┐
│ Average │
└────┬────┘
┌────┴────┐
│ Embed │ ← Context words
└─────────┘Training Objective (Skip-gram):
Maximize: Σ Σ log P(w_context | w_center)
P(w_o | w_i) = exp(v'_o · v_i) / Σ exp(v'_w · v_i)
w∈VNegative Sampling:
Full softmax over vocabulary is expensive. Instead:
# Instead of normalizing over all words
# Sample k negative examples
L = log σ(v'_pos · v_center) + Σ log σ(-v'_neg · v_center)
k negativesGloVe (2014)
Global Vectors for Word Representation
Combines count-based and prediction-based methods:
Objective: Learn embeddings where dot product = log co-occurrence
J = Σ f(X_ij)(w_i · w̃_j + b_i + b̃_j - log X_ij)²
i,j
Where:
- X_ij = co-occurrence count of words i and j
- f(x) = weighting function (caps frequent pairs)Key insight: Word relationships are encoded in co-occurrence ratios.
P(k|ice) / P(k|steam):
- k = "solid": high ratio (ice-related)
- k = "gas": low ratio (steam-related)
- k = "water": ratio ≈ 1 (both related)FastText (2016)
Key innovation: Subword embeddings
Word "where" → subwords: <wh, whe, her, ere, re>
Embedding(where) = Σ Embedding(subword)Advantages:
- Handles out-of-vocabulary (OOV) words
- Captures morphology (prefixes, suffixes)
- Better for morphologically rich languages
"unhappiness" → <un, unh, nha, hap, app, ppi, pin, ine, nes, ess, ss>
Even if "unhappiness" not in training, can compose from subwordsComparison
| Method | Training Data | OOV Handling | Captures |
|---|---|---|---|
| Word2Vec | Local context | No | Semantic similarity |
| GloVe | Global co-occurrence | No | Global statistics |
| FastText | Local + subwords | Yes | Morphology |
6.4.3 Contextual Embeddings
Static embeddings give one vector per word. Contextual embeddings give different vectors based on context.
Static (Word2Vec):
"bank" → same vector always
Contextual (BERT):
"river bank" → vector₁
"bank account" → vector₂ (different!)ELMo (2018)
Embeddings from Language Models
Architecture: Bidirectional LSTM
Forward LSTM: → → → → →
The cat sat on mat
Backward LSTM: ← ← ← ← ←
ELMo embedding = weighted sum of all layer representationsKey features:
- Character-level CNN for input (handles OOV)
- Deep bidirectional LSTM
- Task-specific weighting of layers
BERT (2018)
Bidirectional Encoder Representations from Transformers
Architecture: Transformer Encoder (12-24 layers)
[CLS] The cat sat [MASK] the mat [SEP]
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
┌─────────────────────────────────────┐
│ Transformer Encoder │
│ (Self-attention + Feed-forward) │
└─────────────────────────────────────┘
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
h₀ h₁ h₂ h₃ h₄ h₅ h₆ h₇Pre-training objectives:
-
Masked Language Model (MLM):
- Randomly mask 15% of tokens
- Predict masked tokens from context
- Enables bidirectional context
-
Next Sentence Prediction (NSP):
- Given two sentences, predict if B follows A
- Helps with sentence-pair tasks
Fine-tuning:
Classification: Use [CLS] token → classifier
Token-level: Use each token embedding → per-token classifierGPT (2018-present)
Generative Pre-trained Transformer
Architecture: Transformer Decoder (unidirectional)
The cat sat on → [predict next token]
Only attends to previous tokens (causal/autoregressive)Pre-training: Next token prediction (language modeling)
Key difference from BERT:
- Unidirectional (left-to-right only)
- Generative (can produce text)
- Scales better with size
6.4.4 Common NLP Tasks
Named Entity Recognition (NER)
Identify and classify named entities in text.
Input: "Apple Inc. was founded by Steve Jobs in California"
Output: [Apple Inc.]_ORG was founded by [Steve Jobs]_PER in [California]_LOC
Entity types: PER (person), ORG (organization), LOC (location), DATE, etc.Approaches:
- Sequence labeling with BIO tagging
- BERT + token classification head
BIO Tagging:
Apple Inc. was founded by Steve Jobs
B-ORG I-ORG O O O B-PER I-PERPart-of-Speech (POS) Tagging
Assign grammatical tags to each word.
Input: "The quick brown fox jumps"
Output: DET ADJ ADJ NOUN VERB
Tags: NOUN, VERB, ADJ, ADV, DET, PREP, etc.Sentiment Analysis
Classify text by sentiment/opinion.
Input: "This movie was absolutely fantastic!"
Output: Positive (0.95)
Levels:
- Binary: positive/negative
- Fine-grained: 1-5 stars
- Aspect-based: "Food was great, service was slow"Question Answering (QA)
Extractive QA: Find answer span in context
Context: "The Eiffel Tower is located in Paris, France."
Question: "Where is the Eiffel Tower?"
Answer: "Paris, France" (span extraction)Generative QA: Generate answer from knowledge
Question: "What is the capital of France?"
Answer: "Paris" (generated)Text Classification
Assign categories to documents.
Applications:
- Spam detection
- Topic classification
- Intent detection
- Language identificationMachine Translation
Input (English): "The cat is on the table"
Output (French): "Le chat est sur la table"
Approaches:
- Seq2seq with attention
- Transformer (encoder-decoder)6.4.5 Tokenization
Converting text to tokens that models can process.
Word-level Tokenization
"I love NLP" → ["I", "love", "NLP"]
Problems:
- Large vocabulary
- OOV wordsSubword Tokenization
Byte Pair Encoding (BPE):
Start: character-level vocabulary
Iteratively merge most frequent pairs
"lowest" → ["low", "est"]
"lower" → ["low", "er"]
Handles OOV by breaking into known subwordsWordPiece (BERT):
Similar to BPE but uses likelihood instead of frequency
"playing" → ["play", "##ing"]SentencePiece:
- Language-agnostic
- Treats input as raw text (no pre-tokenization)
- Used by T5, ALBERT
6.4.6 Evaluation Metrics for NLP
Classification Metrics
| Metric | Formula | Use Case |
|---|---|---|
| Accuracy | (TP+TN)/(TP+TN+FP+FN) | Balanced classes |
| Precision | TP/(TP+FP) | Minimize false positives |
| Recall | TP/(TP+FN) | Minimize false negatives |
| F1 | 2×P×R/(P+R) | Balance P and R |
| Macro F1 | Average F1 across classes | Imbalanced classes |
Sequence Labeling (NER, POS)
Entity-level F1:
- Exact match: both boundaries and type must match
- Partial match: overlapping spans
Span-level metrics:
- Precision: correct spans / predicted spans
- Recall: correct spans / gold spansMachine Translation
BLEU (Bilingual Evaluation Understudy):
BLEU = BP × exp(Σ wₙ log pₙ)
Where:
- pₙ = n-gram precision
- BP = brevity penalty (penalizes short translations)
- wₙ = weights (typically uniform)
BLEU-4: considers 1-4 gramsROUGE (Recall-Oriented Understudy for Gisting Evaluation):
ROUGE-N: n-gram recall
ROUGE-L: longest common subsequence
Used for summarizationMETEOR:
- Considers synonyms and stemming
- Better correlation with human judgment than BLEU
Question Answering
Exact Match (EM):
EM = 1 if prediction == ground_truth else 0F1 Score (token-level):
Treat prediction and ground truth as bags of tokens
F1 = 2 × P × R / (P + R)Perplexity (Language Models)
PPL = exp(-1/N × Σ log P(wᵢ | w₁...wᵢ₋₁))
Lower perplexity = better model
Interpretation: average branching factorQuestions & Answers
Q1: How does Word2Vec work (skip-gram, CBOW)?
Answer:
Word2Vec learns dense word embeddings by training a shallow neural network on a word prediction task.
Skip-gram Architecture:
Predicts context words given a center word.
Training example: "The [cat] sat on the mat"
Center word: "cat"
Context words: ["The", "sat", "on", "the"] (window size = 2)
Network:
Input (one-hot) → Embedding layer (V×D) → Output layer (D×V) → Softmax
For each (center, context) pair:
- Input: one-hot vector of center word
- Output: probability distribution over vocabulary
- Target: one-hot vector of context wordObjective:
Maximize: Σ Σ log P(w_context | w_center)
center context
P(w_o | w_c) = exp(u_o · v_c) / Σ exp(u_w · v_c)CBOW Architecture:
Predicts center word given context words.
Training example: "The [cat] sat on the mat"
Context words: ["The", "sat", "on", "the"]
Target: "cat"
Network:
Input (avg of context embeddings) → Output layer → Softmax → center wordNegative Sampling (efficiency):
Full softmax is O(V) per example. Instead:
# Sample k negative words (not in context)
# Binary classification: is this a real context pair?
L = log σ(u_pos · v_c) + Σ E[log σ(-u_neg · v_c)]
k
Typically k = 5-20 for small datasets, k = 2-5 for largeSkip-gram vs CBOW:
| Aspect | Skip-gram | CBOW |
|---|---|---|
| Predicts | Context from center | Center from context |
| Training | Slower (more examples) | Faster |
| Rare words | Better | Worse |
| Frequent words | Worse | Better |
| Typical use | Default choice | Large datasets |
Why it works:
- Words in similar contexts get similar embeddings
- Distributional hypothesis: "You shall know a word by the company it keeps"
Q2: What is the difference between static and contextual embeddings?
Answer:
Static Embeddings (Word2Vec, GloVe, FastText):
Each word has ONE fixed vector regardless of context.
"I went to the bank to deposit money"
"I sat by the river bank"
bank → [0.2, -0.5, 0.8, ...] (same vector!)Characteristics:
- One embedding per word type
- Pre-computed, stored in lookup table
- Fast inference (just lookup)
- Cannot handle polysemy (multiple meanings)
- Context-independent
Contextual Embeddings (ELMo, BERT, GPT):
Each word gets a DIFFERENT vector based on surrounding context.
"I went to the bank to deposit money"
bank → [0.2, -0.5, 0.8, ...] (financial meaning)
"I sat by the river bank"
bank → [-0.3, 0.7, 0.1, ...] (different vector!)Characteristics:
- One embedding per word token (in context)
- Computed at inference time
- Slower (requires forward pass)
- Handles polysemy naturally
- Context-dependent
Comparison:
| Aspect | Static | Contextual |
|---|---|---|
| Polysemy | ✗ Cannot handle | ✓ Different vectors |
| Speed | Fast (lookup) | Slow (forward pass) |
| Memory | Low (V × D) | High (model params) |
| Training | Unsupervised, fast | Large-scale pretraining |
| Performance | Good baseline | State-of-the-art |
| OOV handling | Limited (FastText helps) | Subword tokenization |
When to use which:
| Scenario | Recommendation |
|---|---|
| Limited compute | Static embeddings |
| Real-time, low latency | Static (or distilled contextual) |
| Best accuracy needed | Contextual (BERT, etc.) |
| Domain-specific | Fine-tune contextual |
| Simple baseline | Static + simple model |
Key insight: Contextual embeddings capture that meaning depends on context—the same word can mean different things in different sentences. This is why they dramatically outperform static embeddings on most NLP benchmarks.
Q3: What are common evaluation metrics for NLP tasks?
Answer:
Different NLP tasks require different metrics:
1. Text Classification (Sentiment, Topic, Intent)
| Metric | When to Use |
|---|---|
| Accuracy | Balanced classes |
| Macro F1 | Imbalanced classes (equal weight per class) |
| Weighted F1 | Imbalanced (weight by class frequency) |
| ROC-AUC | Ranking, threshold selection |
# Multi-class example
from sklearn.metrics import classification_report
print(classification_report(y_true, y_pred))2. Sequence Labeling (NER, POS)
| Metric | Description |
|---|---|
| Token-level accuracy | Per-token correctness |
| Entity-level F1 | Exact span + type match |
| Partial F1 | Overlapping spans count |
Gold: [Barack Obama]_PER visited [Paris]_LOC
Pred: [Obama]_PER visited [Paris]_LOC
Token accuracy: 5/5 = 100%
Entity F1: 1/2 exact matches (Obama partial)3. Machine Translation
| Metric | Description |
|---|---|
| BLEU | N-gram precision with brevity penalty |
| METEOR | Includes synonyms, stemming |
| chrF | Character-level F-score |
| COMET | Neural metric, better correlation |
Reference: "The cat is on the table"
Candidate: "A cat is on the table"
BLEU-4 ≈ 0.6 (penalized for "A" vs "The")4. Question Answering
| Metric | Description |
|---|---|
| Exact Match (EM) | Strict string equality |
| F1 (token) | Token overlap between pred and gold |
Gold: "Paris, France"
Pred: "Paris"
EM = 0 (not exact match)
F1 = 2×(1/1)×(1/2) / (1 + 0.5) = 0.675. Summarization
| Metric | Description |
|---|---|
| ROUGE-1 | Unigram recall |
| ROUGE-2 | Bigram recall |
| ROUGE-L | Longest common subsequence |
| BERTScore | Semantic similarity via BERT |
6. Language Modeling
| Metric | Description |
|---|---|
| Perplexity | exp(cross-entropy loss) |
| Bits per character | For character-level models |
Lower perplexity = better model
PPL = 10 means model is "10-way confused" on average7. Semantic Similarity
| Metric | Description |
|---|---|
| Pearson correlation | Linear correlation with human scores |
| Spearman correlation | Rank correlation |
| Cosine similarity | For embedding comparison |
Interview tip: Always mention that automatic metrics have limitations—human evaluation remains the gold standard for many tasks, especially generation. Also note that task-specific metrics matter: BLEU for translation, ROUGE for summarization, F1 for NER, etc.