NLP Complete Textbook BCSE 0454 • v2
BCSE 0454 Complete Syllabus Zero-to-Pro Roadmap

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:

ChModule / ScopeExact Syllabus & Notes Topics Covered in Full DetailCO
0Start & PrereqsSyllabus Audit, 4-Era Evolution, Prerequisites (Conditional Probability, Bayes, Chain Rule, Vectors, Dot Product, Cosine Angle, Logarithms, Softmax)All
1Module INLP, 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 ApproachesCO1
2Module IText 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
3Module ILanguage 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, PerplexityCO2
4Module I & IIPOS 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
5Module IISyntactic 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
6Module IISemantic, 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
7Module 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
8Module IIWord 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&AsCO4
9Module IIEvaluation 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 ApplicationsCO4, CO5
10Beyond 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 MechanismPro
11Beyond 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 NLPPro

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:

  1. 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.
  2. 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.
  3. 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.
  4. 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)

Prerequisite 1: Conditional Probability & Chain Rule

P(A | B) = Probability of event A occurring, given that B has already occurred.

P(A | B) = P(A ∩ B) / P(B)   ⇒   P(A, B) = P(B) · P(A | B)

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.

Prerequisite 2: Vectors, Dot Product & Magnitude

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!).
Prerequisite 3: Logarithm (log₁₀) & Softmax Function
  • Why Log? TF-IDF me raw word count 100 ko 10 se 10× zyada important nahi maana jaata; log₁₀(100)=2 aur log₁₀(10)=1 extreme 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ⱼ)
Syllabus: Module I CO1

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:

NATURAL LANGUAGE PROCESSING (NLP — Complete System Loop) NLU (Understanding: Text → Meaning) Input: "Book a flight to Delhi tomorrow" Morphology → Syntax → Semantics → Discourse Extracts: Intent=BookFlight, Dest=Delhi, Date=Tomorrow Modern Architecture: Encoder-Only (BERT) NLG (Generation: Meaning → Text) Data: {Flight: AI-402, Time: 9 AM, Price: ₹4,800} Deep Planning → Sentence Planning → Realization Output: "Air India AI-402 departs at 9 AM for ₹4,800." Modern Architecture: Decoder-Only (GPT / LLMs)
Figure 1.1: End-to-End NLP Loop chaining NLU (analysis) and NLG (synthesis). Chatbots, voice assistants, and translators combine both halves seamlessly.
AspectNLU (Natural Language Understanding)NLG (Natural Language Generation)
DirectionRaw Text → Structured MeaningStructured Meaning / Data → Fluent Text
Core ChallengeResolving ambiguity, polysemy, and implicit contextEnsuring fluency, coherence, factual accuracy (no hallucination)
Key Sub-tasksEmbeddings, POS Tagging, NER, Parsing, WSD, SRL, CoreferenceLanguage Modeling, Machine Translation, Summarization, Dialogue, TTS
EvaluationPrecision, Recall, F1, Exact Match, AccuracyBLEU, ROUGE, Perplexity, Human Evaluation
Modern ModelsEncoder-Only Transformers (BERT, RoBERTa)Decoder-Only (GPT, Llama) & Encoder-Decoder (T5)
Formal Definition (For University Exams)

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 TypeConceptual Explanation (Hinglish)Exam Examples
1. Lexical AmbiguityEk 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) AmbiguityEk 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 AmbiguityWords 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 AmbiguityPronoun (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 AmbiguitySpeaker 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."
Garden Path Sentences (Even Humans Get Misled Mid-Sentence!)
  • "The horse raced past the barn fell." — Padhte waqt raced main verb lagta hai, par fell aate 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." — plans verb 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:

1. Phonological Phones, IPA Prosody (ASR/TTS) 2. Morphological Morphemes Stem / Lemma 3. Lexical Tokens, Word Relations 4. Syntactic Grammar Rules Parse Trees 5. Semantic Literal Meaning WSD, SRL, NER 6. Discourse Multi-Sentence Coherence, Coref 7. Pragmatic World Context Speech Acts, Deixis
Figure 1.2: The 7 Interacting Levels of Language Processing (from speech sounds up to real-world communication intent).
  1. 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).
  2. Morphological Level: Words chhote meaningful units (Morphemes) se kaise bante hain (books = book + s; unhappy = un + happy). Components: Inflection, Derivation, Stemming, Lemmatization.
  3. 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).
  4. 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!
  5. 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).
  6. 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).
  7. 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 LevelTypical NLP Tasks & Applications
