Complete NLP Learning Guide (BCSE 0454) — Zero to Professional
Tumhare poore university syllabus, saare PDF notes aur PPTs ka 100% exhaustive coverage — har topic ka Why & Evolution, Internal Workflow Diagram, Step-by-Step Math & Numericals, Formal Exam Definitions, aur 2/5/10-Mark Answers ek hi self-contained textbook me.
1. Complete BCSE 0454 Syllabus & Uploaded Notes Audit Map
Ek bhi syllabus heading ya PPT slide skip nahi ki gayi hai. Har chapter me clearly mark kiya gaya hai ki kya tumhare university syllabus (Module I / Module II) ka part hai aur kya professional industry depth (Beyond Syllabus) hai:
| Ch | Module / Scope | Exact Syllabus & Notes Topics Covered in Full Detail | CO |
|---|---|---|---|
| 0 | Start & Prereqs | Syllabus Audit, 4-Era Evolution, Prerequisites (Conditional Probability, Bayes, Chain Rule, Vectors, Dot Product, Cosine Angle, Logarithms, Softmax) | All |
| 1 | Module I | NLP, NLU, NLG; Linguistic terminology (Phoneme, Grapheme, Morpheme); 7 Levels of Language Processing (Phonological to Pragmatic) + Processing Granularity (Char to Multi-Doc); 5 Ambiguities + Garden Path Sentences; Free/Bound Morphemes, Inflectional vs Derivational Morphology, Morphological Parsing (Lexicon, Morphotactics, Orthographic rules); Classical NLP Approaches | CO1 |
| 2 | Module I | Text Preprocessing End-to-End Pipeline; Word Tokenization (edge cases); Word Normalization (Stemming vs Lemmatization — Porter, Over/Under-stemming); Stop-words & Keyword Identification; Regular Expressions; Finite State Automata (FSA/DFA) — 5-tuple + 3 complete worked designs (baa+!, Binary Div by 5, Ends with 100); Chunking (Shallow Parsing) | CO1 |
| 3 | Module I | Language Modelling: Why LM?, Conditional Probability, Chain Rule, Data Sparsity → Markov Property, Unigram/Bigram/Trigram Models, Boundary tokens (<s>, </s>), Both Worked Exam Numericals (I am a human & Jack corpus), Laplace (Add-1) Smoothing, Perplexity | CO2 |
| 4 | Module I & II | POS Tagging (Open vs Closed classes, POS vs Morphology, Penn Treebank / UD / BIS tagsets, 6 Challenges, 8 Applications, Rule-based/EngCG, Transformation-based/Brill Tagger with worked example, Statistical HMM/MaxEnt/CRF, Neural BiLSTM/BERT); HMM (π, A, B); Viterbi Algorithm (Complete Walk, Shop, Clean Trellis + Pseudocode + O(TN²) vs O(Nᵀ) Proof); Named Entity Recognition (NER: Span+Type, Generic vs Named Entity, 4 Core + Extra Categories, BIO/IO/BIOES, ACE/ENAMEX/NUMEX/TIMEX, NER vs Event/Coref/String Matching, 4-way "Washington" Ambiguity, 6 Indian Language Challenges + AI4Bharat, NER Evaluation Challenges) | CO2, CO3 |
| 5 | Module II | Syntactic Processing & Parsing: Why CFG?, 4-Tuple, Constituency, Grammatical Relations, Subcategorization & Dependencies, Leftmost/Rightmost Derivations, Constituency vs Dependency Parsing, Structural Ambiguity (2 Parse Trees), Top-Down vs Bottom-Up Parsing (Worked examples: "The man read this book" & "Book that flight"), Chomsky Normal Form (CNF — 4 conversion steps + examples), CKY Algorithm (Pseudocode + O(n³|G|) + Worked Chart), PCFG & PCKY Algorithm (Complete 7×7 Chart & both Parse Trees for "she saw the man with the telescope") | CO3 |
| 6 | Module II | Semantic, Discourse & Pragmatic Processing: Semantic Analysis & Knowledge Representation; WordNet (Synsets, Gloss, Stats, 4 Applications); All Lexical Semantic Relations (Synonymy, 3 types of Antonymy, Hyponymy/Hypernymy, Meronymy, Homonymy, Polysemy); WSD (3 Approaches) & Lesk Algorithm (7 Components, Architecture SVG, Worked "bank" example, Limitations); Semantic Role Labeling (SRL: Agent/Predicate/Patient/Instrument); Coreference & Anaphora Resolution + Entity Linking; Pragmatics vs Discourse (Coherence, Cohesion, Speech Acts, Deixis, 3 Context Types) | CO3 |
| 7 | Module II (Full IR) | Complete Information Retrieval (IR) System & Statistical NLP: IR Core Terminology; DB vs IR vs QA; Offline Indexing vs Online Querying Architecture SVG; End-to-End Query Lifecycle Workflow; Preprocessing Consistency Rule; Term-Document Incidence Matrix (D1–D3 + 99.8% Sparsity Proof); Inverted Index Construction (4-Step Workflow + SPIMI/MapReduce); Positional Index & Phrase Queries; Boolean Retrieval + INTERSECT Algorithm & Dry Run + Strengths/Weaknesses; Bag of Words (BoW) → Vector Space Model & TF-IDF (Log-TF table, IDF table, Full Numerical); Text Similarity (Jaccard, Dice, Overlap, Cosine Similarity vs Euclidean Distance Proof) | CO4, CO5 |
| 8 | Module II | Word Embeddings & Word2Vec: Complete Evolution (One-Hot → BoW/TF-IDF → Word2Vec → GloVe → FastText → BERT/RoBERTa/GPT); Distributional Hypothesis; Corpus/Vocab/Context Window; CBOW & Skip-gram Architectures + Whiteboard Matrix Math (W, W', Softmax, Backprop); Negative Sampling; Embedding Dimensions; Cosine Similarity & Vector Analogies + Corpus Bias; Complete Gensim Python Code; Limitations; Class Activity Solutions & 10 Viva/Interview Q&As | CO4 |
| 9 | Module II | Evaluation Measures & All NLP Applications: Confusion Matrix, Accuracy vs Precision/Recall/F₁/F_β (Worked Numerical), Exact Match & Entity-Level F1, BLEU, ROUGE, Perplexity, Human Eval; Question Answering (3-Stage Workflow SVG, Datasets, Challenges); Opinion Mining & Sentiment Analysis (Lexicon, ML, ABSA); Text Classification (Pipeline SVG, Rule/ML/Hybrid); Document Summarization (Extractive vs Abstractive SVGs + Worked Example); Machine Translation (RBMT, SMT, HMT, NMT, Transliteration); Recommendation Systems; Ontology Construction & Classification; Emerging NLG Applications | CO4, CO5 |
| 10 | Beyond Syllabus (Pro) | Deep Learning NLP Foundations: Neural LMs → RNN (Equations + Vanishing Gradient) → LSTM (Complete 3-Gate Cell State Architecture SVG + Equations) & GRU → Seq2Seq Encoder-Decoder & Information Bottleneck → Bahdanau Attention Mechanism | Pro |
| 11 | Beyond Syllabus (Pro) | Transformers, LLMs & Modern Production NLP: Self-Attention (Q, K, V Step-by-Step Math), Multi-Head Attention, Positional Encoding, Transformer Architecture SVG, Encoder-Only (BERT/RoBERTa) vs Decoder-Only (GPT/Llama) vs Encoder-Decoder (T5), Post-Training (Instruction Tuning / SFT, RLHF / DPO), Retrieval-Augmented Generation (RAG) End-to-End Workflow SVG, Traditional vs Deep Learning NLP | Pro |
2. Interactive BCSE 0454 Mastery Checklist (Auto-Saved)
3. The 4 Eras of NLP — Why Everything Evolved
NLP ko ratna nahi hai, uski evolution story samajhni hai. Har naya technique pichhle technique ke ek major bottleneck ko todne ke liye aaya:
- Era 1 — Symbolic / Rule-Based NLP (1950s–1980s): Linguists ne manually Regex, CFG grammar rules, aur dictionaries (WordNet) likhi. Limitation: Language me hazaaron exceptions, slang, aur ambiguities hain; manual rules kabhi complete nahi ho sakte.
- Era 2 — Statistical & Probabilistic NLP (1990s–2010s): Rules ke bajaye large corpora se probabilities learn ki gayi (N-grams, HMM + Viterbi, PCFG + PCKY, Naive Bayes, CRF, TF-IDF). Limitation: Words ko discrete IDs/counts maana gaya (sparse vectors), jisse semantic meaning ("car" ≈ "automobile") capture nahi hua aur manual feature engineering lagti thi.
- Era 3 — Dense Embeddings & Sequence Deep Learning (2013–2017): Word2Vec, GloVe, FastText ne dense semantic vectors diye; RNN aur LSTM ne variable-length sequences padhna sikha. Limitation: Word2Vec static tha ("bank" ka ek hi vector), aur RNN/LSTM word-by-word sequential hone se slow the aur very long contexts me weak padte the.
- Era 4 — Transformers, Pretrained LLMs & RAG (2017–Present): Self-Attention (BERT, GPT, T5) ne poora sentence parallel me padha, dynamic contextual embeddings banayi, RLHF se human instructions follow kiye, aur RAG se factual hallucination control kiya.
4. Missing Prerequisites (Zero-Level Math & ML Toolkit)
P(A | B) = Probability of event A occurring, given that B has already occurred.
Chain Rule: Kisi bhi sequence (x₁, x₂, x₃) ki joint probability: P(x₁, x₂, x₃) = P(x₁) · P(x₂|x₁) · P(x₃|x₁, x₂). Isi par poora N-gram Language Model aur HMM khada hai.
Machine text nahi padh sakti, sirf numbers padhti hai. Isliye har word ya document ek Vector (list of numbers) banta hai, e.g., A = [3, 4], B = [6, 8].
- Dot Product:
A · B = (3×6) + (4×8) = 18 + 32 = 50. - Euclidean Norm (Length):
||A|| = √(3² + 4²) = 5,||B|| = √(6² + 8²) = 10. - Cosine of Angle:
cos(θ) = (A · B) / (||A|| · ||B||) = 50 / (5×10) = 1.0(same direction!).
- Why Log? TF-IDF me raw word count 100 ko 10 se 10× zyada important nahi maana jaata;
log₁₀(100)=2aurlog₁₀(10)=1extreme values ko smooth (dampen) kar deta hai. Also, very small probabilities multiply karne par underflow hota hai, log unhe addition me badal deta hai:log(a·b) = log(a) + log(b). - Why Softmax? Word2Vec, Transformers aur Neural Classifiers raw scores (logits) output karte hain, e.g.,
y = [2.0, 1.0, 0.1]. Softmax unhe valid probability distribution me convert karta hai (every value in[0,1], sum =1.0):Softmax(yᵢ) = e^(yᵢ) / Σⱼ e^(yⱼ)
Chapter 1: Foundations of NLP, NLU, NLG & Linguistics
Human language computers ke liye itni mushkil kyun hai? NLP/NLU/NLG ka relationship, 7 Linguistic Levels, Processing Granularity, 5 Ambiguities, Garden Path sentences, aur complete Morphological Analysis.
1. NLP, NLU, and NLG — One Umbrella, Two Directions
Introduction: Hum roz insaanon se natural language (Hindi, English, Hinglish) me baat karte hain. Computer sirf binary 0 aur 1 samajhta hai. Natural Language Processing (NLP) AI ka wo field hai jo computer ko human language read, understand, analyze aur generate karne layak banata hai. Iske 2 goals hain: (1) Primary — practical systems banana (translators, chatbots, search engines), (2) Secondary — human language ko deeper level par samajhna.
NLP do opposite directions me kaam karta hai:
- NLU (Natural Language Understanding — Text → Meaning): Unstructured human text ko structured internal representation me convert karna (intent, entities, syntax, semantic roles). Ye harder hai kyunki ek hi baat ko insaan 100 alag tareekon se bol sakta hai aur language ambiguous hoti hai.
- NLG (Natural Language Generation — Meaning → Text): Structured data ya internal intent se fluent, grammatically sahi human text produce karna. Iske 2 classical phases hote hain: Deep Planning (kya bolna hai / content determination) aur Syntactic/Surface Generation (kaise bolna hai / exact words & grammar).
| Aspect | NLU (Natural Language Understanding) | NLG (Natural Language Generation) |
|---|---|---|
| Direction | Raw Text → Structured Meaning | Structured Meaning / Data → Fluent Text |
| Core Challenge | Resolving ambiguity, polysemy, and implicit context | Ensuring fluency, coherence, factual accuracy (no hallucination) |
| Key Sub-tasks | Embeddings, POS Tagging, NER, Parsing, WSD, SRL, Coreference | Language Modeling, Machine Translation, Summarization, Dialogue, TTS |
| Evaluation | Precision, Recall, F1, Exact Match, Accuracy | BLEU, ROUGE, Perplexity, Human Evaluation |
| Modern Models | Encoder-Only Transformers (BERT, RoBERTa) | Decoder-Only (GPT, Llama) & Encoder-Decoder (T5) |
Natural Language Processing (NLP) is a subfield of Artificial Intelligence and Computational Linguistics that focuses on enabling computers to analyze, understand, and generate human (natural) language in a meaningful and useful way. It comprises Natural Language Understanding (NLU)—mapping unstructured linguistic input into structured semantic representations—and Natural Language Generation (NLG)—synthesizing fluent, coherent natural language from internal data or intent.
2. Why Is Natural Language Difficult? (Ambiguities & Garden Path)
Programming languages (C, Java, Python) me har statement ka strictly ek hi meaning hota hai. Natural language me Ambiguity (ek hi word ya sentence ke multiple interpretations) sabse bada obstacle hai:
| Ambiguity Type | Conceptual Explanation (Hinglish) | Exam Examples |
|---|---|---|
| 1. Lexical Ambiguity | Ek hi word ke multiple meanings ya grammatical categories (POS) hona. | "I can play cricket" (Verb) vs "Give me that can" (Noun). Also: mouse (rodent vs computer device), bank. |
| 2. Syntactic (Structural) Ambiguity | Ek hi sentence ko grammar rules se 2 alag parse trees me toda ja sakta hai. | "A bird saw the man with the binoculars." — Bird ne binoculars se dekha, ya us aadmi ke paas binoculars the? |
| 3. Semantic Ambiguity | Words aur grammar clear hone ke baad bhi sentence ka overall logical meaning 2 tarah se nikle. | "Maman loves his cat and Divyesh does too." — Divyesh apni billi se pyaar karta hai ya Maman ki billi se? |
| 4. Anaphoric Ambiguity | Pronoun (he/she/it/they) pichhle kis noun (antecedent) ko refer kar raha hai, ye unclear hona. | "The house is on a long street. It is very dirty." — House dirty hai ya street? |
| 5. Pragmatic Ambiguity | Speaker ke intent, tone ya situation par depend karne wale multiple implied meanings. | "Can you pass the salt?" (literal ability question nahi, polite request hai); "I love you too." |
- "The horse raced past the barn fell." — Padhte waqt
racedmain verb lagta hai, parfellaate hi backtrack karke samajhna padta hai ki "raced past the barn" ek reduced relative clause hai (= The horse that was raced past the barn fell). - "The government plans to raise taxes were defeated." —
plansverb nahi, plural noun hai! - "The old man the boat." —
old= noun (elderly people),man= verb (to operate/crew)!
3. The 7 Levels of Language Processing & Processing Granularity
Meaning ek saath nahi banta — wo 7 linguistic layers me step-by-step build hota hai. Ye saare levels aapas me interact karte hain:
- Phonological Level: Speech sounds aur unke patterns. Components: Phones (physical sounds), Phonemes (meaning-distinguishing sound units), IPA (e.g., "cat" =
/k/ /a/ /t/), aur Prosody (stress & intonation: "I did THIS" vs "I DID this"). Applications: Speech Recognition (ASR), Text-to-Speech (TTS), Accent Recognition (Indian/British/American). - Morphological Level: Words chhote meaningful units (Morphemes) se kaise bante hain (
books = book + s;unhappy = un + happy). Components: Inflection, Derivation, Stemming, Lemmatization. - Lexical Level: Vocabulary aur isolated word meanings. Components: Tokenization (
"I'll come tomorrow."→ 4 tokens:I, 'll, come, tomorrow) aur Lexical Semantics (Synonymy, Antonymy, Hyponymy, Homonymy, Polysemy). - Syntactic Level: Words ko grammatically valid sentences me arrange karna (Constituency & Dependency Parsing). Cross-linguistic fact: English follows SVO (Subject-Verb-Object), jabki zyadaatar Indian languages (Hindi, Tamil, Telugu, Marathi) SOV hoti hain — Khasi (Meghalaya) is a famous SVO exception among Indian languages!
- Semantic Level: Sentence ka literal meaning compose karna. Tasks: Word Sense Disambiguation (WSD), Semantic Role Labeling (Agent/Recipient/Theme — "John gave Mary a book"), aur Named Entity Recognition (NER).
- Discourse Level: Single sentence se aage badhkar poore paragraph/article ke links samajhna. Components: Coherence (logical flow: "She went to the bakery. She bought bread." ✓ vs "...She washed her hair." ✗), Cohesion (connecting words: however, therefore, moreover), aur Anaphora Resolution ("John loves his dog. It follows him." →
it=dog, him=John). - Pragmatic Level: Real-world situational context, speaker intent, sarcasm aur indirect meaning samajhna. Components: Speech Acts (requests, promises, commands) aur Deixis (context-dependent words like
here,tomorrow). E.g., "It's cold in here" implicitly requests closing the window.
Processing Granularity (Text Units & NLP Applications)
| Granularity Level | Typical NLP Tasks & Applications |
|---|---|
| Character / String Level | Word tokenization, Sentence boundary detection, Regex pattern extraction |
| Word Level (Morphological) | POS tagging, Parsing, Chunking, Term extraction, Gene mention recognition (biomedical) |
| Sentence Level | Sentence classification, Ambiguity detection, Question Answering, Summarization |
| Sentence-Window (4–5 sentences) | Anaphora & Coreference resolution (tracking pronouns across nearby sentences) |
| Paragraph / Passage Level | Predicting rhetorical zones (e.g., Background, Method, Result in scientific papers) |
| Whole Document / Multi-Document | Document similarity calculation, Document clustering, Multi-document summarization |
4. Linguistic Terminology & Morphological Analysis
- Phoneme: Spoken language ki sabse chhoti sound unit jo meaning distinguish karti hai (
/p/in pat vs/b/in bat). - Grapheme: Written language ki sabse chhoti functional unit — letter ya letter group jo ek phoneme represent kare (
c,sh,ph). - Morpheme: Language ki sabse chhoti meaning-bearing unit jise aur meaningful tukdon me nahi toda ja sakta (
mangoes=mango+es;truthfulness=truth + ful + ness).
Classification of Morphemes
- Free Morphemes (standalone meaning):
- Lexical Morphemes: Open content words (Nouns, Verbs, Adjectives, Adverbs —
camera, chair, black). Naye words roz add hote hain. - Grammatical Morphemes: Closed function words (Prepositions, Conjunctions —
in, on, and). Fixed set hota hai.
- Lexical Morphemes: Open content words (Nouns, Verbs, Adjectives, Adverbs —
- Bound Morphemes (Affixes) (cannot stand alone; must attach to a stem): Prefix (re-form, be-cause), Suffix (lov-ed, love-able), Infix (passers-by).
Inflectional vs. Derivational Morphology
| Property | Inflectional Morphology | Derivational Morphology |
|---|---|---|
| Definition | Adapts an existing word for grammatical function (tense, plural, comparison) | Forms a new lexical word by attaching derivational affixes to a base |
| Change in POS? | Never changes POS category (book N → books N; cat → cats) | Often changes POS (teach V → teacher N; danger N → dangerous Adj); can also be class-maintaining (child → childhood) |
| Affix Position | In English, only Suffixes (or Infixes), never Prefixes | Can be both Prefixes (un-happy) and Suffixes (happy-ness) |
| Regularity | Highly regular and productive | Less regular / unpredictable |
Building a Morphological Parser (3 Mandatory Components)
- Lexicon: Stems aur affixes ki list with grammatical metadata (e.g., noun stem vs verb stem).
- Morphotactics: Ordering rules batate hain ki morphemes kis sequence me jud sakte hain (
use + able + ness = useableness ✓, parable + use + ness ✗). - Orthographic Rules: Morphemes judne par hone wale spelling changes ko model karte hain (
lady + s → ladies ✓, notladys ✗).
5. Classical Approaches of NLP
- Rule-Based / Symbolic Approach: Hand-coded grammars (CFG), Regex, Dictionaries, aur Morphological analyzers. Transparent & needs zero training data, par ambiguous/informal text par fail hota hai.
- Statistical / Corpus-Based Approach: Annotated/raw corpora se probabilities learn karta hai (N-grams, HMM, PCFG, Naive Bayes, TF-IDF). Ambiguity mathematically handle karta hai, par semantic similarity aur long-range context me limited hota hai.
6. Exam Preparation & Quick Revision (Chapter 1)
2-Mark, 5-Mark & 10-Mark Exam Questions with Model Answers
Q1 (2 Marks): Define Phoneme, Grapheme, and Morpheme with one example each.
Model Answer: A phoneme is the smallest distinctive sound unit in speech (e.g., /p/ vs /b/ in pat/bat). A grapheme is the smallest written unit representing a phoneme (e.g., 'p', 'sh'). A morpheme is the smallest indivisible unit of meaning in a language (e.g., 'mango' and '-es' in 'mangoes').
Q2 (5 Marks): Differentiate between Inflectional and Derivational Morphology. What are the 3 requirements of a Morphological Parser?
Model Answer: Present the 4-row Inflectional vs Derivational table above, then list and define the 3 parser components: (1) Lexicon, (2) Morphotactics, and (3) Orthographic Rules with examples.
Q3 (10 Marks): Explain the 7 Levels of Language Processing in NLP and the 5 types of Ambiguity with examples.
Model Answer: Draw Figure 1.2, explain each of the 7 levels (Phonological through Pragmatic) with components and applications, then list Lexical, Syntactic, Semantic, Anaphoric, and Pragmatic ambiguities with examples.
Chapter 2: Text Preprocessing, Regular Expressions, FSA & Chunking
Raw text ko clean tokens me badalne ka complete workflow: Tokenization, Normalization (Stemming vs Lemmatization), Stop-words & Keywords, Regular Expressions, Finite State Automata (3 full exam DFAs), aur Chunking.
1. Why Text Preprocessing? (End-to-End Workflow)
Raw text (social media, web pages, emails) me capitalization variations ("NLP" vs "nlp"), punctuation, HTML tags, aur morphological variants (play, plays, played, playing) bhare hote hain. Bina preprocessing ke vocabulary size unnecessarily huge ho jaata hai aur model related words ko alag-alag treat karta hai.
2. Word Tokenization
Tokenization raw character stream ko meaningful discrete units (Tokens) me split karta hai. Example: "Dipesh is an abnormal human" → [Dipesh] [is] [an] [abnormal] [human].
Why simple whitespace splitting is NOT enough: (1) Contractions: "I'll come tomorrow." → ["I", "'ll", "come", "tomorrow", "."]; (2) Multi-word named entities: "New York", "San Francisco"; (3) Abbreviations & numbers: "Dr. Sharma", "U.S.A.", "₹4,500.50"; (4) Modern LLMs use Subword Tokenization (BPE / WordPiece) taaki unknown words ko sub-parts me toda ja sake.
3. Word Normalization: Stemming vs. Lemmatization
Stemming (e.g., Porter Stemmer, Snowball Stemmer) suffix-stripping heuristics lagata hai (Knows, Known, Knowing → Know). Ye bahut fast hai par iske paas dictionary ya grammar knowledge nahi hoti! Result: Over-stemming (Date, Dated, Dating → "Dat" — meaningless root; university & universe dono univers ban jaate hain!) aur Under-stemming (better aur good ko alag rakhna).
Lemmatization is problem ko solve karta hai dictionary (WordNet) + morphological rules + POS tag use karke. Output hamesha ek valid dictionary word (Lemma) hota hai: Die, Died, Dead → Die; better → good; studies → study.
| Parameter | Stemming | Lemmatization |
|---|---|---|
| Core Method | Rule-based heuristic chopping of affixes (Porter / Lancaster) | Dictionary lookup (WordNet) + Morphological & POS analysis |
| Output Validity | May NOT be a real word (dating → dat, studies → studi) | Always a valid dictionary base word / Lemma (better → good) |
| Context Awareness | None | Uses POS tag (saw as Verb → see; as Noun → saw) |
| Speed & Cost | Very fast, low memory | Slower, requires lexicon + POS tagger |
| Best Use Cases | Large-scale IR indexing where speed is critical | Chatbots, QA, Sentiment Analysis, Machine Translation |
Tokenization is the process of segmenting raw text into discrete linguistic units called tokens. Stemming is a heuristic normalization technique that truncates word affixes to produce a root stem without guaranteeing dictionary validity, whereas Lemmatization uses lexical knowledge bases and part-of-speech information to map inflected word forms to their canonical dictionary base form (lemma).
4. Stop Words & Keyword Identification
- Stop Words: High-frequency functional words (
the, is, am, are, in, of, to, a, an) jo har document me milte hain aur topic differentiation me help nahi karte. Removing them reduces index size and noise. Critical Exception: Sentiment Analysis ("not good"), Phrase Search ("to be or not to be"), aur QA systems me stop words hatane se meaning destroy ho sakta hai! - Keyword Identification: Document ke most representative terms extract karna using frequency filtering, TF-IDF scores, POS filtering (keeping Nouns/Adjectives), ya graph algorithms like TextRank/RAKE.
5. Regular Expressions & Finite State Automata (FSA / DFA)
Regular Expressions (Regex) algebraic notation hain text patterns search/extract karne ke liye (e.g., [a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-z]{2,} for emails). Har Regex internally ek Finite State Automaton (FSA / DFA) se execute hota hai.
Formal 5-Tuple Definition of DFA: M = (Q, Σ, δ, q₀, F) where Q = finite set of states, Σ = input alphabet, δ: Q × Σ → Q = transition function, q₀ ∈ Q = start state, F ⊆ Q = set of accepting/final states.
Exam Design 1: FSA for baa+! (Sheep Language)
Pattern requires: one b, followed by at least two a's (a then a+), ending with !. States: Q = {q0, q1, q2, q3, q4}, Σ = {a, b, !}, Start = q0, Final = {q4}.
baa+!. Undefined transitions lead to an implicit dead/reject state (Φ).Exam Design 2: DFA for Binary Numbers Divisible by 5
Logic: Remainder modulo 5 can be 0, 1, 2, 3, 4 (states q0..q4, Final = q0). Reading a new binary digit d ∈ {0, 1} shifts the number left: new_val = 2 × old_val + d, so δ(qᵣ, d) = q_{(2r + d) mod 5}. (Optional separate start state q5 rejects empty string).
| State (Remainder r) | Input 0 → (2r + 0) mod 5 | Input 1 → (2r + 1) mod 5 |
|---|---|---|
q5 (Start, empty) | q0 | q1 |
*q0 (rem 0 — Final) | q0 (0) | q1 (1) |
q1 (rem 1) | q2 (2) | q3 (3) |
q2 (rem 2) | q4 (4) | q0 (5 mod 5 = 0) |
q3 (rem 3) | q1 (6 mod 5 = 1) | q2 (7 mod 5 = 2) |
q4 (rem 4) | q3 (8 mod 5 = 3) | q4 (9 mod 5 = 4) |
Dry Run: 1111₂ (Decimal 15): q5 —1→ q1 —1→ q3 —1→ q2 —1→ q0 (Accepted ✓). 110₂ (Decimal 6): q5 —1→ q1 —1→ q3 —0→ q1 (Rejected ✗).
Exam Design 3: DFA for Binary Strings Ending with 100
| State | Suffix Matched | Input 0 | Input 1 |
|---|---|---|---|
q0 (Start) | None | q0 | q1 |
q1 | Ends with 1 | q2 | q1 |
q2 | Ends with 10 | q3 | q1 |
*q3 (Final) | Ends with 100 | q0 | q1 |
6. Chunking (Shallow Parsing)
Full syntactic parsing (CFG/CKY) computationally heavy hoti hai. Chunking POS-tagged tokens ko non-overlapping phrases (NP, VP, PP) me group karta hai without building deep nested trees. Example: "Amaya ate the black cat." → [NP Amaya/NN] [VP ate/VBD] [NP the/DT black/JJ cat/NN]. Fast information extraction aur entity span finding me use hota hai.
7. Exam Preparation & Quick Revision (Chapter 2)
2-Mark, 5-Mark & 10-Mark Exam Questions
Q1 (5 Marks): Differentiate between Stemming and Lemmatization with examples.
Key Points: Mechanism, Dictionary validity (dating → dat vs better → good), POS awareness, Speed vs Accuracy, Use cases.
Q2 (10 Marks): Define a Finite State Automaton (5-tuple) and design DFAs for (a) baa+! and (b) Binary numbers divisible by 5.
Exam Tip: Always write M = (Q, Σ, δ, q₀, F), transition table, state diagram (double circle for final state), and 1 accepted + 1 rejected dry run.
Chapter 3: Statistical Language Modelling & N-Gram Models
Machine kaise decide karti hai ki "She is a tall girl" natural hai par "She is a long girl" galat? Chain Rule, Data Sparsity, Markov Property, Unigram/Bigram/Trigram models, complete university numericals, Smoothing, aur Perplexity.
- 1. Introduction & Why Do We Need Language Models?
- 2. Mathematical Evolution: Chain Rule → Sparsity → Markov Property
- 3. Unigram, Bigram & Trigram Models (With Workflow)
- 4. Complete Step-by-Step Worked Exam Numericals
- 5. Limitations, Laplace Smoothing & Perplexity
- 6. Exam Preparation & Quick Revision
1. Introduction & Why Do We Need Language Models?
Jab tum phone me type karte ho "See you ___", keyboard suggest karta hai tomorrow ya soon, na ki refrigerator. Automatic Speech Recognition (ASR) me "recognize speech" aur "wreck a nice beach" lagbhag same sound karte hain — computer sahi phrase kaise chunta hai? Language Model (LM) se!
A Language Model performs two equivalent mathematical tasks: (1) Assigning a probability P(w₁, w₂, ..., wₘ) to an entire word sequence, and (2) Predicting the probability of the next word given prior context P(wᵢ | w₁, ..., wᵢ₋₁). Real-world applications: Speech Recognition, Machine Translation (fluent target word ordering), Spell Checking / Autocorrect, Keyboard Autocomplete, aur Modern Generative AI (LLMs).
A Statistical Language Model is a probabilistic model that defines a probability distribution over sequences of words. Given a sequence W = w₁, w₂, ..., wₘ, it computes the joint sentence probability P(w₁, ..., wₘ) or the conditional probability of an upcoming word P(wᵢ | w₁, ..., wᵢ₋₁) to evaluate linguistic fluency and guide prediction.
2. Mathematical Evolution: Chain Rule → Sparsity → Markov Assumption
Step 1 — Chain Rule of Probability: Exact probability of a sentence is factored word-by-word:
Example: P("its water is so transparent") = P(its) × P(water|its) × P(is|its water) × P(so|its water is) × P(transparent|its water is so).
Maximum Likelihood Estimation (MLE) se counting karke probability nikalne ki koshish karo:
P(transparent | its water is so) = Count("its water is so transparent") / Count("its water is so").
Problem: Human language creative hai! 5–10 words ka exact phrase poore internet corpus me bhi 0 baar aa sakta hai (0 / 0 undefined!). Is Data Sparsity Problem ko solve karne ke liye hum Markov Property (Assumption) lagate hain: agla word poori history par nahi, sirf pichhle k words par depend karta hai!
3. N-Gram Models (Unigram, Bigram, Trigram)
| Model | Order (k) | Formula (MLE) | Behavior & Example |
|---|---|---|---|
| Unigram (N=1) | k = 0 | P(wᵢ) = C(wᵢ) / Total_Tokens | Words completely independent; generates random word soup ("Sixth, the, rupees, education...") |
| Bigram (N=2) | k = 1 | P(wᵢ | wᵢ₋₁) = C(wᵢ₋₁, wᵢ) / C(wᵢ₋₁) | Conditions on 1 previous word; local grammar appears (<s> marks sentence start, </s> marks end) |
| Trigram (N=3) | k = 2 | P(wᵢ | wᵢ₋₂, wᵢ₋₁) = C(wᵢ₋₂, wᵢ₋₁, wᵢ) / C(wᵢ₋₂, wᵢ₋₁) | Conditions on 2 previous words; much better fluency, par higher sparsity |
4. Complete Step-by-Step Worked Exam Numericals (From Your Notes)
Corpus: (1) <s> I am a human </s> | (2) <s> I am not a stone </s> | (3) <s> I I live in Mumbai </s>
Find: P(<s> I I am not </s>) using a Bigram Model.
Step 1 — Unigram Counts (Denominators): C(<s>) = 3, C(I) = 4 (1+1+2), C(am) = 2, C(not) = 1.
Step 2 — Bigram Counts (Numerators): C(<s>, I) = 3, C(I, I) = 1, C(I, am) = 2, C(am, not) = 1, C(not, </s>) = 0 (corpus me not ke baad sirf a aaya hai).
Insight: Sirf ek unseen bigram (not, </s>) ki wajah se poori sentence probability collapse hokar 0 ho gayi! Isiliye Smoothing zaroori hai.
Training Corpus (5 sentences): (1) <s> I am Jack </s> | (2) <s> Jack I am </s> | (3) <s> Jack I like </s> | (4) <s> Jack I do like </s> | (5) <s> do I like Jack </s>
Compute Bigram Probabilities for Last Words:
- Given
Jack(C(Jack)=5):P(I|Jack) = 3/5 = 0.6,P(</s>|Jack) = 2/5 = 0.4→ Most probable next word =I. (Answers Q1:<s> Jack ___and Q3:<s> Jack I am Jack ___). - Given
do(C(do)=2):P(like|do) = 1/2 = 0.5,P(I|do) = 1/2 = 0.5→ Tie:likeorI. (Answers Q2:<s> Jack I do ___). - Given
like(C(like)=3):P(</s>|like) = 2/3 = 0.67,P(Jack|like) = 1/3 = 0.33→ Most probable next word =</s>. (Answers Q4:<s> do I like ___).
5. Limitations of N-Grams, Smoothing & Perplexity
- Limitation 1 — Long-Distance Dependencies: "The computer which I had just put into the machine room on the fifth floor crashed." Bigram/Trigram sirf
"fifth floor"dekhega; use 12 words pehle aaya"computer"yaad hi nahi hoga! (Solved later by RNN/LSTM/Transformers). - Limitation 2 — Zero-Probability Problem → Laplace (Add-1) Smoothing: Har bigram count me +1 add karo aur denominator me vocabulary size
V:PLaplace(wᵢ | wᵢ₋₁) = ( Count(wᵢ₋₁, wᵢ) + 1 ) / ( Count(wᵢ₋₁) + V ) - Limitation 3 — No Semantic Generalization: Agar corpus me "cat drinks milk" hai par "dog drinks milk" nahi, toh N-gram
dogaurcatki similarity nahi samajhta (solved by Neural LMs & Embeddings). - Evaluation Metric — Perplexity (PP): Inverse probability of the test set normalized by word count
N. Intuition: "Average branching factor — har step par model kitne words me confused hai." Lower Perplexity = Better Language Model.PP(W) = P(w₁, w₂, ..., wₙ)^(-1/N) = ⁿ√( 1 / ∏ P(wᵢ | wᵢ₋₁) )
6. Exam Preparation & Quick Revision (Chapter 3)
Exam Questions & Revision Notes (Chapter 3)
Q1 (5 Marks): Explain Chain Rule, Markov Property, and N-gram models with limitations.
Q2 (10 Marks): Compute Bigram sentence probability (with and without Add-1 smoothing) and next-word prediction on a given corpus.
Quick Revision: Always include <s> and </s>; Bigram depends ONLY on 1 previous word; Zero count → Use Laplace Smoothing; Lower Perplexity = Better LM.
Chapter 4: Sequence Labeling — POS Tagging, HMM, Viterbi & NER
Har word ko sentence context ke hisaab se grammatical tag (POS) ya real-world entity tag (NER) kaise dete hain? Brill Tagger, Hidden Markov Model, Viterbi Dynamic Programming numerical + complexity proof, BIO/BIOES, aur Indian languages me NER challenges.
- 1. POS Tagging: Concepts, Classes, Tagsets, Challenges & Applications
- 2. Evolution of POS Taggers (Rule → Brill → Statistical → Neural)
- 3. Hidden Markov Model (HMM) & Viterbi Algorithm (Full Numerical + Proof)
- 4. Named Entity Recognition (NER): BIO/BIOES, Tagsets & Workflow
- 5. NER Ambiguities, Indian Language Challenges & Evaluation
- 6. Exam Preparation & Quick Revision
1. Part-of-Speech (POS) Tagging
What is POS Tagging? Sentence ke har word ko uske grammatical role aur surrounding context ke hisaab se ek label (Noun, Verb, Adjective, Determiner, etc.) dena. Example: The/DT little/JJ boy/NN plays/VBZ cricket/NN. Ek hi word alag context me alag POS ban sakta hai — jaise "back": the back door (JJ), on my back (NN), voters back (RB), back the bill (VB); ya "light": turn on the light (NN), bag is light (JJ), light the candle (VB); ya classic "Can(NNP) can(MD) can(VB) the can(NN)".
POS Tagging vs. Morphological Analysis
| Dimension | Morphological Analysis | POS Tagging |
|---|---|---|
| Scope | Word-based (internal root + affixes) | Sentence-based (surface form in surrounding context) |
| Tag Set | Smaller (only inflecting categories: N, V, Adj, Adv, Pron) | Larger (also includes non-inflecting categories: prepositions, conjunctions, particles) |
| Output per Word | Can produce multiple candidate analyses | Produces exactly one context-disambiguated tag |
Word Classes & Standard Tagsets
- Open Class (Content Words): New words continuously enter — Nouns (proper/common, count/mass, space & time nouns), Verbs (finite, non-finite, infinitives, gerunds, auxiliaries), Adjectives, Adverbs.
- Closed Class (Function Words): Fixed membership — Prepositions/Postpositions, Determiners, Pronouns, Conjunctions (coordinating/subordinating), Particles, Numerals, Quotatives (notable in Indian languages).
- Standard Tagsets: (1) Penn Treebank (Fine-grained English, ~45 tags:
NN, NNS, NNP, VB, VBD, VBZ, JJ, RB, DT, IN, PRP, CC), (2) Universal Dependencies (UD) (Google's minimalist cross-lingual tagset:NOUN, VERB, ADJ, ADV, ADP, DET, PRON), (3) BIS (Bureau of Indian Standards) (Hierarchical tagset for Indian languages — Hindi, Tamil, Telugu, Bengali, Marathi — supports postpositions, quotatives, space/time nouns).
6 Major Challenges of POS Tagging: (1) Lexical Ambiguity (book V vs N), (2) Context Dependency (beautiful vs beautifully), (3) Unknown / OOV Words (new brand/tech terms), (4) Morphological Complexity (play/plays/played/playing), (5) Informal Language ("u r gr8"), (6) Domain Dependency ("model" in fashion vs ML).
8 Key Applications: Speech Synthesis (pronunciation: reCORD verb vs RECord noun; INsult vs inSULT), Speech Recognition, Machine Translation, Information Retrieval, Information Extraction, Sentiment Analysis (adjectives/adverbs), Question Answering, Syntactic Parsing & NER.
2. Evolution of POS Taggers
| Approach | Internal Mechanism & Example | Pros | Limitations (Why Next Evolved) |
|---|---|---|---|
| 1. Rule-Based (e.g., EngCG — 3,700+ negative constraints) | Dictionary assigns all candidate tags; hand-written linguistic rules eliminate wrong ones (e.g., word after the → Noun; ends with -ly → Adv) | Interpretable; no labeled training data needed | Hard to scale/maintain; misses long-distance dependencies; lower accuracy on noisy text |
| 2. Transformation-Based (Brill Tagger, 1992) | 3-Step Loop: (1) Assign most frequent tag from corpus, (2) Iteratively apply automatically learned correction rules (e.g., "The boy played" → VBD; "was eaten by me" preceded by by → change VBD to VBN), (3) Keep rule giving max error reduction | Combines rule interpretability with corpus-driven learning | Slow training; restricted to fixed local rule templates |
| 3. Stochastic / Statistical (HMM, MaxEnt, CRF) | Learns probabilities from tagged corpus: P(run=Verb) = 3600/4800 = 0.75 + tag sequence probabilities (Bigram/Trigram). HMM = generative (Transition × Emission); MaxEnt/CRF = discriminative (arbitrary overlapping features) | Handles ambiguity mathematically; generalizes well | Needs large annotated corpus; struggles with unseen words |
| 4. Neural / Deep Learning (BiLSTM, BERT, ALBERT) | Automatically learns bidirectional contextual representations from raw + labeled text | State-of-the-art accuracy; handles OOV via subwords | High compute & data requirements; black-box |
3. Hidden Markov Model (HMM) & Viterbi Algorithm
POS tagging me humein sentence ke Words dikhai dete hain (Observations O), par unke POS Tags chhupe hote hain (Hidden States Q). Same logic weather example me: dost ne bataya ki usne [Walk, Shop, Clean] kiya (Observations) → tumhe guess karna hai ki mausam [Sunny, Rainy] ka sequence kya tha (Hidden States)!
3 Parameters of an HMM: (1) Initial Probability (π): P(q₁ = s), (2) Transition Probability (A): P(tagᵢ | tagᵢ₋₁), (3) Emission Probability (B): P(wordᵢ | tagᵢ). Goal: Find tag sequence T* = argmax_T ∏ P(tᵢ | tᵢ₋₁) · P(wᵢ | tᵢ).
[Walk, Shop, Clean]. Backtracking from the winning final state Rainy (0.00680) yields Sunny → Sunny → Rainy.Given: π(S)=0.6, π(R)=0.4 | Transitions: S→S: 0.7, S→R: 0.3, R→S: 0.6, R→R: 0.4 | Emissions: S:{Walk:0.6, Shop:0.3, Clean:0.1}, R:{Walk:0.2, Shop:0.5, Clean:0.3}.
- t=1 (Walk):
δ₁(S) = 0.6×0.6 = 0.36|δ₁(R) = 0.2×0.4 = 0.08. - t=2 (Shop):
δ₂(S) = 0.3 × max(0.7×0.36, 0.6×0.08) = 0.3 × max(0.252, 0.048) = 0.0756(from S).
δ₂(R) = 0.5 × max(0.3×0.36, 0.4×0.08) = 0.5 × max(0.108, 0.032) = 0.0540(from S). - t=3 (Clean):
δ₃(S) = 0.1 × max(0.7×0.0756, 0.6×0.054) = 0.1 × max(0.05292, 0.0324) = 0.005292(from S).
δ₃(R) = 0.3 × max(0.3×0.0756, 0.4×0.054) = 0.3 × max(0.02268, 0.0216) = 0.006804(from S). - Backtrack:
max(0.005292, 0.006804) = Rainy←Sunny←Sunny⇒ Sunny → Sunny → Rainy.
VITERBI(Observations O[1..T], States S[1..N], π, A, B):
for s in 1..N:
viterbi[s, 1] = π[s] * B[s, O[1]]
backptr[s, 1] = 0
for t in 2..T:
for s in 1..N:
viterbi[s, t] = max_{s' in 1..N} ( viterbi[s', t-1] * A[s', s] ) * B[s, O[t]]
backptr[s, t] = argmax_{s' in 1..N} ( viterbi[s', t-1] * A[s', s] )
best_last = argmax_{s in 1..N} viterbi[s, T]
return BACKTRACK(backptr, best_last) # Time: O(T * N²), Space: O(T * N)
Why Viterbi is Better (Complexity Proof): Brute-force HMM path search checks all Nᵀ sequences → O(Nᵀ) (exponential, impossible for real sentences). Viterbi stores only the best sub-path per state at each step: for each of T steps, N current states check N previous states → O(T · N²) (polynomial)!
4. Named Entity Recognition (NER)
What is NER? Unstructured text me se real-world proper names ko locate karna (Span Detection) aur unki semantic category assign karna (Type Classification). Generic vs Named Entity: Hotel (Generic ✗) vs Taj Hotel (Named Entity ✓); Airport (✗) vs Indira Gandhi International Airport (✓); Prime Minister (✗) vs Mr. Manmohan Singh (✓).
- 4 Core Categories + Extras: PERSON (Marie Curie, Satya Nadella), ORGANIZATION (Microsoft, OpenAI, United Airlines, IPCC), LOCATION (geographical: Sunshine Canyon), GPE (Geo-Political Entity) (administrative/political: Poland, New York, Palo Alto) — plus DATE/TIME (15 August 2026), MONEY ($5 billion), PERCENTAGES.
- What NER is NOT: NER ≠ Event Recognition (marriages, conferences), ≠ Template Creation, ≠ Coreference Resolution / Entity Linking (downstream tasks), ≠ Simple String Matching (cannot handle ambiguity/types).
- BIO / IO / BIOES Tagging Schemes: Because entities span multiple tokens, we encode boundaries:
- IO:
I(Inside),O(Outside) — fails to separate two adjacent entities of the same type! - BIO: Adds
B(Beginning) —Jane/B-PER Villano/I-PER of/O United/B-ORG Airlines/I-ORG. - BIOES: Adds
E(End) &S(Single-token). For "United Airlines Holding": IO →I I I| BIO →B I I| BIOES →B I E.
- IO:
- Standard NER Tagsets: ACE (hierarchical: Person → Individual/Group), ENAMEX (Person, Org, Location), NUMEX (numerical/money), TIMEX (dates/times).
- NER Modeling Approaches: Classical (HMM, CRF, MaxEnt, SVM) → Modern Neural (BiLSTM-CRF, BERT, LLMs).
5. NER Ambiguities, Indian Language Challenges & Evaluation
- Core Ambiguities: Segmentation & Boundary Ambiguity (
New YorkCity vs State), Overlapping Entities (President Obama= Title + Person), Type Ambiguity (Amazoncompany vs rainforest), Metonymy (Washington signed the treaty). Classic 4-Way "Washington" Example: (1) PERSON (Booker T. Washington), (2) ORG (sports team), (3) LOCATION (city), (4) GPE (state government passing a law). - 6 Special Challenges in Indian Languages (Indo-Aryan, Dravidian, Austroasiatic):
- No Capitalization Cue: English me
Rahul visited Delhicapitals se pehchana jaata hai; Hindiराहुल दिल्ली गयाme koi capital case nahi hota. - Morphological Richness / Agglutination: Postpositions attach directly to entities — e.g.,
रामसे=राम(PER) +से(marker), making boundary detection hard. - Common-Noun Overlap:
"Raja is my friend"(PERSON) vs"Raja flower"(common word). - Spelling Variations:
कृष्णappears as Krishna, Krishan, Krushna. - Low-Resource Pre-processing Tools: Fewer high-accuracy POS taggers/chunkers available.
- Scarcity of Annotated Corpora: Very limited labeled datasets (initiatives like AI4Bharat are bridging this gap).
- No Capitalization Cue: English me
- NER Evaluation & Challenges: Evaluated via Precision, Recall, F1, Exact Match Ratio, Entity-Level F1. 4 Evaluation challenges: (1) Consistent Annotation Guidelines, (2) Partial Matches (tagging only
"Obama"instead of"President Obama"), (3) Cross-Domain drop (News → Medical), (4) Cross-Lingual transfer.
Hidden Markov Model (HMM) is a generative probabilistic sequence model defined by initial state probabilities (π), state transition probabilities (A), and observation emission probabilities (B), decoded optimally in O(TN²) time using the Viterbi Dynamic Programming Algorithm. Named Entity Recognition (NER) is a sequence-labeling task that locates multi-token entity spans and classifies them into semantic types (PERSON, ORG, LOC, GPE) using BIO/BIOES schemes.
6. Exam Preparation & Quick Revision (Chapter 4)
Exam Questions (Chapter 4)
Q1 (10 Marks): Explain HMM and solve the Viterbi numerical for [Walk, Shop, Clean]. Prove why Viterbi beats brute-force search.
Q2 (10 Marks): Explain NER, BIO/BIOES schemes, "Washington" 4-way ambiguity, and 6 challenges of NER in Indian languages.
Q3 (5 Marks): Compare Rule-Based, Transformation-Based (Brill), and Statistical POS Taggers.
Chapter 5: Syntactic Processing — CFG, Parsing, CNF, CKY & PCKY
Sentence ki grammatical hierarchy (Parse Tree) kaise banti hai? CFG, Constituency vs Dependency, Top-Down vs Bottom-Up parsing (worked examples), CNF conversion, CKY algorithm, aur PCFG/PCKY full numerical.
- 1. Why CFG? Formal Definition & 3 Core Syntactic Concepts
- 2. Parsing: Top-Down vs Bottom-Up, Derivations & Ambiguity
- 3. Chomsky Normal Form (CNF) — 4 Conversion Steps
- 4. CKY Parsing Algorithm (Pseudocode + Worked Chart)
- 5. PCFG & PCKY Algorithm (Complete 7×7 Numerical & Trees)
- 6. Exam Preparation & Quick Revision
1. Why CFG? Formal Definition & Syntactic Concepts
FSA/Regex ke paas infinite nesting track karne ke liye stack memory nahi hoti. Human language me deeply nested recursive clauses hote hain: "The boy [who saw a girl [who smiled]] won the race" aur long-distance agreement: "The keys that I left on the table are missing." Is recursive tree structure ko model karne ke liye Context-Free Grammar (CFG) use hota hai.
Formal 4-Tuple: G = (N, Σ, R, S) — N: Non-terminals (S, NP, VP, Det, N), Σ: Terminals (actual words), R: Production rules (LHS → RHS), S: Start symbol.
- 3 Core Concepts of CFG: (1) Constituency (word groups acting as single units, e.g., Noun Phrase
"A well-weathered three-story structure"), (2) Grammatical Relations (Subject vs Object — in "She ate a mammoth breakfast",She=Subject,a mammoth breakfast=Object), (3) Subcategorization & Dependencies (verbwantallows infinitive "want to fly" or NP "want a flight", parfindrejects infinitive "found to fly" ✗). - Constituency Parsing vs. Dependency Parsing: Constituency parsing builds nested phrase trees (
S → NP VP). Dependency Parsing connects words directly via head → dependent links (chased → dog (subj),chased → ball (obj)) — directly revealing "who did what to whom" (widely preferred in modern NLU).
2. Parsing: Top-Down vs Bottom-Up & Structural Ambiguity
Derivation: Start symbol S se ek-ek rule apply karke sentence banana (Leftmost = always expand leftmost non-terminal; Rightmost = always expand rightmost non-terminal). Parsing = reverse process: given sentence se valid Parse Tree dhundhna.
Worked Examples (From Notes): (a) "The man read this book" using S→NP VP, NP→Det Nom, Nom→Noun, VP→Verb NP; (b) "Book that flight" using S→VP, VP→Verb NP, NP→Det Nom, Nom→SingularNoun — Top-Down expands S → VP → Verb NP → Book Det Nom → Book that flight, whereas Bottom-Up starts from Book (Verb), that (Det), flight (SingularNoun) and reduces upward to S!
| Parameter | Top-Down Parsing | Bottom-Up Parsing |
|---|---|---|
| Direction | Root S → down to input words | Input words → up to Root S |
| Derivation | Leftmost Derivation | Rightmost Derivation (in reverse) |
| Main Decision | Which production rule to apply next? | When to reduce a substring to a non-terminal? |
| Strength & Weakness | Moderate; wastes work on mismatched rules & loops infinitely on Left Recursion (NP → NP PP) | More powerful; handles left recursion, but builds useless sub-trees that never reach S |
| Examples | Recursive Descent Parser, LL Parser | Shift-Reduce (SR) Parser, CKY, LR Parser |
3. Chomsky Normal Form (CNF)
CKY algorithm binary parse trees require karta hai. A CFG is in CNF iff every rule is either A → B C (2 Non-Terminals) or A → a (1 Terminal). 4 Conversion Steps: (1) Remove ε-productions (A→ε), (2) Remove unit rules (S→VP ⇒ copy VP's rules into S), (3) Fix mixed rules (NP→the N ⇒ NP→Det N, Det→the), (4) Binarize long rules (S→Aux NP VP ⇒ S→X1 VP, X1→Aux NP; VP→V NP PP ⇒ VP→X2 PP, X2→V NP).
4. CKY (Cocke-Kasami-Younger) Parsing Algorithm
Why CKY? Backtracking parsers exponential time O(2ⁿ) lete hain kyunki same sub-spans baar-baar parse hote hain. CKY ek Bottom-Up Dynamic Programming parser hai (requires CNF) jo har span [i, j] ko sirf ek baar fill karta hai in O(n³ · |G|) time!
CKY(words[1..n], Grammar G in CNF):
for j = 1 to n:
table[j-1, j] = { A | (A -> words[j]) in G }
for i = j-2 down to 0:
for k = i+1 to j-1:
if B in table[i, k] and C in table[k, j] and (A -> B C) in G:
table[i, j].add(A)
return (S in table[0, n]) # Time: O(n³ * |G|)
Worked CKY Chart (From Notes): 0 the 1 cat 2 chased 3 the 4 mouse 5 (Grammar: S→NP VP, NP→Det N, VP→V NP):
| i \ j | 1 (the) | 2 (cat) | 3 (chased) | 4 (the) | 5 (mouse) |
|---|---|---|---|---|---|
| 0 | Det | NP (0,1)+(1,2) | Ø | Ø | S (0,2)+(2,5) ✓ |
| 1 | — | N | Ø | Ø | Ø |
| 2 | — | — | V | Ø | VP (2,3)+(3,5) |
| 3 | — | — | — | Det | NP (3,4)+(4,5) |
| 4 | — | — | — | — | N |
5. Probabilistic CFG (PCFG) & PCKY Algorithm
Evolution: CKY ambiguous sentences ke sabhi valid trees deta hai par most likely tree nahi batata. PCFG har rule ko probability deta hai (Σ P(A → β) = 1 for each LHS A). PCKY har cell me max probability + backpointer store karta hai (Viterbi : POS Tagging :: PCKY : Parsing).
Sentence: 0 she 1 saw 2 the 3 man 4 with 5 the 6 telescope 7
PCFG (CNF): S→NP VP (1.0), VP→V NP (0.6), VP→VP PP (0.4), NP→Det N (0.5), NP→NP PP (0.2), NP→she (0.3), PP→P NP (1.0), Det→the (1.0), N→man (0.5), N→telescope (0.5), V→saw (1.0), P→with (1.0).
- Length 1:
[0,1] NP:0.3,[1,2] V:1.0,[2,3] Det:1.0,[3,4] N:0.5,[4,5] P:1.0,[5,6] Det:1.0,[6,7] N:0.5. - Length 2–3:
[2,4] NP = 0.5×1.0×0.5 = 0.25|[5,7] NP = 0.25|[1,4] VP = 0.6×1.0×0.25 = 0.15|[4,7] PP = 1.0×1.0×0.25 = 0.25|[0,4] S = 1.0×0.3×0.15 = 0.045. - Span [2,7] NP:
0.2 × 0.25 × 0.25 = 0.0125. - Span [1,7] VP (2 Competing Splits!):
k=4(VP→VP[1,4] PP[4,7]):0.4 × 0.15 × 0.25 = 0.015(MAX — stored with backpointer!)k=2(VP→V[1,2] NP[2,7]):0.6 × 1.0 × 0.0125 = 0.0075
- Span [0,7] S (
S→NP[0,1] VP[1,7]): Tree 1 (VP attach) =1.0 × 0.3 × 0.015 = 0.0045(BEST ✓) vs Tree 2 (NP attach) =1.0 × 0.3 × 0.0075 = 0.00225.
A Context-Free Grammar (CFG) is a 4-tuple G = (N, Σ, R, S) defining the syntactic structure of a language. The CKY Algorithm is an O(n³|G|) bottom-up dynamic programming parser for CFGs in Chomsky Normal Form (CNF). PCFG/PCKY attaches probabilities to rules to resolve structural ambiguity by finding the maximum-likelihood parse tree.
6. Exam Preparation & Quick Revision (Chapter 5)
Exam Questions (Chapter 5)
Q1 (5 Marks): Differentiate between Top-Down and Bottom-Up Parsing, and Constituency vs Dependency Parsing.
Q2 (10 Marks): Convert a CFG to CNF and construct the PCKY matrix for "she saw the man with the telescope" to pick the best parse tree.
Chapter 6: Semantic, Discourse & Pragmatic Processing
Syntax ke baad asli "Meaning" kaise nikalte hain? Knowledge Representation (WordNet), saare Lexical Semantic Relations, WSD & Lesk Algorithm (7 components + SVG), Semantic Role Labeling, Coreference Resolution, aur Pragmatics vs Discourse.
1. Semantic Analysis & Knowledge Representation
Introduction: Grammar (Syntax) sirf ye batati hai ki sentence structurally sahi hai ya nahi; Semantic Analysis us sentence ka actual, literal meaning nikalta hai. Example: "Your teaching is very good, I scored full marks in my Viva" — human turant samajh jaata hai ki student khush hai, par machine ko word meanings aur relationships ko represent karna seekhna padta hai (warna sarcasm ya context misinterpret ho jayega).
5 Core Applications of Semantic Analysis: (1) Information Extraction, (2) Text Summarization, (3) Information Retrieval, (4) Machine Translation, (5) Expert Systems (e.g., Grammarly).
2. WordNet & Lexical Semantic Relations
WordNet English ka ek massive, freely available lexical database hai jo normal alphabetical dictionary se bilkul alag hai — ye words ko concepts (cognitive synonyms) ke groups me store karta hai jinhe Synsets kehte hain (e.g., {car, auto, automobile}). Har synset me ek short definition (Gloss) aur usage examples hote hain, aur synsets semantic relations se interlinked hote hain.
WordNet Scale (From Notes): Nouns: 117,097 | Verbs: 11,488 | Adjectives: 22,141 | Adverbs: 4,601.
4 Major Applications of WordNet: (1) Automatic Query Expansion (IR search me synonyms include karna), (2) Document Summarization (lexical chains), (3) Concept Identification, (4) Word Sense Disambiguation (WSD).
| Lexical Relation | Conceptual Meaning (Hinglish) | Types / Properties & Exam Examples |
|---|---|---|
| 1. Synonymy | Alag words jo same/nearly identical concept express karein | shut / close, car / automobile, beautiful / gorgeous, mistake / error, rich / wealthy |
| 2. Antonymy | Opposite ya contrasting meanings (3 types!) | • Complementary (binary, no middle): right/wrong, interior/exterior, inhale/exhale• Gradable (continuous spectrum): young/old, hot/cold• Relational (opposite viewpoints): doctor/patient, brother/sister |
| 3. Hyponymy & Hypernymy | IS-A hierarchy (Subclass vs Superclass). Transitive! | car is a hyponym (subclass) of vehicle; vehicle is a hypernym (superclass) of car. Also: dog → animal, strawberry → fruit. Transitive: violet → purple → color. |
| 4. Meronymy | PART-OF relationship (constituent part) | coconut is a meronym of coconut tree; wheel is a meronym of car |
| 5. Homonymy | Same spelling & pronunciation, bilkul unrelated meanings | bat (wooden cricket/baseball bat vs flying mammal); bank (river side vs financial institution) |
| 6. Polysemy | Same word, different par related meanings | newspaper ("The artist sued the newspaper" [company] vs "She read the newspaper" [physical object]) |
3. Word Sense Disambiguation (WSD) & Lesk Algorithm
What is WSD? Jab ek hi word ke multiple dictionary senses hon (e.g., "She killed him with a baseball bat"), toh surrounding context dekhkar sahi sense select karne ko Word Sense Disambiguation (WSD) kehte hain. 3 approaches: (1) Knowledge/Dictionary-Based (Lesk), (2) Supervised / Unsupervised ML, (3) Hybrid.
Sentence: "The bank can guarantee deposits will eventually cover future tuition costs because it invests in adjustable rate mortgage."
- Context Bag (after stop-word removal):
{guarantee, deposits, eventually, cover, future, tuition, costs, invests, adjustable, rate, mortgage}. - Sense 1 (Financial Institution): Gloss + Example = "A financial institution that accepts deposits... holds the mortgage on my home" → Overlap = 2 (
deposits, mortgage). - Sense 2 (River Bank): Gloss + Example = "Sloping land beside body of water... pulled canoe up" → Overlap = 0.
- Result: 2 > 0 ⇒ Sense 1 (Financial Institution) selected! Limitation of Lesk: Exact string matching par depend karta hai; short glosses me synonyms match nahi hote (solved later by BERT contextual embeddings).
4. Semantic Role Labeling (SRL), Coreference & Entity Linking
- Semantic Role Labeling (SRL): Main verb (Predicate) ke respect me har phrase ka role identify karna ("Who did what to whom, how, when, where"). Example: "Mary [AGENT] broke [PREDICATE] the window [PATIENT] with a hammer [INSTRUMENT]." Active ("Mary broke the window") aur Passive ("The window was broken by Mary") dono ka SRL identical hota hai!
- Coreference Resolution & Anaphora Resolution: Text me alag-alag mentions jo ek hi real-world entity ko refer karein unhe cluster karna (e.g., "Maria said she would come" →
she = Maria). Jab ek pronoun pichhle noun (antecedent) ko point kare, use Anaphora Resolution kehte hain. - Entity Linking: Textual mention ko ek unique Knowledge Base / Wikipedia ID se link karna (e.g.,
"Paris"→ Paris, France vs Paris Hilton).
5. Pragmatics vs. Discourse Analysis
| Aspect | Discourse Analysis | Pragmatics |
|---|---|---|
| Unit of Analysis | Connected multi-sentence text, articles, or conversations | Individual utterance interpreted in real-world situational context |
| Core Focus | Coherence (logical flow), Cohesion (grammatical connectors like however, therefore), Anaphora | Intended meaning vs Literal meaning (Semantics = literal; Pragmatics = intended), Speech Acts (request, warn, promise), Deixis (here, tomorrow) |
| 3 Context Types (Discourse) | 1. Situational Context (physical surroundings) 2. Background Knowledge (cultural/interpersonal) 3. Co-textual Context (what was said earlier) | Uses speaker, listener, time, place, and social norms |
| Examples (From Notes) | "Namaste! Mere deshwasiyo. Ghar se bahar matt niklo." (connected speech) | Sign "Ladies" beside a bus seat → Pragmatically means "Reserved for women"! |
WordNet is a large lexical knowledge base of English that groups words into sets of cognitive synonyms called synsets, each accompanied by a gloss and linked via conceptual-semantic relations. Word Sense Disambiguation (WSD) is the task of determining the exact intended sense of an ambiguous word in context, classically solved by the Lesk Algorithm through maximum word overlap between a context bag and dictionary sense bags.
6. Exam Preparation & Quick Revision (Chapter 6)
Exam Questions (Chapter 6)
Q1 (10 Marks): Explain WSD and the Lesk Algorithm with its architecture diagram, 7 components, and a worked example.
Q2 (5 Marks): Explain WordNet and differentiate between Synonymy, Antonymy (3 types), Hyponymy, Meronymy, Homonymy, and Polysemy.
Q3 (5 Marks): Differentiate between Semantics, Pragmatics, and Discourse Analysis with examples.
Chapter 7: Complete Information Retrieval (IR) System Workflow, Indexing, TF-IDF & Similarity
Google / Search Engine andar se step-by-step kaise kaam karta hai? Core IR Terminology, Offline Indexing vs Online Querying Architecture Diagram, Term-Document Incidence Matrix, 4-Step Inverted Index Construction (SPIMI/MapReduce), Positional Index, Boolean Retrieval (INTERSECT), BoW → Vector Space Model (TF-IDF), aur Jaccard/Dice/Cosine Similarity.
- 1. What is IR? Core Terminology & DB vs IR vs QA
- 2. Complete IR System Workflow (Offline Indexing vs Online Querying SVG)
- 3. Linear Scan → Incidence Matrix → Inverted Index (4-Step Construction & Positional Index)
- 4. Boolean Retrieval, INTERSECT Algorithm & Strengths/Weaknesses
- 5. Ranked Retrieval: Bag of Words → Vector Space Model & TF-IDF
- 6. Text Similarity: Jaccard, Dice/Overlap & Cosine Similarity (vs Euclidean)
- 7. Exam Preparation & Quick Revision
1. What is Information Retrieval (IR)? Core Terminology & Comparisons
Introduction: Information Retrieval (IR) ka matlab hai ek bahut bade unstructured text collection (web pages, emails, legal docs, e-commerce listings) me se aise documents dhoondhna aur rank karna jo user ki Information Need ko satisfy karein. Key reality: user kabhi perfect query nahi likhta aur machine document ko insaan ki tarah "samajhti" nahi — isliye IR relevance ranking ke around design hota hai. Modern QA aur RAG systems ka first stage bhi IR hi hota hai!
Core IR Terminology (From Notes)
| IR Term | Exact Meaning | Concrete Example |
|---|---|---|
| Document | The fundamental retrievable unit (web page, email, paragraph, product listing) | One news article |
| Corpus / Collection | The complete set of all documents searchable by the IR system | Entire newspaper archive |
| Information Need | What the user actually wants to find out (in their head) | "Is it safe to take ibuprofen with paracetamol?" |
| Query | What the user types into the search box (an imperfect expression of the need) | "ibuprofen paracetamol together" |
| Relevance | Judgement (binary or graded) that a document satisfies the information need (not just matching query words!) | Medical page explaining drug interactions |
| Term | Normalized indexed unit produced after preprocessing | rank (normalized from "ranking") |
| Index | Pre-built data structure for millisecond lookup | Inverted Index |
Database Search (SQL) vs. Information Retrieval (IR) vs. Question Answering (QA)
| Aspect | Database Query (SQL) | Information Retrieval (IR) | Question Answering (QA) |
|---|---|---|---|
| Data Type | Structured (tables, rows, schemas) | Unstructured or semi-structured text | Text passages or Knowledge Bases |
| Query Form | Formal exact language (SQL) | Free keywords or natural language (often vague) | Natural-language question |
| Matching | Exact deterministic match (row matches or not) | Partial relevance scoring & ranking | Extract or generate a specific answer |
| Output | Set of database rows | Ranked list of relevant documents | Short concise answer (ideally with evidence) |
| Correctness | Deterministic (Right / Wrong) | Subjective (Precision, Recall, NDCG over queries) | Answer Accuracy / Exact Match / F1 |
2. Complete IR System Workflow: Offline Indexing vs. Online Querying
IR system ko do halves me divide kiya jaata hai: Offline Side (Indexing) — expensive work jo pehle se ek baar karke Inverted Index disk/RAM me store kar liya jaata hai; aur Online Side (Query Time) — jab user query type karta hai, toh milliseconds me postings lists read karke documents rank kar diye jaate hain. Pay the cost once at indexing time, so every user query is super cheap!
"queries" stem hokar "queri" store hua aur query stem nahi hui, toh match kabhi nahi hoga!End-to-End Query Lifecycle (Step-by-Step Walkthrough)
- Step 1 (Offline Crawling & Acquisition): Web crawler ya ingestion pipeline saare documents collect karke har document ko unique
docIDassign karti hai. - Step 2 (Offline Preprocessing): Tokenization, lowercasing, stop-word removal, stemming/lemmatization se raw text clean index terms me badalta hai.
- Step 3 (Offline Index Construction): Indexer sabhi
(term, docID)pairs ko sort & merge karke Inverted Index (Dictionary in RAM + Postings Lists on disk) banata hai, saath metfaurdfstore karta hai. - Step 4 (Online Query Processing): User query type karta hai → wahi exact preprocessing pipeline chalti hai → clean query terms milte hain.
- Step 5 (Postings Lookup & Candidate Filtering): System sirf unhi query terms ki postings lists fetch karta hai (Term-at-a-Time scoring) — poora corpus kabhi scan nahi hota!
- Step 6 (Scoring & Ranking): Candidate documents ko Boolean logic ya Vector Space Model (TF-IDF + Cosine Similarity / BM25) se score karke Top-K ranked list user ko dikhai jaati hai.
3. Indexing Evolution: Linear Scan → Incidence Matrix → Inverted Index
Linear Scan 10 files ke liye theek hai, billions of pages par fail. Next idea: Term-Document Incidence Matrix (rows = terms, columns = docs, cell = 1 if present else 0). Scale Math (From Notes): Suppose N = 1,000,000 documents and V = 500,000 unique terms → Matrix has 5 × 10¹¹ (500 billion) cells! If each doc averages 1,000 tokens, at most 10⁹ cells are 1 → 99.8% of the matrix is pure ZEROS!
Solution — Inverted Index: Sirf 1s store karo! Do parts: (1) Dictionary (in RAM via Hash Table / B-Tree, stores term + df), (2) Postings Lists (on disk, often gap-compressed, stores sorted docID: tf).
Complete Worked Construction (From Notes): D1 = "search engine ranks web pages" | D2 = "web crawler collects web pages" | D3 = "search engine uses inverted index"
| Term | D1 | D2 | D3 | df | Inverted Index Postings (docID: tf) |
|---|---|---|---|---|---|
collects | 0 | 1 | 0 | 1 | D2:1 |
crawler | 0 | 1 | 0 | 1 | D2:1 |
engine | 1 | 0 | 1 | 2 | D1:1, D3:1 |
index | 0 | 0 | 1 | 1 | D3:1 |
inverted | 0 | 0 | 1 | 1 | D3:1 |
pages | 1 | 1 | 0 | 2 | D1:1, D2:1 |
ranks | 1 | 0 | 0 | 1 | D1:1 |
search | 1 | 0 | 1 | 2 | D1:1, D3:1 |
uses | 0 | 0 | 1 | 1 | D3:1 |
web | 1 | 1 | 0 | 2 | D1:1, D2:2 |
4-Step Inverted Index Construction Workflow & Large-Scale Indexing
- Assign a unique integer
docIDto every document. - Tokenize & normalize each document to emit a stream of
(term, docID)pairs. - Sort all pairs alphabetically by
term, and secondarily bydocID. - Merge duplicate
(term, docID)pairs to compute term frequencytf, group by term into postings lists, and count list length to get document frequencydf.
Scaling to Web Size: Jab collection RAM me fit nahi hota, toh hum block-by-block indexing use karte hain: BSBI (Blocked Sort-Based Indexing), SPIMI (Single-Pass In-Memory Indexing), ya distributed MapReduce.
Positional Index (For Phrase Queries): Standard inverted index "inverted index" aur "index inverted" me farq nahi kar sakta! Positional Index har posting me term ki exact word positions store karta hai (e.g., inverted: D3[pos 4], index: D3[pos 5] → consecutive positions pos(index) = pos(inverted) + 1 ⇒ Phrase Match!). Trade-off: 2–4× larger index size.
4. Boolean Retrieval & Linear INTERSECT Algorithm
Queries use AND, OR, NOT directly on postings lists: search AND engine = {D1,D3} ∩ {D1,D3} = {D1,D3} | web AND NOT search = {D1,D2} − {D1,D3} = {D2} | web OR index = {D1,D2,D3}. Because postings lists are sorted, AND runs via linear two-pointer merge in O(|p1| + |p2|) time! Optimization: Multi-term AND queries ko hamesha increasing order of df (rarest term first) process karo taaki intermediate results chhote rahein.
INTERSECT(p1, p2):
answer = []
while p1 and p2 are not exhausted:
if docID(p1) == docID(p2):
answer.append(docID(p1)); advance(p1); advance(p2)
else if docID(p1) < docID(p2):
advance(p1)
else:
advance(p2)
return answer # Cost: O(|p1| + |p2|)
| Boolean Retrieval Strengths | Boolean Retrieval Weaknesses (Why Ranked Retrieval Evolved) |
|---|---|
| Precise, predictable, and 100% explainable (still used in legal, patent & medical literature reviews) | No Ranking: All matching documents are treated as equally relevant |
| Very fast with an Inverted Index | "Feast or Famine": AND often returns 0 docs; OR returns thousands of docs |
| Full expert user control & reproducibility | Requires structured Boolean syntax; weights all query terms equally |
5. Ranked Retrieval: Bag of Words → Vector Space Model & TF-IDF
Bag of Words (BoW) har document ko raw word-count vector me badalta hai (ignores word order). Limitation: Common words dominate counts. Vector Space Model (Salton, 1960s–70s) har document aur query ko high-dimensional space me vector banata hai aur TF-IDF weights assign karta hai:
idf(t) = log10(N / df(t)) (Karen Spärck Jones, 1972)
w(t, d) = wtf(t, d) × idf(t)
| Log-Scaled TF Intuition (Raw tf → 1 + log₁₀ tf) | IDF Intuition (N = 1,000,000 docs) |
|---|---|
tf=1 → 1.00 | tf=2 → 1.30 | tf=3 → 1.48 | tf=5 → 1.70 | tf=10 → 2.00 | tf=100 → 3.00 | df=1 → idf=6 (very rare/informative) | df=100 → idf=4 | df=10,000 → idf=2 | df=1,000,000 → idf=0 (useless!) |
Corpus (N=3): D1 ("search engine ranks web pages"), D2 ("web crawler collects web pages"), D3 ("search engine uses inverted index"). Query Q = "web engine".
- IDF:
df(web)=2 ⇒ idf=log₁₀(3/2)=0.176|df(engine)=2 ⇒ idf=0.176. - Vectors on [web, engine]:
Q = [0.176, 0.176](||Q||=0.249) |D1 = [0.176, 0.176](||D1||=0.249) |D2 = [(1+log₁₀2)×0.176, 0] = [0.229, 0](||D2||=0.229) |D3 = [0, 0.176](||D3||=0.176). - Cosine Scores:
cos(Q, D1) = 1.00(Rank #1!) |cos(Q, D2) = 0.707(Rank #2 tie) |cos(Q, D3) = 0.707(Rank #2 tie).
Limitations of TF-IDF VSM: (1) Bag-of-words ignores order ("dog bites man" = "man bites dog"), (2) Term independence / Vocabulary Mismatch (car and automobile have 0 similarity), (3) Crude length normalization (improved by BM25).
6. Text Similarity Methods
- Jaccard Similarity:
Jaccard(A, B) = |A ∩ B| / |A ∪ B|(Range 0–1; set-based, ignores frequency). Example:A={cat, sat, mat},B={cat, sat, hat}→2/4 = 0.5. - Dice & Overlap Similarity Coefficients:
Dice(A, B) = 2|A ∩ B| / (|A| + |B|);Overlap(A, B) = |A ∩ B| / min(|A|, |B|). - Cosine Similarity:
cos(q, d) = (q · d) / (||q|| · ||d||)(Range -1 to 1; 0 to 1 for non-negative TF-IDF). Why Cosine beats Euclidean Distance: Ek document ko copy-paste karke double kar do → vector length 2× ho gayi (huge Euclidean distance!), par direction same hai ⇒ Cosine = 1.0! Long documents unfairly win nahi karte.
Information Retrieval (IR) is the discipline of indexing, searching, and ranking unstructured textual documents from a large collection to satisfy a user's information need. Modern IR separates expensive offline indexing (building an Inverted Index) from millisecond online query ranking (using Boolean retrieval or Vector Space TF-IDF + Cosine Similarity).
7. Exam Preparation & Quick Revision (Chapter 7)
Exam Questions (Chapter 7)
Q1 (10 Marks): Explain the complete Information Retrieval System architecture (Offline vs Online) with a neat diagram. Explain Inverted Index construction and Boolean INTERSECT algorithm.
Q2 (10 Marks): Compute TF-IDF weights and Cosine Similarity for a given document collection and query. Why is Cosine Similarity preferred over Euclidean Distance?
Chapter 8: Word Embeddings — Word2Vec & Evolution to Contextual Models
One-Hot Encoding → Word2Vec (CBOW & Skip-gram) → GloVe → FastText → BERT/RoBERTa/GPT ka complete evolution, whiteboard matrix math, Negative Sampling, Analogies, Gensim Python code, aur 10 Viva/Interview Q&As.
- 1. Why Dense Embeddings? One-Hot / BoW / TF-IDF Limitations
- 2. Word2Vec Internals: CBOW vs Skip-gram + Whiteboard Matrix Math
- 3. Negative Sampling, Cosine Similarity, Analogies & Gensim Code
- 4. Full Evolution: Word2Vec → GloVe → FastText → BERT / RoBERTa / GPT
- 5. Class Activity Solutions & 10 Interview/Exam Q&As
1. The Problem Before Word2Vec (Why One-Hot / BoW / TF-IDF Failed)
Vocab = {king, queen, apple, mango}. One-Hot Vectors: king=[1,0,0,0], queen=[0,1,0,0], apple=[0,0,1,0], mango=[0,0,0,1].
1. Curse of Dimensionality & Sparsity: 100k vocabulary ⇒ 100k-length vectors with 99,999 zeros.
2. Zero Semantic Similarity: king · queen = 0 and king · apple = 0 — every word is equally orthogonal!
Breakthrough — Distributional Hypothesis: "Words occurring in similar contexts tend to have similar meanings." Word2Vec learns compact, fixed-size dense vectors (e.g., 50–300 dims) from raw text contexts so king=[0.82, 0.15, -0.34, 0.67] and queen=[0.79, 0.19, -0.29, 0.70] point in similar directions!
| Property | One-Hot Encoding | Word2Vec (Dense Embeddings) |
|---|---|---|
| Vector Size | Vocabulary-sized (V, huge) | Compact, fixed dimension (D = 50..300) |
| Values | Sparse (mostly zeros) | Dense learned continuous real numbers |
| Semantic Similarity | Not encoded (orthogonal) | Captured via vector closeness & analogies |
| How Created | Manual index assignment | Self-supervised learning from sliding context windows |
| OOV Handling | Needs vocabulary entry | Standard Word2Vec cannot embed unseen words directly |
2. Word2Vec Architectures: CBOW vs. Skip-gram & Internal Math
Corpus, Vocabulary & Context Window: Sentence: "The cat sits on the mat." Target = "sits", Window radius = 2 → Context = {The, cat, on, the}.
Memory Cue: CBOW = Context predicts Center word ("The cat ___ on the mat" → sits); Skip-gram = Center word predicts surrounding Context words ("sits" → cat, on, the, mat).
W ∈ ℝ^(V×D) and Output Matrix W' ∈ ℝ^(D×V)).Step-by-Step Internal Math (Matching Your Class Whiteboard!)
Sentence: "I love machine learning." | V = 4, D = 100 → Embedding matrix W is 4 × 100. Target = machine (row 3), Window = 1 → Context = (love [row 2], learning [row 4]).
- CBOW: Look up
W[2]andW[4]→ Average in Hidden Layer:h̄ = (W[2] + W[4]) / 2(1 × 100) → Multiply by Output MatrixW'(100 × 4) to get 4 logits[y¹, y², y³, y⁴]→ Apply Softmax:P(yⁱ) = e^(yⁱ) / (e^(y¹)+e^(y²)+e^(y³)+e^(y⁴))→ Compare with true targetmachine([0,0,1,0]), compute Cross-Entropy loss, and backpropagate to updateWandW'. - Skip-gram: Feed target vector
W[3](1 × 100) → Multiply byW'→ Softmax → Predict both context pairs(machine, love)and(machine, learning). After training, rows ofWare our learned Word2Vec embeddings! (ForV=10,000, D=100, total parameters inW=1,000,000).
3. Negative Sampling, Analogies & Gensim Implementation
- Why Negative Sampling? Full Softmax over
V = 100,000words updates all 100,000 output vectors on every single word pair — way too slow! Negative Sampling turns it into binary logistic classification: update only 1 positive context word + k = 5 to 20 randomly sampled negative words (e.g.,(machine, banana)). Massive speedup! - Vector Arithmetic & Analogies:
v(king) − v(man) + v(woman) ≈ v(queen);v(Paris) − v(France) + v(Italy) ≈ v(Rome). Important caveat: Not guaranteed universally, and embeddings absorb social/gender biases present in the training corpus.
from gensim.models import Word2Vec
sentences = [
["i", "love", "machine", "learning"],
["i", "love", "deep", "learning"],
["machine", "learning", "is", "useful"],
["deep", "learning", "uses", "neural", "networks"],
["cats", "and", "dogs", "are", "animals"]
]
# sg=1 -> Skip-gram; sg=0 -> CBOW
model = Word2Vec(sentences=sentences, vector_size=50, window=2, min_count=1, workers=1, sg=1, epochs=100)
print(model.wv["learning"][:5]) # Dense 50-dim vector
print(model.wv.most_similar("learning", topn=3)) # Top 3 nearest neighbors
print(model.wv.similarity("machine", "learning")) # Cosine similarity
4. Evolution: Word2Vec → GloVe → FastText → BERT / RoBERTa / GPT
| Technique | How It Computes Embeddings | Limitation of Previous Solved | Remaining Limitation |
|---|---|---|---|
| Word2Vec | Local sliding context window (CBOW / Skip-gram) | Solved One-Hot sparsity & lack of semantic similarity | Local only; fails on OOV words; static (one vector per word) |
| GloVe | Global word-word co-occurrence matrix factorization across entire corpus | Captures global corpus statistics alongside local meaning | Still static & fails on OOV words |
| FastText | Word2Vec + character n-gram subwords (playing → play, lay, ayi, ying) | Solves OOV words & morphologically rich languages (e.g., playingly) | Still static — same vector for both senses of "bank" |
| BERT / RoBERTa | Bidirectional Transformer reading full left + right sentence (RoBERTa = more data & longer training) | Contextual Embeddings! "money in the bank" ≠ "bank of the river" | Heavy compute & memory compared to Word2Vec |
| GPT | Causal (left-context only) Transformer predicting next token | Enables autoregressive NLG + contextual representations | Unidirectional left-to-right context |
Word2Vec is a self-supervised, shallow neural network technique grounded in the Distributional Hypothesis that learns compact, dense vector representations (embeddings) from word-context co-occurrences using either CBOW (context → target) or Skip-gram (target → context), typically accelerated via Negative Sampling.
5. Class Activity Solutions & Top Interview / Exam Q&As
Solved Class Activity + 10 Viva / Interview Questions (From PPT)
Class Activity: "The student reads a book." (Target = "reads", Window = 1)
1. Context words = {student, a}. 2. Skip-gram pairs = (reads, student), (reads, a). 3. CBOW = Input [student, a] → Target: reads. 4. Why one vector for "book"? Standard Word2Vec is static (one row in W per vocab word). 5. Advantage: compact semantic similarity; Limitation: cannot disambiguate polysemy or handle OOV.
Quick Viva Q&As:
- Supervised or Unsupervised? Self-supervised (targets created automatically from raw text).
- Word2Vec vs TF-IDF? Word2Vec = dense learned context vectors; TF-IDF = sparse corpus-frequency vectors.
- Can Word2Vec disambiguate "bank"? No — requires contextual models like BERT.
Chapter 9: Evaluation Measures & Real-World Applications of NLP
NLP models ko scientifically evaluate kaise karte hain (Confusion Matrix, Precision, Recall, F₁, BLEU, ROUGE, Perplexity), aur tumhare syllabus ke sabhi NLP Applications ka complete internal workflow aur diagrams.
- 1. Performance & Correctness Measures (Classification, NER & NLG)
- 2. Question Answering (QA) System — 3-Stage Workflow SVG
- 3. Opinion Mining, Sentiment Analysis & Text Classification
- 4. Document Summarization (Extractive vs Abstractive SVGs)
- 5. Machine Translation (RBMT, SMT, HMT, NMT)
- 6. Recommendation Systems, Ontology Construction & Emerging NLG
- 7. Exam Preparation & Quick Revision
1. Performance & Correctness Measures
Maan lo ek 100-word article me sirf 5 Named Entities hain (95% tokens O hain). Ek dumb model jo har word ko O predict kare, uski Accuracy = 95% hogi — par usne 0 entities pakdi! Imbalanced NLP tasks (NER, Spam, IR) me isliye Confusion Matrix → Precision, Recall, F-Measure use hote hain.
| Gold Standard: Positive (Actually True) | Gold Standard: Negative (Actually False) | |
|---|---|---|
| System Predicted: Positive | TP (True Positive — Correctly found ✓) | FP (False Positive — False alarm ✗) |
| System Predicted: Negative | FN (False Negative — Missed entity ✗) | TN (True Negative — Correctly ignored ✓) |
Precision (P) = TP / (TP + FP) | Recall (R) = TP / (TP + FN)
F₁-Measure = (2 · P · R) / (P + R) | F_β = (1 + β²) · P · R / (β² · P + R)
An NER system predicts 12 entities in a news article: 9 are completely correct (TP=9), 3 are wrong (FP=3). The gold-standard article actually contains 15 true entities, so the model missed 6 (FN=6).
Precision = 9 / (9 + 3) = 9 / 12 = 0.75 (75%)— Of what it predicted, 75% was right.Recall = 9 / (9 + 6) = 9 / 15 = 0.60 (60%)— Of all true entities, it caught 60%.F₁ = (2 × 0.75 × 0.60) / (0.75 + 0.60) = 0.90 / 1.35 = 0.667 (66.7%).
NLG & Sequence Evaluation Metrics
| Metric | What It Measures | Primary NLP Task |
|---|---|---|
| Exact Match / Entity-Level F1 | Strict full span + entity type match (partial match = error) | NER, Extractive QA (SQuAD) |
| BLEU | Precision-based n-gram overlap against human reference translations | Machine Translation (MT) |
| ROUGE | Recall-based n-gram / longest common subsequence overlap vs reference | Document Summarization |
| Perplexity (PP) | How surprised an LM is by test text (lower = more fluent) | Language Models |
| Human Evaluation | Human judges rating fluency, coherence, relevance & factuality | All NLG (Gold Standard) |
2. Question Answering (QA) Systems
Search Engine (IR) user ko documents ki list deta hai; Question Answering (QA) System natural language question ka direct, concise, exact answer deta hai (e.g., "What is the birth place of Shree Krishna?" → "Mathura"). Used in Siri, Alexa, Google Assistant, aur enterprise RAG bots.
3 Core Challenges of QA: (1) Lexical Gap (same meaning expressed with different words), (2) Ambiguity (syntactic like "flying planes" & lexical/polysemy like bank), (3) Multilingualism (web knowledge & user queries span dozens of languages).
3. Opinion Mining, Sentiment Analysis & Text Classification
- Text Classification (Categorization / Topic Spotting): Unstructured documents (emails, reviews, news, regional Indian language text in Hindi/Tamil/Telugu/Bengali/Marathi) ko predefined classes me sort karna (e.g.,
Positive / Neutral / Negative;Spam / Ham). Workflow: Raw Docs → Preprocessing → Feature Extraction (BoW / N-grams / TF-IDF / Embeddings) → Classifier → Predicted Label.- Rule-Based: Handcrafted keyword lists (e.g.,
fur, feathers, claws→ Animals). High domain effort, doesn't scale. - Machine Learning: Naive Bayes, SVM, Logistic Regression, or Deep Learning (BERT/DistilBERT).
- Hybrid: Combines ML predictions with strict domain rules.
- Rule-Based: Handcrafted keyword lists (e.g.,
- Opinion Mining & Sentiment Analysis: Customer reviews/tweets se polarity (Positive, Negative, Neutral) aur emotions nikalna. 3 levels: Document-level, Sentence-level, aur Aspect-Based Sentiment Analysis (ABSA) (uses NER!): "I love the iPhone 14, but its battery life is disappointing" →
iPhone 14: Positive,Battery life: Negative!
4. Document Summarization
Information overload solve karne ke liye lambe documents ko concise, coherent, non-redundant summary me compress karna without losing core meaning.
5. Machine Translation (MT)
Machine Translation: Source Language → MT System → Target Language while preserving meaning. 3 Core Challenges: (1) Vast diversity of scripts/grammars (SVO vs SOV), (2) Sequence-to-sequence alignment is harder than fixed numeric mapping, (3) No single "one right translation". Key Rule: Named entities (e.g., Marie Curie, Mathura) should be transliterated (sound preserved), not translated!
| MT Paradigm | How It Works | Strengths & Limitations |
|---|---|---|
| 1. RBMT (Rule-Based) | Hand-crafted source/target grammar rules + bilingual lexicons | Predictable; requires huge linguistic effort, rigid & slow to build |
| 2. SMT (Statistical) | Learns word/phrase alignment probabilities from large parallel corpora (early Google Translate) | Data-driven; misses wide sentence context → choppy translations |
| 3. HMT (Hybrid) | Combines RBMT + SMT + Translation Memory | Better quality than pure SMT; still needs heavy human post-editing |
| 4. NMT (Neural MT) | Single end-to-end neural network (Encoder-Decoder + Attention / Transformers) | State-of-the-art fluency & context awareness (Modern Google Translate / DeepL) |
6. Recommendation Systems, Ontology Construction & Emerging NLG
- NLP in Recommendation Systems: Content-based filtering converts item/article descriptions into TF-IDF or Word2Vec/BERT embeddings and ranks unseen items by Cosine Similarity to user history; NER-based recommendation tracks entities the user reads frequently (e.g., Elon Musk / SpaceX) to recommend related stories.
- Ontology Construction & Classification: An Ontology is a formal, machine-readable representation of domain knowledge defining Classes/Concepts, IS-A Taxonomies, Attributes, and Relations (e.g.,
Disease → ViralDisease → COVID-19). NLP Workflow for Ontology Learning: Raw Domain Corpus → Preprocessing & POS → Term & Entity Extraction (TF-IDF/NER) → Synonym Grouping (WordNet/Embeddings) → Taxonomy Discovery (Hearst Patterns like "X such as Y") → Relation Extraction → Formal OWL/RDF Classification. - Emerging Applications of NLG: Conversational AI & Multi-turn Dialogue Agents, Code Generation & Debugging Copilots, Retrieval-Augmented Enterprise Knowledge Bots (RAG), Automated Financial/Medical Report Generation, Personalized Tutoring, and Neural Text-to-Speech (TTS).
7. Exam Preparation & Quick Revision (Chapter 9)
Exam Questions (Chapter 9)
Q1 (5 Marks): Explain Precision, Recall, and F-Measure with Confusion Matrix and a numerical example.
Q2 (10 Marks): Compare Extractive vs Abstractive Summarization and explain the 4 types of Machine Translation.
Q3 (5 Marks): Explain Ontology Construction, Question Answering Systems, and Aspect-Based Sentiment Analysis.
Chapter 10: Sequence Deep Learning — RNN, LSTM, GRU, Seq2Seq & Attention
N-grams aur static Word2Vec ki limitations todne ke liye Deep Learning kaise aaya? RNN equations, Vanishing Gradient problem, LSTM ke teeno gates + Cell State conveyor belt SVG, GRU, Seq2Seq bottleneck, aur Bahdanau Attention.
1. Recurrent Neural Networks (RNN) & The Vanishing Gradient Problem
Standard Feedforward Neural Networks fixed-size input lete hain aur unke paas sequence order ki koi memory nahi hoti. N-grams sirf 2–3 previous words dekh sakte hain. RNN sentence ko word-by-word padhta hai aur har step par ek Hidden State hₜ aage pass karta hai jo ab tak padhe gaye saare words ki summary rakhta hai:
The Fatal Flaw — Vanishing Gradient Problem: Backpropagation Through Time (BPTT) me gradients har time step par Whh aur tanh' (≤ 1) se multiply hote rehte hain. 20–30 words peeche jaate-jaate gradient 0.5³⁰ ≈ 0.0000000009 (vanish!) ho jaata hai. Result: RNN lambe sentences ke shuruati subject ko bhool jaata hai!
2. Long Short-Term Memory (LSTM) & GRU
LSTM (Hochreiter & Schmidhuber, 1997) ne vanishing gradient solve karne ke liye RNN ke andar ek Cell State (Cₜ) highway (conveyor belt) banayi jahan gradients bina multiply hue seedha addition ke through flow kar sakein! Is highway ko 3 smart Sigmoid Gates (0 = block, 1 = let pass) control karte hain:
Cₜ = fₜ⊙Cₜ₋₁ + iₜ⊙C̃ₜ, and Output Gate exposes the filtered hidden state hₜ.GRU (Gated Recurrent Unit, 2014): LSTM ka streamlined version — Cell State aur Hidden State ko merge kar deta hai aur sirf 2 gates (Reset Gate & Update Gate) rakhta hai. Fewer parameters, faster training, often similar accuracy!
3. Seq2Seq Encoder-Decoder & Attention Mechanism
Machine Translation ya Summarization me input aur output ki length alag hoti hai. Seq2Seq do LSTMs use karta hai: Encoder poore input sentence ko ek single fixed-size Context Vector me compress karta hai, aur Decoder us vector se target sentence generate karta hai.
The Information Bottleneck: 50-word paragraph ko ek fixed vector me thunsna information loss kar deta hai! Bahdanau Attention (2014) ne is bottleneck ko toda: Decoder har output word generate karte waqt Encoder ke saare hidden states par weighted attention daal sakta hai — jis input word ki zaroorat hai, seedha uspe focus karo!
4. Comparison: RNN vs. LSTM vs. GRU
| Feature | Vanilla RNN | LSTM | GRU |
|---|---|---|---|
| Memory State | Only Hidden State hₜ | Hidden State hₜ + Cell State Cₜ | Merged Hidden State hₜ |
| Gates | None | 3 Gates (Forget, Input, Output) | 2 Gates (Reset, Update) |
| Long-Range Memory | Very poor (Vanishing Gradient) | Strong | Strong |
| Remaining Flaw | All three process tokens sequentially (one by one) — cannot parallelize across a sentence on GPUs! (Solved by Transformers in Chapter 11!) | ||
Chapter 11: Transformers, BERT vs. GPT, Alignment (RLHF) & RAG
Aaj ke modern AI (ChatGPT, Gemini, Claude, BERT) ka engine: Self-Attention (Q, K, V) step-by-step math, Multi-Head Attention, Positional Encoding, Encoder vs Decoder families, Instruction Tuning, RLHF/DPO, aur RAG.
- 1. Transformers & Scaled Dot-Product Self-Attention (Q, K, V)
- 2. Encoder-Only (BERT) vs Decoder-Only (GPT) vs Encoder-Decoder (T5)
- 3. Post-Training: Instruction Tuning, Alignment (RLHF/DPO) & Test-Time
- 4. Retrieval-Augmented Generation (RAG) Workflow SVG
- 5. Traditional NLP vs. Deep Learning / Transformer NLP
1. Transformers ("Attention Is All You Need", 2017)
RNN/LSTM ek time par ek hi word padh sakte the (sequential bottleneck). Transformers ne recurrence poori tarah hata diya! Poora sentence simultaneously parallel me process hota hai, Positional Encoding word order inject karta hai, aur Self-Attention har word ko sentence ke har dusre word se direct O(1) path se connect kar deta hai!
Step-by-Step Self-Attention Intuition:
- Project into Q, K, V: Har word embedding
xko 3 learned matrices (W_Q, W_K, W_V) se multiply karke 3 vectors bante hain: Query (Q) = "mujhe kis tarah ka context chahiye?", Key (K) = "mere paas kya info hai?", Value (V) = "meri actual meaning payload". - Score & Scale:
Q · Kᵀhar word ka har dusre word ke saath similarity score nikalta hai.√dₖse divide karte hain taaki large dot products softmax ko saturate na karein. - Weighted Sum:
softmaxscores ko attention weights (sum=1) banata hai, aur unseVka weighted sum milkar naya context-aware embedding ban jaata hai! (Example: "The animal didn't cross the street because it was too tired" →itattends strongly toanimal!). - Multi-Head Attention: Ek nahi, 8–96 attention heads parallel me chalte hain — ek head grammar (subject-verb) dekhta hai, dusra coreference, teesra semantic relations!
2. The 3 Transformer Families: BERT vs. GPT vs. T5
| Family | Flagship Models | Attention Mask | Pre-Training Objective | Ideal Tasks |
|---|---|---|---|---|
| Encoder-Only | BERT, RoBERTa, DistilBERT | Bidirectional (sees full left + right context) | Masked Language Modeling (predict [MASK]) | NLU: Classification, NER, Sentiment, Extractive QA, Semantic Search |
| Decoder-Only | GPT-4, Llama, Gemini, Claude | Causal (masked — sees ONLY previous left tokens) | Autoregressive Next-Token Prediction | NLG: Chatbots, Coding, Reasoning, Creative Writing |
| Encoder–Decoder | T5, BART, Original Transformer | Bidirectional Encoder + Causal Decoder + Cross-Attention | Seq2Seq Denoising / Span Corruption | Machine Translation, Abstractive Summarization |
3. Making LLMs Useful: Post-Training & Alignment (From L2_NLU.pptx)
Pre-training ke baad ek raw base LLM sirf internet text auto-complete karta hai — agar tum puchho "What is gravity?" toh wo jawab dene ke bajaye aur sawal likhne lag sakta hai! Isliye 3 post-training stages zaroori hain:
- Instruction Tuning (SFT): Curated
(Instruction, Ideal Response)pairs par supervised fine-tuning taaki model instructions follow karna seekhe. - Alignment (RLHF / DPO): Human preference rankings (Response A > Response B) use karke model ko helpful, honest, aur safe banana (Reinforcement Learning from Human Feedback / Direct Preference Optimization).
- Test-Time Strategies: Retraining ke bina generation time par Chain-of-Thought (CoT) reasoning aur structured prompting se accuracy boost karna.
4. Retrieval-Augmented Generation (RAG) — Bridging Classical IR & Modern LLMs
Why RAG? LLMs ki knowledge unki training cutoff par freeze ho jaati hai, aur wo confidently galat facts invent kar sakte hain (Hallucination). RAG classical Information Retrieval (Chapter 7 — NLU) ko modern LLMs (Chapter 11 — NLG) se jodta hai:
5. Traditional NLP vs. Deep Learning / Transformer NLP
| Dimension | Traditional / Statistical NLP | Deep Learning / Transformer NLP |
|---|---|---|
| Feature Engineering | Manual (Regex, POS tags, TF-IDF, N-grams, WordNet) | End-to-end automatic representation learning |
| Context Handling | Fixed local window (Bigram/Trigram) or Bag-of-Words | Full-sentence & multi-page contextual Self-Attention |
| Data & Hardware | Works well on small datasets & standard CPUs | Requires large corpora & GPUs (or pretrained fine-tuning) |
| Interpretability | High (transparent rules, probabilities, postings lists) | Low ("black box" billions of parameters) |
| Best Real-World Fit | Ultra-fast keyword search (BM25/Inverted Index), strict regex validation, low-resource rules | Chatbots, Translation, Summarization, Semantic Search, Complex NLU, RAG |