Unit 1: Foundations of NLP and Text Processing
1. Introduction to Natural Language Processing (NLP)
Natural Language Processing (NLP) is an interdisciplinary field at the intersection of computer science, artificial intelligence, and computational linguistics. Its primary objective is to enable computational systems to understand, interpret, synthesize, and manipulate human language in a manner that is both semantically valid and contextually appropriate.
CODE+-----------------------------------------------------------------------------------+ | THE INTERDISCIPLINARY SPECTRUM OF NLP | +-----------------------------------------------------------------------------------+ | Computer Science | Algorithms, Data Structures, Complexity, Systems Eng. | | Artificial Intelligence| Machine Learning, Deep Neural Networks, Probabilistic PGM| | Linguistics | Syntax, Semantics, Morphology, Phonology, Pragmatics | | Cognitive Science | Human Language Acquisition, Mental Lexicon, Comprehension| +-----------------------------------------------------------------------------------+
1.1 The Linguistic Hierarchy
Human language is organized as a layered, hierarchical symbolic system. Computational processing typically decomposes natural language along these classical linguistic strata:
CODE[ Pragmatics & Discourse ] (Context, Intent, Multi-Sentence Coherence) ^ [ Semantics ] (Literal Meaning, Truth Conditions, Roles) ^ [ Syntax ] (Grammar, Parse Trees, Dependency Graphs) ^ [ Morphology ] (Morphemes, Stems, Roots, Affixes) ^ [ Phonology / Orthography] (Sound Waves, Phonemes, Alphabetic Tokens)
- Phonetics and Phonology:
- Studies the physical production (phonetics) and systematic cognitive patterns (phonology) of speech sounds.
- Core units: Phones (acoustic waveforms) and Phonemes (minimal sound units distinguishing words, e.g.,
/p/vs./b/in "pat" vs. "bat").
- Morphology:
- The study of word structure and the rules governing how minimal units of meaning (morphemes) combine.
- Free Morphemes: Can stand alone as independent words (e.g.,
dog,play,govern). - Bound Morphemes: Must attach to other morphemes as prefixes, suffixes, or infixes (e.g.,
un-,-ed,-ment,-s). - Inflectional Morphology: Modifies grammatical form without changing lexical category (e.g.,
walkwalks,walked,walking). - Derivational Morphology: Creates new lexical concepts or alters grammatical category (e.g.,
govern(verb)government(noun)governmental(adjective)).
- Syntax:
- The structural rules governing how words combine into grammatical phrases, clauses, and sentences.
- Formalized using context-free grammars (CFGs), constituency parse trees (phrase structure), and dependency grammars (head-dependent governor relationships).
- Semantics:
- The study of literal meaning expressed by words, phrases, and compositional sentences, independent of subjective context.
- Encompasses lexical semantics (synonymy, antonymy, hyponymy, polysemy) and compositional semantics (Frege's principle: the meaning of a whole sentence is a mathematical function of the meanings of its constituent parts).
- Pragmatics:
- How context, social conventions, background knowledge, and speaker intentions influence meaning.
- Decodes non-literal expressions, sarcasm, metaphors, and speech acts (e.g., "Can you pass the salt?" is a pragmatic request to take action, not a query regarding physical capability).
- Discourse Analysis:
- Understanding linguistic meaning across sequences of connected sentences, handling anaphora resolution, coreference chains, and rhetorical structure.
2. Inherent Challenges and Ambiguities in Natural Language
Unlike formal programming languages (such as Python, C++, or SQL) which possess deterministic context-free grammars and unambiguous compilation rules, human languages are inherently fluid, dynamic, and laden with multifaceted ambiguity.
2.1 Taxonomy of Linguistic Ambiguity
CODE+----------------------------------------------------------------------------------------------------+ | TAXONOMY OF NLP AMBIGUITIES | +------------------------------------+---------------------------------------------------------------+ | Ambiguity Type | Illustrative Example & Computational Problem | +------------------------------------+---------------------------------------------------------------+ | Lexical Ambiguity (Polysemy) | "I deposited money in the bank" vs "He sat on the river bank".| | | (The token 'bank' possesses completely distinct senses). | +------------------------------------+---------------------------------------------------------------+ | Syntactic Ambiguity (Structural) | "I saw the man with a telescope." | | | (Did I use a telescope to see him, or did the man hold one?) | +------------------------------------+---------------------------------------------------------------+ | Semantic Ambiguity (Scope) | "Every student loves a professor." | | | (Does a single professor get loved by all, or does each | | | student love a different professor?) | +------------------------------------+---------------------------------------------------------------+ | Pragmatic / Anaphoric Ambiguity | "The trophy did not fit in the suitcase because it was too | | | big." (What does 'it' refer to? The trophy or the suitcase?)| +------------------------------------+---------------------------------------------------------------+
- Lexical Ambiguity:
- Occurs when a single word token exhibits multiple meanings:
- Homonymy: Unrelated concepts sharing the exact same orthographic spelling and pronunciation (e.g.,
bankas a financial institution vs. river bank). - Polysemy: Related senses derived from an underlying conceptual root (e.g.,
woodas a forested area vs. the structural material from trees).
- Homonymy: Unrelated concepts sharing the exact same orthographic spelling and pronunciation (e.g.,
- Resolved via Word Sense Disambiguation (WSD) algorithms using context vectors.
- Occurs when a single word token exhibits multiple meanings:
- Syntactic (Structural) Ambiguity:
- Arises when a sequence of tokens can generate multiple valid hierarchical syntax trees.
- Prepositional Phrase (PP) Attachment Ambiguity:
In "The chef cooked the pasta with garlic", the PP attaches to the verb phrase (cooked with garlic). In "The chef cooked the pasta with clams", the PP attaches to the noun phrase (pasta with clams). Resolving this requires world knowledge regarding culinary semantics.
- Anaphoric / Coreference Ambiguity:
- Winograd Schema challenges demonstrate pragmatic ambiguity:
- "The city councilmen refused the demonstrators a permit because they feared violence."
they= councilmen. - "The city councilmen refused the demonstrators a permit because they advocated violence."
they= demonstrators.
- "The city councilmen refused the demonstrators a permit because they feared violence."
- Resolving pronouns requires deep contextual reasoning and world knowledge beyond surface grammar.
- Winograd Schema challenges demonstrate pragmatic ambiguity:
3. Text Preprocessing and Normalization Pipelines
Before unstructured textual corpora can be processed by machine learning algorithms or neural networks, text must undergo rigorous cleaning, segmentation, and normalization.
CODERaw Text Document | [Sentence Segmentation] --> Divides document into discrete sentences | [Word Tokenization] --> Divides sentences into token streams | [Case Normalization] --> Lowercasing (conditional) | [Stopword Removal] --> Strips high-frequency syntactic glue (task-dependent) | [Morphological Parsing] --> Stemming or Lemmatization v Cleaned Token Sequence
3.1 Sentence Segmentation (Sentence Boundary Disambiguation)
- Sentence segmentation identifies boundary delimiters separating consecutive sentences.
- The Period Delimiter Problem: Periods do not solely denote sentence terminations; they mark abbreviations (e.g.,
Dr.,Inc.,U.S.A.), decimal numbers (3.1415), ellipses (...), and email/web addresses (info@lpu.in). - Techniques:
- Regular expression heuristic rules (e.g., match uppercase letter following period and whitespace).
- Machine learning classifiers (e.g., Punkt tokenizer in NLTK): unsupervised rule-based clustering of abbreviation candidates based on collocations and capitalization patterns.
3.2 Tokenization Paradigms
Tokenization partitions a continuous string of characters into meaningful atomic units termed tokens.
- Whitespace Tokenization:
- Splits text strictly along whitespace characters (
,\t,\n). - Failure Modes: Fails on punctuation boundaries (
"Hello, world!"["Hello,", "world!"]), contracted forms ("don't"["don't"]instead of["do", "n't"]), and non-segmented writing systems (Chinese, Japanese, Thai) that feature no whitespace between words.
- Splits text strictly along whitespace characters (
- Penn Treebank Rule-Based Tokenization:
- Separates clitics and contractions:
"they'll"["they", "'ll"],"isn't"["is", "n't"]. - Isolates terminal punctuation while preserving abbreviations and internal hyphens.
- Separates clitics and contractions:
3.3 Stopword Filtering
- Stopwords: Extremely high-frequency functional words that carry little distinctive semantic information in classical bag-of-words retrieval models (e.g.,
the,is,at,which,on,and). - When to Remove: Information retrieval, keyword extraction, topic modeling (LDA), document classification using TF-IDF.
- When NOT to Remove: Machine translation, sentiment analysis, text generation, and modern Transformer-based pretrained models (BERT, GPT). In transformers, self-attention uses stopwords to establish syntactic scaffolding and coreference connections (e.g., stripping
"not"completely inverts sentiment in"not good").
3.4 Stemming vs. Lemmatization
CODE+-----------------------------------------------------------------------------------+ | STEMMING VS. LEMMATIZATION COMPARISON | +--------------------------+----------------------------+---------------------------+ | Dimension | Stemming | Lemmatization | +--------------------------+----------------------------+---------------------------+ | Primary Approach | Crude heuristic suffix | Morphological analysis | | | stripping rules | using lexical dictionaries| +--------------------------+----------------------------+---------------------------+ | Part of Speech Awareness | Completely unaware of POS | Strictly requires POS tag | +--------------------------+----------------------------+---------------------------+ | Output Validity | Often yields non-words | Always yields valid base | | | (e.g., 'studi', 'univers') | dictionary lemmas ('study')| +--------------------------+----------------------------+---------------------------+ | Computational Speed | Extremely fast, lightweight| Slower, requires lexicon | | | memory footprint | lookup & morphological DB | +--------------------------+----------------------------+---------------------------+
Stemming Algorithms: Porter vs. Lancaster
- Porter Stemmer (Porter, 1980):
- Consists of 5 sequential heuristic condition-action phases.
- Relies on the measure of alternating vowel-consonant sequences: .
- Example:
generalizationsgeneralizegeneralgener. - Errors:
- Over-stemming: Merging words with distinct meanings to the same root (e.g.,
universe,university,universalall reduced tounivers). - Under-stemming: Failing to reduce words with the same root together (e.g.,
adhereandadhesionreduced to different roots).
- Over-stemming: Merging words with distinct meanings to the same root (e.g.,
- Lancaster (Paice-Husk) Stemmer:
- Employs aggressive rule tables. Highly prone to over-stemming (e.g.,
policypol).
- Employs aggressive rule tables. Highly prone to over-stemming (e.g.,
Lemmatization: WordNet Lemmatizer
- Reduces inflected word forms to their linguistically valid base form (lemma) using a vocabulary database (e.g., Princeton WordNet).
- Crucial POS Dependency: The word
"meeting":- If tagged as a Noun ():
lemma = "meeting"(an event). - If tagged as a Verb ():
lemma = "meet". - The word
"better":- If tagged as Adjective ():
lemma = "good".
- If tagged as Adjective ():
- If tagged as a Noun ():
4. Subword Tokenization Algorithms
Modern neural language models (BERT, RoBERTa, GPT-4, LLaMA) require fixed-size vocabularies (typically tokens) capable of representing arbitrary open-domain text without suffering from Out-Of-Vocabulary (OOV) issues.
CODECharacter Tokenization Subword Tokenization Word Tokenization [c, a, t, s, b, e, d] [cat, ##s, bed] [cats, bed] (Vocab: ~100; Seq: Long) (Vocab: ~32k; Balanced, No OOV) (Vocab: >1M; Huge, Many OOVs)
4.1 Byte-Pair Encoding (BPE)
Pioneered for data compression by Gage (1994) and adapted for NLP subword tokenization by Sennrich, Haddow, and Birch (ACL 2016).
The BPE Training Algorithm
- Initialize vocabulary with all unique characters present in the training corpus, plus a special end-of-word symbol (e.g.,
</w>). - Represent every word in the training corpus as a sequence of individual character symbols.
- Count the frequency of all adjacent symbol pairs across the entire tokenized corpus.
- Identify the most frequent adjacent pair and merge it into a single new symbol .
- Add to vocabulary .
- Repeat steps 3–5 iteratively until reaching a predefined target vocabulary size or merge threshold.
CODEBPE Step-by-Step Toy Example: Corpus: {"l o w </w>": 5, "l o w e r </w>": 2, "n e w e s t </w>": 6, "w i d e s t </w>": 3} Iteration 1: Pair counts: ('e', 's'): 9, ('s', 't'): 9, ('e', 'w'): 8, ('l', 'o'): 7, ('o', 'w'): 7 Merge ('e', 's') -> 'es'. Corpus: {"l o w </w>": 5, "l o w e r </w>": 2, "n e w es t </w>": 6, "w i d es t </w>": 3} Iteration 2: Most frequent pair: ('es', 't') -> count: 9. Merge ('es', 't') -> 'est'. Corpus: {"l o w </w>": 5, "l o w e r </w>": 2, "n e w est </w>": 6, "w i d est </w>": 3} Iteration 3: Most frequent pair: ('est', '</w>') -> count: 9. Merge ('est', '</w>') -> 'est</w>'. Corpus: {"l o w </w>": 5, "l o w e r </w>": 2, "n e w est</w>": 6, "w i d est</w>": 3}
4.2 Byte-Level BPE (BBPE)
- Standard BPE operating on Unicode characters struggles across multilingual corpora with rare Unicode glyphs (emojis, complex scripts), causing vocabulary bloat.
- Radfor et al. (GPT-2) introduced Byte-level BPE: initializes the base vocabulary with all raw byte values of UTF-8.
- Advantage: Any sequence of text in any language can be represented without ever producing an unknown token (
<unk>).
4.3 WordPiece Tokenizer
Developed by Schuster & Nakajima (2012) and adopted in Google's BERT (Devlin et al., 2018).
- Difference from BPE: Instead of selecting the symbol pair with the highest raw co-occurrence frequency, WordPiece selects the pair that maximizes the likelihood of the training corpus under a unigram language model.
- Score for candidate pair :
High scores reward pairs whose joint frequency is significantly higher than expected by independent chance. - In BERT, subwords that occur inside words rather than at prefixes are preceded by a double-hash prefix (
##):
"unaffable"["un", "##aff", "##able"].
4.4 Unigram Language Model Tokenizer (SentencePiece)
Introduced by Kudo (2018):
- Operates in a top-down pruning direction, unlike BPE's bottom-up merging.
- Starts with an enormous initial seed vocabulary (e.g., all characters + thousands of common substrings).
- Fits a unigram language model over the corpus.
- At each step, calculates how much the total corpus likelihood would decrease if each candidate subword were removed from the vocabulary.
- Prunes the bottom (e.g., ) of subwords causing the least likelihood loss.
- Repeats until reaching the desired vocabulary size. At inference time, uses the Viterbi algorithm to find the optimal subword segmentation that maximizes overall probability.
5. Statistical Language Modeling and Vector Space Models
Before deep recurrent or transformer networks, NLP relied on statistical vector space representations and N-gram Markov models.
5.1 Bag-of-Words (BoW) Representation
- Represents a document as an unordered collection of word counts, completely discarding syntax, word order, and grammar.
- Let vocabulary . A document is mapped to a vector where each coordinate equals the frequency of term in .
- Limitations:
- Extreme Sparsity: If vocabulary and a sentence contains 10 words, of vector coordinates are zero.
- Total Loss of Sequential Context: "Not bad, really good" and "Not good, really bad" yield identical vectors.
- Frequency Bias: Ubiquitous non-informative words (
the,is) dominate magnitude over rare informative terms (photosynthesis).
5.2 Term Frequency - Inverse Document Frequency (TF-IDF)
TF-IDF attenuates the influence of ubiquitous terms while boosting domain-specific keywords.
CODE+-----------------------------------------------------------------------------------+ | THE TF-IDF MATHEMATICAL FORMULATION | +-----------------------------------------------------------------------------------+ | Term Frequency: TF(t, d) = f_{t, d} / sum_{t'} f_{t', d} | | | | Inverse Doc Frequency: IDF(t, D) = log( (1 + N) / (1 + |{d in D : t in d}|) ) + 1| | | | Combined Weight: TF-IDF(t, d, D) = TF(t, d) * IDF(t, D) | +-----------------------------------------------------------------------------------+
- Term Frequency (TF): Measures how frequently term appears within document :
- Inverse Document Frequency (IDF): Measures the informativeness of term across corpus containing total documents:
If a term appears in every document (), , completely nullifying its weight. - TF-IDF Vector:
Vectors are typically normalized to unit -norm: .
5.3 Vector Similarity Metrics: Cosine Similarity
To compare two documents represented by TF-IDF vectors and :
- Invariant to document length: Two documents with identical topic proportions but different lengths produce an identical cosine similarity of 1.0.
6. N-Gram Language Models and Smoothing Techniques
A Language Model (LM) computes a joint probability distribution over word sequences :
Applying the chain rule of probability decomposes this joint distribution:
6.1 The Markov Assumption and N-Gram Formulations
Conditioning on the entire preceding history is computationally intractable because long word sequences never repeat in finite training data.
The Markov Assumption: The probability of an upcoming word depends only on the preceding words:
- Unigram Model (): Words are independent:
- Bigram Model (): Depends only on the immediate predecessor:
- Trigram Model (): Depends on preceding two words:
6.2 Maximum Likelihood Estimation (MLE)
Using relative frequency counts from a training corpus:
6.3 The Zero-Probability Pathology & Smoothing Algorithms
If a valid word sequence was never observed during training (), then . Under the chain rule, a single zero probability forces the entire document probability to zero:
To fix this, smoothing reallocates probability mass from frequent N-grams to unobserved N-grams.
1. Laplace (Add-1) Smoothing
Adds 1 to every N-gram count:
Where is vocabulary size.
Limitation: Adds far too much probability mass to unseen events when is large (), severely degrading performance.
2. Add-k (Lidstone) Smoothing
Replaces 1 with a fractional parameter (typically ):
3. Jelinek-Mercer Linear Interpolation
Linearly combines higher-order and lower-order N-gram probabilities using interpolation weights satisfying :
4. Kneser-Ney Smoothing
The gold standard in classical statistical N-gram modeling. Incorporates continuation probability:
- Consider the word
"York". It is very frequent, but almost exclusively follows"New". - If a unigram model encounters a novel context, standard unigram probability would rank
"York"highly, which is erroneous. - Continuation Probability measures how likely word is to complete an unobserved context by counting the number of unique preceding words:
- Interpolated Kneser-Ney Bigram Formula:
Where is an absolute discount parameter, and normalizes the distribution.
7. Evaluating Language Models: Perplexity
How do we measure the quality of a language model without deploying it in an end-to-end downstream system?
7.1 Cross-Entropy and Perplexity
For a test corpus containing total tokens, the average cross-entropy per word is:
The Perplexity (PPL) is mathematically defined as 2 raised to the power of the cross-entropy:
CODE+-----------------------------------------------------------------------------------+ | PERPLEXITY (PPL) INTUITIVE INTERPRETATION | +-----------------------------------------------------------------------------------+ | Intuition: The effective weighted "branching factor" of the language model. | | | | - If PPL = 50: At each prediction step, the model is as confused as if it were | | choosing uniformly at random among 50 equally probable words. | | - A lower Perplexity indicates a superior language model that assigns higher | | probabilities to real human-written text. | | - A perfect model predicting the exact word with P=1.0 has Perplexity = 1.0. | +-----------------------------------------------------------------------------------+
8. Summary Comparison of Tokenization and Representation Methods
| Method | Vocabulary Size | OOV Handling | Preserves Word Order | Computational Overhead | Primary Modern Use Case |
|---|---|---|---|---|---|
| Whitespace Tokenizer | Extremely large () | Fails completely on OOV | No (when in BoW) | Minimal (split string) | Quick baselines |
| Porter Stemmer | Moderate | Crude truncation | No | Negligible | Traditional IR, search engines |
| WordNet Lemmatizer | Moderate | Preserves root | No | Moderate (lexicon lookup) | Linguistic corpus analysis |
| Byte-Pair Encoding (BPE) | Fixed () | Eliminates OOV via subwords | Sequence format | Fast (trained once) | GPT-2, RoBERTa, LLaMA |
| WordPiece | Fixed () | Eliminates OOV via subwords | Sequence format | Fast (greedy lookup) | BERT, DistilBERT |
| Bag-of-Words (BoW) | $ | V | \approx 10^5$ | Ignores OOV words | No (unordered set) |
| TF-IDF | $ | V | \approx 10^5$ | Ignores OOV words | No (weighted vector) |
| Kneser-Ney N-Gram | Factorial combinations | Handled via discounting | Yes (local Markov window) | High memory for large N | Speech recognition decoding |