Character / String LevelWord tokenization, Sentence boundary detection, Regex pattern extraction
Word Level (Morphological)POS tagging, Parsing, Chunking, Term extraction, Gene mention recognition (biomedical)
Sentence LevelSentence classification, Ambiguity detection, Question Answering, Summarization
Sentence-Window (4–5 sentences)Anaphora & Coreference resolution (tracking pronouns across nearby sentences)
Paragraph / Passage LevelPredicting rhetorical zones (e.g., Background, Method, Result in scientific papers)
Whole Document / Multi-DocumentDocument similarity calculation, Document clustering, Multi-document summarization

4. Linguistic Terminology & Morphological Analysis

Classification of Morphemes

Inflectional vs. Derivational Morphology

PropertyInflectional MorphologyDerivational Morphology
DefinitionAdapts 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 PositionIn English, only Suffixes (or Infixes), never PrefixesCan be both Prefixes (un-happy) and Suffixes (happy-ness)
RegularityHighly regular and productiveLess regular / unpredictable

Building a Morphological Parser (3 Mandatory Components)

  1. Lexicon: Stems aur affixes ki list with grammatical metadata (e.g., noun stem vs verb stem).
  2. Morphotactics: Ordering rules batate hain ki morphemes kis sequence me jud sakte hain (use + able + ness = useableness ✓, par able + use + ness ✗).
  3. Orthographic Rules: Morphemes judne par hone wale spelling changes ko model karte hain (lady + s → ladies ✓, not ladys ✗).

5. Classical Approaches of NLP

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.

Syllabus: Module I CO1

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.

Raw Text "Dogs are running!" 1. Tokenize ["Dogs","are","running"] 2. Lowercase ["dogs","are","running"] 3. Stop-words ["dogs","running"] 4. Stem/Lemma ["dog","run"] Index / Model BoW / TF-IDF / ML
Figure 2.1: Complete Text Preprocessing Workflow. Golden Rule in IR & ML: Training/indexing documents aur test/query text dono par identical preprocessing pipeline lagani hoti 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

Evolution: Why Lemmatization Was Needed After Stemming

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.

ParameterStemmingLemmatization
Core MethodRule-based heuristic chopping of affixes (Porter / Lancaster)Dictionary lookup (WordNet) + Morphological & POS analysis
Output ValidityMay NOT be a real word (dating → dat, studies → studi)Always a valid dictionary base word / Lemma (better → good)
Context AwarenessNoneUses POS tag (saw as Verb → see; as Noun → saw)
Speed & CostVery fast, low memorySlower, requires lexicon + POS tagger
Best Use CasesLarge-scale IR indexing where speed is criticalChatbots, QA, Sentiment Analysis, Machine Translation
Formal Definition (For University Exams)

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

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}.

q0 b q1 a q2 a q3 a ! q4
Figure 2.2: FSA for 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 5Input 1 → (2r + 1) mod 5
q5 (Start, empty)q0q1
*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

StateSuffix MatchedInput 0Input 1
q0 (Start)Noneq0q1
q1Ends with 1q2q1
q2Ends with 10q3q1
*q3 (Final)Ends with 100q0q1

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.

Syllabus: Module I CO2

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?

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).

Formal Definition (For University Exams)

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:

