Angad Sandhu
Search
Browse
On this page

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 vectors

Bag 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 documents

Limitations:

  • 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 ≈ Rome

Word2Vec (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∈V

Negative 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 negatives

GloVe (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 subwords

Comparison

MethodTraining DataOOV HandlingCaptures
Word2VecLocal contextNoSemantic similarity
GloVeGlobal co-occurrenceNoGlobal statistics
FastTextLocal + subwordsYesMorphology

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 representations

Key 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:

  1. Masked Language Model (MLM):

    • Randomly mask 15% of tokens
    • Predict masked tokens from context
    • Enables bidirectional context
  2. 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 classifier

GPT (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-PER

Part-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 identification

Machine 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 words

Subword 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 subwords

WordPiece (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

MetricFormulaUse Case
Accuracy(TP+TN)/(TP+TN+FP+FN)Balanced classes
PrecisionTP/(TP+FP)Minimize false positives
RecallTP/(TP+FN)Minimize false negatives
F12×P×R/(P+R)Balance P and R
Macro F1Average F1 across classesImbalanced 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 spans

Machine 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 grams

ROUGE (Recall-Oriented Understudy for Gisting Evaluation):

ROUGE-N: n-gram recall
ROUGE-L: longest common subsequence

Used for summarization

METEOR:

  • Considers synonyms and stemming
  • Better correlation with human judgment than BLEU

Question Answering

Exact Match (EM):

EM = 1 if prediction == ground_truth else 0

F1 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 factor

Questions & 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 word

Objective:

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 word

Negative 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 large

Skip-gram vs CBOW:

AspectSkip-gramCBOW
PredictsContext from centerCenter from context
TrainingSlower (more examples)Faster
Rare wordsBetterWorse
Frequent wordsWorseBetter
Typical useDefault choiceLarge 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:

AspectStaticContextual
Polysemy✗ Cannot handle✓ Different vectors
SpeedFast (lookup)Slow (forward pass)
MemoryLow (V × D)High (model params)
TrainingUnsupervised, fastLarge-scale pretraining
PerformanceGood baselineState-of-the-art
OOV handlingLimited (FastText helps)Subword tokenization

When to use which:

ScenarioRecommendation
Limited computeStatic embeddings
Real-time, low latencyStatic (or distilled contextual)
Best accuracy neededContextual (BERT, etc.)
Domain-specificFine-tune contextual
Simple baselineStatic + 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)

MetricWhen to Use
AccuracyBalanced classes
Macro F1Imbalanced classes (equal weight per class)
Weighted F1Imbalanced (weight by class frequency)
ROC-AUCRanking, threshold selection
# Multi-class example
from sklearn.metrics import classification_report
print(classification_report(y_true, y_pred))

2. Sequence Labeling (NER, POS)

MetricDescription
Token-level accuracyPer-token correctness
Entity-level F1Exact span + type match
Partial F1Overlapping 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

MetricDescription
BLEUN-gram precision with brevity penalty
METEORIncludes synonyms, stemming
chrFCharacter-level F-score
COMETNeural 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

MetricDescription
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.67

5. Summarization

MetricDescription
ROUGE-1Unigram recall
ROUGE-2Bigram recall
ROUGE-LLongest common subsequence
BERTScoreSemantic similarity via BERT

6. Language Modeling

MetricDescription
Perplexityexp(cross-entropy loss)
Bits per characterFor character-level models
Lower perplexity = better model
PPL = 10 means model is "10-way confused" on average

7. Semantic Similarity

MetricDescription
Pearson correlationLinear correlation with human scores
Spearman correlationRank correlation
Cosine similarityFor 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.

Browse the library