P(w₁, w₂, ..., wₙ) = P(w₁) · P(w₂ | w₁) · P(w₃ | w₁, w₂) · ... · P(wₙ | w₁, ..., wₙ₋₁)

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).

The Problem (Data Sparsity) → Why Markov Assumption Was Introduced

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!

P(wᵢ | w₁, w₂, ..., wᵢ₋₁) ≈ P(wᵢ | wᵢ₋ₖ, ..., wᵢ₋₁)

3. N-Gram Models (Unigram, Bigram, Trigram)

ModelOrder (k)Formula (MLE)Behavior & Example
Unigram (N=1)k = 0P(wᵢ) = C(wᵢ) / Total_TokensWords completely independent; generates random word soup ("Sixth, the, rupees, education...")
Bigram (N=2)k = 1P(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 = 2P(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)

Exam Numerical 1: Bigram Sentence Probability (With Boundary Tokens)

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).

P = P(I|<s>) × P(I|I) × P(am|I) × P(not|am) × P(</s>|not) = (3/3) × (1/4) × (2/4) × (1/2) × (0/1) = 0

Insight: Sirf ek unseen bigram (not, </s>) ki wajah se poori sentence probability collapse hokar 0 ho gayi! Isiliye Smoothing zaroori hai.

Exam Numerical 2: Next-Word Prediction Using Bigram Model (Jack Corpus)

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: like or I. (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

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.

Syllabus: Module I (POS/HMM/Viterbi) Syllabus: Module II (NER) CO2 • CO3

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

DimensionMorphological AnalysisPOS Tagging
ScopeWord-based (internal root + affixes)Sentence-based (surface form in surrounding context)
Tag SetSmaller (only inflecting categories: N, V, Adj, Adv, Pron)Larger (also includes non-inflecting categories: prepositions, conjunctions, particles)
Output per WordCan produce multiple candidate analysesProduces exactly one context-disambiguated tag

Word Classes & Standard Tagsets

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

ApproachInternal Mechanism & ExampleProsLimitations (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 neededHard 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 reductionCombines rule interpretability with corpus-driven learningSlow 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 wellNeeds large annotated corpus; struggles with unseen words
4. Neural / Deep Learning (BiLSTM, BERT, ALBERT)Automatically learns bidirectional contextual representations from raw + labeled textState-of-the-art accuracy; handles OOV via subwordsHigh compute & data requirements; black-box

3. Hidden Markov Model (HMM) & Viterbi Algorithm

Core Intuition: Observations vs. Hidden States

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ᵢ).

t=1: Walk t=2: Shop t=3: Clean Sunny Rainy δ₁(S) = 0.36 0.6 × 0.6 (MAX) δ₁(R) = 0.08 0.4 × 0.2 δ₂(S) = 0.0756 ptr: Sunny δ₂(R) = 0.0540 ptr: Sunny δ₃(S) = 0.00529 ptr: Sunny δ₃(R) = 0.00680 ptr: Sunny (WIN)
Figure 4.1: Viterbi Trellis for [Walk, Shop, Clean]. Backtracking from the winning final state Rainy (0.00680) yields Sunny → Sunny → Rainy.
Complete Viterbi Calculation (From Notes)

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.
Pseudocode — Viterbi Dynamic Programming Algorithm
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 (✓).

5. NER Ambiguities, Indian Language Challenges & Evaluation

Formal Definition (For University Exams)

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.

Syllabus: Module II CO3

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 & Syntactic Concepts

Evolution: Why Regular Expressions / FSA Fail at Sentence Syntax

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.

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!

ParameterTop-Down ParsingBottom-Up Parsing
DirectionRoot S → down to input wordsInput words → up to Root S
DerivationLeftmost DerivationRightmost Derivation (in reverse)
Main DecisionWhich production rule to apply next?When to reduce a substring to a non-terminal?
Strength & WeaknessModerate; 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
ExamplesRecursive Descent Parser, LL ParserShift-Reduce (SR) Parser, CKY, LR Parser
Tree 1: VP Attachment (She used telescope) SNPVP sheVPPP V: sawNP: the man P: withNP: the telescope Tree 2: NP Attachment (Man had telescope) SNPVP sheV: sawNP NP: the manPP: with telescope
Figure 5.1: Structural Ambiguity — two valid parse trees for "she saw the man with the telescope". Standard CFG cannot rank them; PCFG + PCKY solves this!

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!

Pseudocode — CKY Bottom-Up DP Parser
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 \ j1 (the)2 (cat)3 (chased)4 (the)5 (mouse)
0DetNP (0,1)+(1,2)ØØS (0,2)+(2,5) ✓
1—NØØØ
2——VØVP (2,3)+(3,5)
3———DetNP (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).

Complete PCKY Numerical (7×7 Chart — From Your Notes)

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.
Formal Definition (For University Exams)

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.

Syllabus: Module II CO3

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 RelationConceptual Meaning (Hinglish)Types / Properties & Exam Examples
1. SynonymyAlag words jo same/nearly identical concept express kareinshut / close, car / automobile, beautiful / gorgeous, mistake / error, rich / wealthy
2. AntonymyOpposite 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 & HypernymyIS-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. MeronymyPART-OF relationship (constituent part)coconut is a meronym of coconut tree; wheel is a meronym of car
5. HomonymySame spelling & pronunciation, bilkul unrelated meaningsbat (wooden cricket/baseball bat vs flying mammal); bank (river side vs financial institution)
6. PolysemySame word, different par related meaningsnewspaper ("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.

1. Input Sentence Preprocess + Target 2. Context Bag Remaining sentence words 3. Sense Bag (WordNet) All senses (Gloss + Examples) 4. Overlap Scorer |Context ∩ Senseᵢ| 5. Best Sense Max overlap wins
Figure 6.1: Lesk Algorithm Workflow — 7 Components: Input, Pre-processing (tokenize, stop-words, stem), Knowledge Source (WordNet / IndoWordNet), Sense Bag, Context Bag, Overlap Scorer, and Decision Module.
Complete Lesk Walkthrough (From Your Notes)

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

5. Pragmatics vs. Discourse Analysis

AspectDiscourse AnalysisPragmatics
Unit of AnalysisConnected multi-sentence text, articles, or conversationsIndividual utterance interpreted in real-world situational context
Core FocusCoherence (logical flow), Cohesion (grammatical connectors like however, therefore), AnaphoraIntended 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"!
Formal Definition (For University Exams)

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.

Syllabus: Module II (Full IR & Stats) CO4 • CO5

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 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 TermExact MeaningConcrete Example
DocumentThe fundamental retrievable unit (web page, email, paragraph, product listing)One news article
Corpus / CollectionThe complete set of all documents searchable by the IR systemEntire newspaper archive
Information NeedWhat the user actually wants to find out (in their head)"Is it safe to take ibuprofen with paracetamol?"
QueryWhat the user types into the search box (an imperfect expression of the need)"ibuprofen paracetamol together"
RelevanceJudgement (binary or graded) that a document satisfies the information need (not just matching query words!)Medical page explaining drug interactions
TermNormalized indexed unit produced after preprocessingrank (normalized from "ranking")
IndexPre-built data structure for millisecond lookupInverted Index

Database Search (SQL) vs. Information Retrieval (IR) vs. Question Answering (QA)

AspectDatabase Query (SQL)Information Retrieval (IR)Question Answering (QA)
Data TypeStructured (tables, rows, schemas)Unstructured or semi-structured textText passages or Knowledge Bases
Query FormFormal exact language (SQL)Free keywords or natural language (often vague)Natural-language question
MatchingExact deterministic match (row matches or not)Partial relevance scoring & rankingExtract or generate a specific answer
OutputSet of database rowsRanked list of relevant documentsShort concise answer (ideally with evidence)
CorrectnessDeterministic (Right / Wrong)Subjective (Precision, Recall, NDCG over queries)Answer Accuracy / Exact Match / F1

2. Complete IR System Workflow: Offline Indexing vs. Online Querying

Central Architectural Design Idea of Every Search Engine

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!

OFFLINE SIDE (Indexing Pipeline — Run Once / Periodically) Document Corpus Raw Web / PDFs Text Preprocessing Tokenize • Stop-words • Stem Indexer Sort, Merge, df & tf Inverted Index Dictionary + Postings ONLINE SIDE (Query-Time Pipeline — Real-Time Milliseconds) User Query "web search engine" IDENTICAL Preproc. Same Tokenize & Stem! Ranker / Matcher Boolean / TF-IDF / BM25 Ranked Results Top-K Sorted Docs
Figure 7.1: Complete Information Retrieval (IR) System Architecture showing Offline Indexing and Online Query Processing. Critical Rule: Documents aur User Query par exact same preprocessing pipeline chalni chahiye — warna agar doc me "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)

  1. Step 1 (Offline Crawling & Acquisition): Web crawler ya ingestion pipeline saare documents collect karke har document ko unique docID assign karti hai.
  2. Step 2 (Offline Preprocessing): Tokenization, lowercasing, stop-word removal, stemming/lemmatization se raw text clean index terms me badalta hai.
  3. 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 me tf aur df store karta hai.
  4. Step 4 (Online Query Processing): User query type karta hai → wahi exact preprocessing pipeline chalti hai → clean query terms milte hain.
  5. 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!
  6. 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

Why Term-Document Incidence Matrix Does Not Scale (The 99.8% Sparsity Proof)

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"

TermD1D2D3dfInverted Index Postings (docID: tf)
collects0101D2:1
crawler0101D2:1
engine1012D1:1, D3:1
index0011D3:1
inverted0011D3:1
pages1102D1:1, D2:1
ranks1001D1:1
search1012D1:1, D3:1
uses0011D3:1
web1102D1:1, D2:2

4-Step Inverted Index Construction Workflow & Large-Scale Indexing

  1. Assign a unique integer docID to every document.
  2. Tokenize & normalize each document to emit a stream of (term, docID) pairs.
  3. Sort all pairs alphabetically by term, and secondarily by docID.
  4. Merge duplicate (term, docID) pairs to compute term frequency tf, group by term into postings lists, and count list length to get document frequency df.

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.

Pseudocode — Boolean Postings List Intersection
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 StrengthsBoolean 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 & reproducibilityRequires 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:

wtf(t, d) = 1 + log10(tf(t, d))  (if tf > 0, else 0)
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.00df=1 → idf=6 (very rare/informative) | df=100 → idf=4 | df=10,000 → idf=2 | df=1,000,000 → idf=0 (useless!)
Complete TF-IDF & Cosine Ranking Numerical

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

Formal Definition (For University Exams)

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?

Syllabus: Module II CO4

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. The Problem Before Word2Vec (Why One-Hot / BoW / TF-IDF Failed)

Why Sparse Representations Cannot Understand Meaning

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!

PropertyOne-Hot EncodingWord2Vec (Dense Embeddings)
Vector SizeVocabulary-sized (V, huge)Compact, fixed dimension (D = 50..300)
ValuesSparse (mostly zeros)Dense learned continuous real numbers
Semantic SimilarityNot encoded (orthogonal)Captured via vector closeness & analogies
How CreatedManual index assignmentSelf-supervised learning from sliding context windows
OOV HandlingNeeds vocabulary entryStandard 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).

A. CBOW (Context → Target) love learning Hidden h̄ Mean(W[ctx]) 1 × D W' + Softmax → machine Faster training • Strong on frequent words B. Skip-gram (Target → Context) machine Hidden h Lookup W[t] 1 × D love learning Slower • Better on rare words & small corpora
Figure 8.1: Word2Vec CBOW vs Skip-gram Architecture (Embedding Matrix 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]).

  1. CBOW: Look up W[2] and W[4] → Average in Hidden Layer: h̄ = (W[2] + W[4]) / 2 (1 × 100) → Multiply by Output Matrix W' (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 target machine ([0,0,1,0]), compute Cross-Entropy loss, and backpropagate to update W and W'.
  2. Skip-gram: Feed target vector W[3] (1 × 100) → Multiply by W' → Softmax → Predict both context pairs (machine, love) and (machine, learning). After training, rows of W are our learned Word2Vec embeddings! (For V=10,000, D=100, total parameters in W = 1,000,000).

3. Negative Sampling, Analogies & Gensim Implementation

Python — Complete Gensim Word2Vec Demo (From PPT)
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

TechniqueHow It Computes EmbeddingsLimitation of Previous SolvedRemaining Limitation
Word2VecLocal sliding context window (CBOW / Skip-gram)Solved One-Hot sparsity & lack of semantic similarityLocal only; fails on OOV words; static (one vector per word)
GloVeGlobal word-word co-occurrence matrix factorization across entire corpusCaptures global corpus statistics alongside local meaningStill static & fails on OOV words
FastTextWord2Vec + 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 / RoBERTaBidirectional 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
GPTCausal (left-context only) Transformer predicting next tokenEnables autoregressive NLG + contextual representationsUnidirectional left-to-right context
Formal Definition (For University Exams)

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.
Syllabus: Module II CO4 • CO5

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

Why Accuracy Alone Is Misleading in NLP

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: PositiveTP (True Positive — Correctly found ✓)FP (False Positive — False alarm ✗)
System Predicted: NegativeFN (False Negative — Missed entity ✗)TN (True Negative — Correctly ignored ✓)
Accuracy = (TP + TN) / (TP + TN + FP + FN)
Precision (P) = TP / (TP + FP)   |   Recall (R) = TP / (TP + FN)
F₁-Measure = (2 · P · R) / (P + R)   |   F_β = (1 + β²) · P · R / (β² · P + R)
Worked Numerical: Precision, Recall & F₁-Score

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

MetricWhat It MeasuresPrimary NLP Task
Exact Match / Entity-Level F1Strict full span + entity type match (partial match = error)NER, Extractive QA (SQuAD)
BLEUPrecision-based n-gram overlap against human reference translationsMachine Translation (MT)
ROUGERecall-based n-gram / longest common subsequence overlap vs referenceDocument Summarization
Perplexity (PP)How surprised an LM is by test text (lower = more fluent)Language Models
Human EvaluationHuman judges rating fluency, coherence, relevance & factualityAll 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.

Natural Question "Who announced...?" 1. Question Processing Type: "Who" → PERSON 2. Passage Retrieval IR Index / Vector Search 3. Answer Extraction NER/BERT → "Satya Nadella"
Figure 9.1: Three-Stage Question Answering (QA) Pipeline. Standard QA Datasets: SQuAD (Stanford), WikiQA, TREC-QA, News-QA.

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

4. Document Summarization

Information overload solve karne ke liye lambe documents ko concise, coherent, non-redundant summary me compress karna without losing core meaning.

Extractive Summarization (Select & Copy) S1, S2,S3, S4 Rank & Pick S2 + S4 Abstractive Summarization (Paraphrase) S1, S2,S3, S4 Seq2Seq/LLM Brand NewSentences
Figure 9.2: Extractive (pulls exact sentences/keywords — e.g., "Joseph and Mary attended event Jerusalem. Mary gave birth Jesus.") vs Abstractive (generates fluent new paraphrased sentences like humans).

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 ParadigmHow It WorksStrengths & Limitations
1. RBMT (Rule-Based)Hand-crafted source/target grammar rules + bilingual lexiconsPredictable; 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 MemoryBetter 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

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.

Beyond Syllabus • Pro Level Sequence Deep Learning

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

Why RNN Was Invented After N-Grams & Feedforward ANNs

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:

hₜ = tanh( Whh · hₜ₋₁ + Wxh · xₜ + bh )   |   ŷₜ = softmax( Why · hₜ + by )

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ₜ₋₁ Cₜ (Cell State Highway) × + 1. Forget Gate (fₜ) Drop old irrelevant info 2. Input Gate (iₜ, C̃ₜ) Add new useful info 3. Output Gate (oₜ) hₜ = oₜ ⊙ tanh(Cₜ) hₜ hₜ₋₁, xₜ →
Figure 10.1: LSTM Cell Architecture — Forget Gate deletes stale memory, Input Gate writes new memory to the Cell State highway 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

FeatureVanilla RNNLSTMGRU
Memory StateOnly Hidden State hₜHidden State hₜ + Cell State CₜMerged Hidden State hₜ
GatesNone3 Gates (Forget, Input, Output)2 Gates (Reset, Update)
Long-Range MemoryVery poor (Vanishing Gradient)StrongStrong
Remaining FlawAll three process tokens sequentially (one by one) — cannot parallelize across a sentence on GPUs! (Solved by Transformers in Chapter 11!)
Beyond Syllabus • Industry Pro Modern LLMs (L2_NLU.pptx)

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 ("Attention Is All You Need", 2017)

Why Transformers Replaced RNNs & LSTMs Overnight

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!

Attention(Q, K, V) = softmax( (Q · Kᵀ) / √dₖ ) · V

Step-by-Step Self-Attention Intuition:

  1. Project into Q, K, V: Har word embedding x ko 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".
  2. 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.
  3. Weighted Sum: softmax scores ko attention weights (sum=1) banata hai, aur unse V ka weighted sum milkar naya context-aware embedding ban jaata hai! (Example: "The animal didn't cross the street because it was too tired" → it attends strongly to animal!).
  4. 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

FamilyFlagship ModelsAttention MaskPre-Training ObjectiveIdeal Tasks
Encoder-OnlyBERT, RoBERTa, DistilBERTBidirectional (sees full left + right context)Masked Language Modeling (predict [MASK])NLU: Classification, NER, Sentiment, Extractive QA, Semantic Search
Decoder-OnlyGPT-4, Llama, Gemini, ClaudeCausal (masked — sees ONLY previous left tokens)Autoregressive Next-Token PredictionNLG: Chatbots, Coding, Reasoning, Creative Writing
Encoder–DecoderT5, BART, Original TransformerBidirectional Encoder + Causal Decoder + Cross-AttentionSeq2Seq Denoising / Span CorruptionMachine 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:

  1. Instruction Tuning (SFT): Curated (Instruction, Ideal Response) pairs par supervised fine-tuning taaki model instructions follow karna seekhe.
  2. 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).
  3. 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:

User Query Natural Question 1. Retriever (IR / NLU) Vector DB + BM25 Search 2. LLM Generator (NLG) Query + Retrieved Evidence Grounded Answer Cited & Up-to-date
Figure 11.1: End-to-End RAG Architecture — combines IR retrieval with LLM generation to eliminate hallucinations and support private/real-time documents without retraining!

5. Traditional NLP vs. Deep Learning / Transformer NLP

DimensionTraditional / Statistical NLPDeep Learning / Transformer NLP
Feature EngineeringManual (Regex, POS tags, TF-IDF, N-grams, WordNet)End-to-end automatic representation learning
Context HandlingFixed local window (Bigram/Trigram) or Bag-of-WordsFull-sentence & multi-page contextual Self-Attention
Data & HardwareWorks well on small datasets & standard CPUsRequires large corpora & GPUs (or pretrained fine-tuning)
InterpretabilityHigh (transparent rules, probabilities, postings lists)Low ("black box" billions of parameters)
Best Real-World FitUltra-fast keyword search (BM25/Inverted Index), strict regex validation, low-resource rulesChatbots, Translation, Summarization, Semantic Search, Complex NLU, RAG