Chapter 1: Introduction to NLP
Understand what Natural Language Processing is, trace its evolution from rule-based systems to modern transformers, and explore the core tasks, data representations, challenges, and real-world applications that define the field.
- Topics
- 6
- Demos
- 3
- Videos
- 3
- Min read
- 53
Chapter Overview
Natural Language Processing (NLP) is the branch of artificial intelligence concerned with giving machines the ability to read, understand, generate, and reason about human language. It sits at the intersection of computer science, linguistics, and statistics, and has become one of the most impactful areas of modern AI.
At its core, NLP transforms unstructured text---the dominant form of human knowledge---into structured representations that algorithms can manipulate. Whether we model language with hand-crafted rules, statistical counts, or billion-parameter neural networks, the fundamental goal is the same: bridge the gap between how humans communicate and how computers process information.
The field has undergone several paradigm shifts. Early systems relied on manually written grammars and dictionaries. Statistical methods introduced data-driven learning via n-grams and probabilistic models. Deep learning brought distributed representations and sequence models. Most recently, the Transformer architecture and large-scale pretraining have unified many previously separate tasks under a single framework.
This chapter covers:
- What is NLP? Defining the field and its relationship to AI and linguistics
- History of NLP: From rule-based parsers to neural transformers
- Core NLP Tasks: Tokenization, POS tagging, NER, sentiment analysis, and more
- Text as Data: Why language is uniquely challenging for machines
- Challenges in NLP: Ambiguity, context, sarcasm, and multilingual complexity
- Applications of NLP: Search engines, chatbots, translation, medical NLP, and beyond
Chapter Roadmap
Click any topic to jump in
What is NLP
Problem formulation, language levels, and the three paradigms — framing NLP as conditional probability estimation.
How the field evolved and what problems it tackles
History of NLP
From symbolic rules through statistical counting to neural representation learning — each era's key insight.
Core NLP Tasks
Tokenization, POS tagging, NER, and sentiment analysis — the building-block tasks the field is organized around.
Representing text numerically and understanding why it is hard
Text as Data
Bag-of-words, TF-IDF, embeddings, and contextual representations — turning words into numbers machines can process.
Challenges in NLP
Ambiguity, coreference, sarcasm, and multilinguality — why language is harder than images for machines.
Applications
Search, translation, chatbots, and biomedical NLP — where the techniques meet real-world impact.
Topics
6 topics in this chapter
Most of what people know is written down in emails, contracts, medical notes, reviews, and chat logs, yet a computer sees all of it as a string of characters with no meaning attached. A bank that wants to route a million support emails, or a hospital that wants to find every patient whose notes mention a drug reaction, cannot hire enough people to read them. The problem is turning text, which is ambiguous, open-ended, and full of unstated context, into decisions a program can act on.
This topic opens the NLP plan and builds on the probability and machine-learning basics from the Foundations and ML plans. It starts with the problem formulation that almost every NLP task shares: estimate the most probable output for an input text . It then walks through the levels of language a system can analyze, from word structure to speaker intent, compares the rule-based, statistical, and neural paradigms, and ends by separating understanding (NLU) from generation (NLG). Later topics in this chapter build on each of these ideas.
Definition
Natural Language Processing is the field that builds computational systems to analyze, understand, and generate human language. Most NLP tasks are framed as learning a conditional distribution over outputs , such as a label, a tag sequence, or another text, given an input text , and predicting the most probable .
In this topic
- 1The NLP Problem Formulation
- 2Levels of Language Understanding
- 3Rule-Based vs Statistical vs Neural NLP
- 4NLP vs NLU vs NLG
The NLP Problem Formulation
Almost every NLP task can be written as one question: given input text , which output is most probable? For spam filtering is a label; for tagging it is a sequence of tags; for translation it is a whole sentence. Bayes' theorem gives two ways to answer it. A generative model learns how text is produced, , and a prior , then inverts them; the evidence is the same for every , so it drops out of the argmax. A discriminative model learns directly. Generative models such as Naive Bayes need little data but assume independence; discriminative neural models usually win when labels are plentiful.
Most NLP tasks reduce to estimating where is text and is the desired output. Bayes' theorem decomposes this as . A spam classifier with uniform prior needs only vs — whichever likelihood is larger wins. The ratio is the Bayes factor: values above 1 favor spam, below 1 favor ham.
Frame spam detection as an NLP problem. Given the email text "Win a FREE iPhone now!!!", what is and what is ?
Levels of Language Understanding
Language is layered, and each layer asks a different question. Phonetics and phonology study sounds. Morphology studies how words are built from morphemes, the smallest meaningful units, such as 'un-' or '-ness'. Syntax studies how words combine into phrases and sentences. Semantics studies literal meaning, and pragmatics studies what a speaker intends in context, such as a request disguised as a question. A task usually needs only some layers: spell-checking is mostly morphology, while a dialogue system needs all of them. Because errors made at a lower layer feed every layer above it, a mistake in segmenting words can derail parsing and meaning further down the pipeline.
Analyzing language at levels means composing imperfect functions: . If each level has accuracy , the end-to-end accuracy is roughly . With and , you get — an 81% pipeline from 95% components. This explains why even small errors at the tokenization level propagate and compound through deeper analysis.
Analyze the sentence "Unhappiness is contagious" at the morphological and semantic levels.
Rule-Based vs Statistical vs Neural NLP
Three paradigms have shaped NLP. Rule-based systems encode expert knowledge as hand-written grammars, dictionaries, and patterns; they are precise and explainable, but every new phrasing needs another rule, so they break on open-ended text. Statistical systems, such as Naive Bayes or hidden Markov models, learn probabilities from counted data but depend on features that humans design, like word counts or suffixes. Neural systems learn their own features from raw text and now dominate most benchmarks, at the cost of large datasets, heavy compute, and weaker interpretability. Rules still earn their place for formats with fixed structure, such as dates or product codes, and as guardrails around learned models.
Rule-based systems have no trainable parameters but need a hand-written rule set whose size grows with every phrasing they must cover. Statistical models such as Naive Bayes have about parameters for a vocabulary of size and classes, estimated from counts. Neural models have far more: BERT-base has about 110M parameters, most of them in layers that each scale with for hidden size . Larger models generally need more data, which is why pretraining on unlabeled text matters: it supplies that data without labels, and fine-tuning then needs only a few thousand labeled examples.
Design a simple rule-based sentiment analyzer for product reviews using Python.
NLP vs NLU vs NLG
NLP is the umbrella term for any computation over language. Natural Language Understanding (NLU) maps text to a structured representation: a class label, a set of entities, an intent with slots, or a logical form. Natural Language Generation (NLG) runs the other way, producing fluent text from structured data or from other text, as in summarization or dialogue replies. Many applications chain the two, understanding the input before generating the output. The distinction matters when choosing metrics: NLU is usually scored against a single correct answer with accuracy or F1, while NLG has many acceptable outputs, so it needs overlap metrics such as BLEU or human judgment.
NLU maps text to a structured representation: (e.g., intent + entities). NLG maps structure back to text: . Translation composes both: . Modern seq2seq models learn this composition end-to-end, but the decomposition clarifies why translation is harder than classification — it requires both understanding and generation.
Classify each task as NLU or NLG: (1) extracting dates from emails, (2) writing a product description, (3) detecting fake news, (4) translating English to French.
Theory Exercise
Problem:
Explain why NLP is considered harder than many other AI tasks like image classification. What properties of natural language make it uniquely challenging for machines?
Coding Exercise
Problem:
Write a function that takes a sentence and returns a dictionary with basic NLP statistics: word count, unique words, average word length, and the longest word.
Related Problems on PixelBank
Why does a modern NLP course still teach regular expressions, n-gram counts, and hidden Markov models when a single transformer can do almost everything? Because each generation of methods failed in an instructive way, and the methods that replaced it were built to fix that failure. Rules could not cover open-ended language, counts could not see beyond a few words, and recurrent networks could not be trained in parallel or remember long contexts. Knowing these failures explains the design of the systems we use today.
The previous topic, What is NLP, framed tasks as estimating and contrasted the rule-based, statistical, and neural paradigms. This topic puts those paradigms on a timeline. It starts with the symbolic era of hand-written grammars and ELIZA, moves to the statistical revolution driven by large corpora and probabilistic models, follows the neural era of word embeddings, LSTMs, and attention, and ends with the Transformer and large-scale pretraining, which unified most tasks under one architecture.
Definition
The history of NLP is usually divided into four eras by the dominant source of knowledge: symbolic systems built from hand-written rules (1950s to 1980s), statistical systems that estimate probabilities from corpora (1990s to early 2010s), neural systems that learn dense representations (about 2013 to 2017), and pretrained Transformer models (2017 onward).
In this topic
- 1The Symbolic Era (1950s--1980s)
- 2The Statistical Revolution (1990s--2010s)
- 3The Neural Era (2013--2017)
- 4The Transformer Era (2017--Present)
The Symbolic Era (1950s--1980s)
The first NLP systems encoded language knowledge by hand. The 1954 Georgetown-IBM demonstration translated more than 60 Russian sentences into English using a 250-word vocabulary and just six grammar rules, and it fueled predictions that translation would be solved within years. Chomsky's Syntactic Structures (1957) gave syntax a formal footing. ELIZA (1966) imitated a therapist with keyword patterns, and SHRDLU (around 1970) obeyed commands in a toy world of blocks. The 1966 ALPAC report concluded that machine translation had not delivered and US funding was cut sharply. The lesson was that rules work in narrow domains but cannot keep up with open-ended language.
Symbolic systems operate on discrete grammar rules where is a finite rule set. ELIZA used pattern-match operations per input. The fundamental limitation is that is fixed at design time while natural language is infinite — Chomsky showed that regular grammars cannot even handle center-embeddings like 'the cat the dog chased ran', requiring context-free rules at minimum.
Write an ELIZA-style pattern-matching response generator.
The Statistical Revolution (1990s--2010s)
By the late 1980s, large machine-readable corpora and cheaper computing made it possible to learn language patterns by counting. IBM's translation models learned word alignments from Canadian parliamentary proceedings in English and French, the Penn Treebank (1993) supplied millions of words annotated with tags and parse trees, and hidden Markov models became standard for tagging and speech. The formula above picks the label that maximizes : a likelihood estimated from counts times a prior. The weakness was sparsity, since most word combinations never appear in any training corpus, so models needed smoothing and hand-designed features to generalize.
Statistical models estimate from corpus counts. The maximum-likelihood bigram estimate is . With vocabulary , there are possible bigrams — most never appear in any corpus. Add- smoothing redistributes mass: , preventing zero probabilities for unseen pairs.
A bigram model trained on a corpus assigns P('learning' | 'machine') = 0.03. What does this number mean and how was it computed?
The Neural Era (2013--2017)
Neural methods replaced sparse counts with dense learned vectors. Word2Vec (2013) trained embeddings by predicting nearby words, so words used in similar contexts ended up close together. Recurrent networks, especially LSTMs, read a sentence one token at a time, updating a hidden state from the current input and the previous state , as the formula shows. Encoder-decoder models (2014) translated by compressing a source sentence into vectors and decoding a target, and Bahdanau attention let the decoder look back at every source word instead of a single summary vector. The remaining weaknesses were sequential computation, which was slow to train, and difficulty remembering information across long distances.
Word2Vec's training objective maximizes . The embedding matrix with compresses each word from a -dimensional one-hot vector to a 300-dimensional dense vector. The famous analogy works because the embedding space encodes semantic relationships as approximately linear directions.
Word2Vec learns that vec('king') - vec('man') + vec('woman') is close to vec('queen'). What does this reveal about word embeddings?
The Transformer Era (2017--Present)
The Transformer (2017) removed recurrence entirely. In the formula, every token forms a query that is compared with the keys of all tokens, the scores are divided by to keep them in a stable range, and the softmax weights mix the values . Every position therefore connects directly to every other in one layer, and all positions are computed in parallel. Pretraining then exploited this at scale: BERT (2018) learned bidirectional representations by predicting masked words, and GPT models learned to predict the next token. One pretrained model fine-tuned for many tasks replaced separate pipelines. The main cost is attention's quadratic growth with sequence length.
Self-attention computes where the scaling prevents dot products from growing too large. Without scaling, if and entries have variance 1, their dot product has variance , pushing softmax into saturated regions where gradients vanish. The scaling ensures the variance stays at 1 regardless of dimension, keeping gradients healthy during training.
Why did the Transformer replace LSTMs for most NLP tasks?
Theory Exercise
Problem:
Compare the data requirements of rule-based, statistical, and neural NLP systems. Why do modern neural models need orders of magnitude more data than statistical models, and what makes this feasible today?
Coding Exercise
Problem:
Implement a simple bigram language model that trains on a corpus and can generate text. Include add-k smoothing to handle unseen bigrams.
Related Problems on PixelBank
A customer email arrives: "My order from Amazon shipped to Boston on May 3rd but never arrived, and I'm furious." A useful system has to split it into units, decide which words are nouns and verbs, notice that Amazon, Boston, and May 3rd name specific things, and judge that the writer is angry. No single step does all of this, so NLP breaks the problem into a small set of standard tasks that can be built, measured, and debugged separately.
The previous topic, History of NLP, traced how methods evolved from rules to Transformers. This topic looks at the tasks those methods were built to solve. It begins with tokenization, which splits raw text into the units every later task consumes. It then covers part-of-speech tagging, the classic sequence-labeling task, and named entity recognition, which labels spans of text with types such as person or location. It closes with sentiment analysis and text classification, which assign a label to a whole document. Modern models often learn these tasks jointly, but each one still defines its own inputs, outputs, and metrics.
Definition
Core NLP tasks are standard problem formulations defined by the shape of their output. Tokenization segments text into units; sequence labeling, such as POS tagging and NER, assigns one label per token; classification assigns one label per document; and generation produces new text one token at a time.
In this topic
- 1Tokenization
- 2Part-of-Speech (POS) Tagging
- 3Named Entity Recognition (NER)
- 4Sentiment Analysis and Text Classification
Tokenization
Tokenization splits raw text into tokens, the units a model counts or embeds. Word tokenizers split on spaces and punctuation, which is simple but leaves rare words and new names out of a fixed vocabulary. Subword tokenizers such as BPE learn a vocabulary of frequent pieces: the formula says BPE repeatedly merges the adjacent pair with the highest frequency into a new symbol . Rare words then decompose into known pieces instead of an unknown token. Real tokenizers rarely split along morphemes: GPT-2 splits 'unhappiness' into un, h, appiness. The choice trades vocabulary size against sequence length, and every later task inherits its mistakes.
A tokenizer maps a string to a sequence . For BPE, the vocabulary starts as individual bytes () and grows by merging the most frequent adjacent pair at each step. After merges, . GPT-2 uses merges, giving a vocabulary of ~50,257 tokens. The compression ratio (characters per token) converges to roughly 3.5--4.0 for English text.
Tokenize 'unhappily' using a BPE vocabulary: ['un', 'hap', 'pi', 'ly', 'happy', 'unhappy', 'happily']. Assume the greedy longest-match strategy.
Part-of-Speech (POS) Tagging
POS tagging assigns each word a grammatical category such as noun, verb, adjective, or determiner. The formula asks for the tag sequence that is most probable given the words , so tags are chosen jointly, not one word at a time. Context matters because many words are ambiguous: 'book' is a noun in 'a book' and a verb in 'book a flight'. Hidden Markov models combined word-given-tag and tag-transition probabilities, and the Viterbi algorithm found the best sequence; modern taggers use bidirectional neural encoders and exceed 97 percent accuracy on news text. The Penn Treebank defines 36 word-level tags.
A POS tagger assigns one of tags to each word in a sequence of length . With the Viterbi algorithm on an HMM, complexity is — quadratic in tag count, linear in sentence length. For the Penn Treebank tagset () and a 20-word sentence, that is operations — fast enough for real-time processing.
POS-tag the sentence 'The old man the boat.' Why is this sentence tricky?
Named Entity Recognition (NER)
NER finds spans of text that name specific things and assigns each a type, such as PERSON, ORGANIZATION, LOCATION, or DATE. Because entities can span several tokens, NER is usually cast as sequence labeling with BIO tags: B-TYPE marks the first token of an entity, I-TYPE marks a continuation, and O marks tokens outside any entity. With entity types there are labels. A valid sequence never starts an entity with I-, which is why taggers often add a CRF layer that scores label transitions. NER feeds search, question answering, and knowledge graphs, and it fails on unseen names, on nested entities, and when moved to a new domain.
NER is a sequence labeling task using BIO tags: each token gets B-TYPE (begin), I-TYPE (inside), or O (outside). With entity types, there are possible labels. A CRF layer on top of BERT models transition scores between label at position and label at position , preventing illegal transitions like I-PER following B-LOC.
Apply BIO tagging to: 'Barack Obama visited the United Nations in New York on January 5th.'
Sentiment Analysis and Text Classification
Text classification assigns one or more labels to a whole document; sentiment analysis, spam filtering, topic tagging, and intent detection are all instances. In the formula, is a feature vector for the text, such as word counts or a neural embedding, is a learned weight per feature, is a bias, and the predicted class is the one with the highest score. A linear model over word counts is a strong baseline that is fast and interpretable. Its weakness is that it ignores word order and composition, so negation ('not good') and contrast ('good but') confuse it, and fine-tuned Transformers handle these far better.
Binary sentiment classification estimates . A logistic regression on bag-of-words computes where assigns a learned weight to each word. Words with large positive weights ('excellent', 'amazing') push toward positive; large negative weights ('terrible', 'awful') push toward negative. The decision boundary is the hyperplane in vocabulary space.
Classify the sentiment of: 'The food was good but the service was absolutely terrible and ruined the whole experience.'
Theory Exercise
Problem:
Explain the difference between sequence labeling tasks (POS tagging, NER) and sequence-to-sequence tasks (translation, summarization). How do the input-output relationships differ, and what architectural choices does each require?
Coding Exercise
Problem:
Implement a simple rule-based NER system that identifies PERSON, ORGANIZATION, and LOCATION entities using capitalization patterns and a small gazetteer (dictionary of known entities).
Related Problems on PixelBank
A logistic regression needs a fixed-length vector of numbers, but a review is a sequence of words of any length, drawn from a vocabulary of hundreds of thousands, where word order and context change the meaning. How do we turn "dog bites man" into numbers without making it identical to "man bites dog", and how do we let a model know that "car" and "automobile" mean nearly the same thing? Every NLP system has to answer this before any learning can start.
The previous topic, Core NLP Tasks, defined what models must predict. This topic covers how text is represented as their input. It starts with bag-of-words, which counts words and ignores order. TF-IDF then reweights those counts so that distinctive words matter more than common ones. Word embeddings replace sparse counts with dense vectors in which similar words lie close together. Contextual representations finish the arc: they give each occurrence of a word its own vector, so 'bank' by a river and 'bank' with money are no longer the same point.
Definition
A text representation is a function that maps a document or token to a numerical vector. Sparse representations such as bag-of-words and TF-IDF have one dimension per vocabulary word; dense representations such as word embeddings use a few hundred learned dimensions, and contextual representations compute a different vector for each occurrence depending on its surrounding words.
In this topic
- 1Bag-of-Words Representation
- 2TF-IDF Weighting
- 3Word Embeddings
- 4Contextual Representations
Bag-of-Words Representation
Bag-of-words fixes a vocabulary of words and represents a document by the vector in the formula: entry is the number of times word occurs in . Every document, short or long, becomes a point in the same -dimensional space, so any standard classifier can use it. The vectors are extremely sparse, because a document uses a tiny fraction of the vocabulary. The cost of the simplicity is that order is discarded: 'dog bites man' and 'man bites dog' get identical vectors. Adding bigrams as extra features recovers some local order at the price of a much larger vocabulary, and words outside the vocabulary are dropped.
A BoW vector is extremely sparse: a 200-word document with has at most 200 non-zero entries — 99.6% zeros. Sparse matrix formats (CSR) store only non-zero values and their indices, reducing memory from to . For a corpus of documents, the full matrix would need floats, but sparse storage typically uses of that.
Given vocabulary ['cat', 'dog', 'fish', 'the', 'sat'], compute BoW vectors for 'the cat sat' and 'the dog sat the dog'.
TF-IDF Weighting
Raw counts let frequent words like 'the' dominate a document vector. TF-IDF fixes this by multiplying two factors. The term frequency counts how often term appears in document . The inverse document frequency uses the corpus size and the number of documents that contain : a term found in every document gets , while a rare term gets a large weight. The result rewards words that are frequent in one document but rare overall. TF-IDF remains a strong baseline for search and classification, but it still ignores word order and treats synonyms as unrelated.
TF-IDF weights a term by . The log-IDF factor downweights common terms: a word appearing in all documents gets weight, while a term in only 1 document gets . For and natural logs, IDF ranges from 0 to about 9.2; a word in 10 documents gets about 6.9, three quarters of the maximum. Ratios of IDF values do not depend on the log base, because changing the base rescales every value by the same constant.
In a corpus of 10,000 documents, 'the' appears in 9,500 and 'quantum' appears in 15. Compute IDF for each.
Word Embeddings
Word embeddings represent each word by a dense vector in , usually with between 100 and 300, learned so that words used in similar contexts get similar vectors. Similarity is measured with the cosine in the formula, which ignores vector length and compares direction only. Unlike one-hot or bag-of-words vectors, where every pair of different words is equally unrelated, embeddings let knowledge transfer: a classifier that learns 'car' also learns something about 'automobile'. Word2Vec predicts neighboring words, GloVe factorizes co-occurrence counts, and FastText adds character n-grams for rare words. All of them give one vector per word, which mixes the senses of words like 'bank'.
An embedding with represents each word as a dense vector. Cosine similarity lies between and , and in trained spaces related words usually score well above unrelated ones. It measures shared contexts, not shared meaning: antonyms such as 'hot' and 'cold' occur in similar contexts and typically score high, not near . Unlike one-hot vectors, where for every pair of distinct words, embeddings place similar words close together, so what a model learns about one word transfers to its neighbors.
Word2Vec gives these cosine similarities: sim('car', 'automobile') = 0.93, sim('car', 'banana') = 0.12. What does this tell us about the embedding space?
Contextual Representations
Static embeddings give a word one vector everywhere, so 'bank' in 'river bank' and in 'bank account' share a point that blends both senses. Contextual representations compute a vector for each occurrence from the whole sentence. ELMo (2018) did this with bidirectional LSTMs; BERT and GPT do it with Transformer layers, where each token's vector is updated by attending to its neighbors. The same word then gets different vectors in different contexts, which handles polysemy and lets one pretrained encoder serve many tasks. The costs are that every occurrence needs a forward pass through a large network, and the vectors depend on the model's layers and training data.
Contextual representations produce different vectors for the same word in different contexts. BERT encodes 'bank' in 'river bank' as and in 'bank account' as ; the two vectors are noticeably less similar than two occurrences of the same sense, yet more similar than two unrelated words, because both still carry the word's identity. Each of BERT-base's 12 layers refines the representation, and probing studies find that lower layers encode more surface and syntactic information while upper layers encode more task-specific and semantic information.
The word 'crane' appears in two sentences: 'The crane lifted the steel beam' and 'The crane waded through the marsh.' How would static vs contextual embeddings handle this?
Theory Exercise
Problem:
Compare bag-of-words, TF-IDF, static word embeddings (Word2Vec), and contextual embeddings (BERT) along these dimensions: (1) handling of word order, (2) handling of polysemy, (3) vocabulary scalability, and (4) computational cost.
Coding Exercise
Problem:
Implement TF-IDF from scratch. Given a corpus of documents, compute the TF-IDF matrix and find the most important words in each document.
Related Problems on PixelBank
A model can score above 90 percent on a benchmark and still misread "I saw the man with the telescope", resolve "it" to the wrong noun, or call a sarcastic review glowing. And most of the world's languages have so little labeled data that a strong English system has no counterpart for them. Why is language so much harder for machines than its surface suggests?
The previous topic, Text as Data, showed how text becomes vectors. This topic looks at what those vectors often fail to capture. It starts with ambiguity: words with several senses and sentences with several parses. It then covers context and coreference, where resolving a pronoun can require knowledge about the physical world. Sarcasm and figurative language follow, where the intended meaning contradicts the literal words. The topic closes with multilingual and low-resource settings, where rich morphology, missing word boundaries, and scarce data break assumptions built for English. Knowing these limits helps you design evaluations that expose them before users do.
Definition
The core challenges of NLP are the properties that make the mapping from text to meaning many-to-many: ambiguity in word senses and sentence structure, dependence on context and world knowledge for reference, non-literal language such as sarcasm, and the diversity and data scarcity of the world's languages.
In this topic
- 1Lexical and Structural Ambiguity
- 2Context and Coreference
- 3Sarcasm, Irony, and Figurative Language
- 4Multilingual and Low-Resource Challenges
Lexical and Structural Ambiguity
Lexical ambiguity arises when one word form has several meanings: WordNet lists 18 senses for 'bank' across its noun and verb uses. Structural ambiguity arises when one word sequence has several valid parse trees: in 'I saw the man with the telescope', the phrase 'with the telescope' can attach to 'saw' (the instrument) or to 'the man' (what he carries). Only about one in five WordNet lemmas is polysemous, but those include the most frequent words. People resolve ambiguity with context and world knowledge so quickly that they rarely notice it, while a model has to infer the right reading from data.
Lexical ambiguity means . In WordNet only about 21 percent of lemmas are polysemous, but those include the most frequent words: 'bank' has 18 senses across nouns and verbs and 'run' has 57. For a sentence with ambiguous words each having senses, there are up to combined readings: with and , that is . Context prunes this space quickly: the word 'river' next to 'bank' rules out every financial sense in one step.
The sentence 'Time flies like an arrow' has at least three parsings. Find them.
Context and Coreference
Coreference resolution decides which earlier mention a pronoun or noun phrase refers to. The formula scores each candidate referent for compatibility with the pronoun and its context, then normalizes the scores over all candidates to get a probability. Grammar alone often cannot decide: in 'The trophy doesn't fit in the suitcase because it is too big', both nouns agree with 'it', and only knowing how containers work picks the trophy. Winograd schemas pair sentences that differ in one word, flipping the referent. WinoGrande scales this to about 44,000 problems built to defeat word-association shortcuts; at publication the best model scored 79.1 percent against 94 percent for humans.
Coreference links mentions to entities: 'John said he was tired' requires resolving 'he' 'John'. A document with mentions has candidate pairs. Modern coreference models score each pair with where are span representations. The highest-scoring antecedent for each mention forms the coreference chain.
Resolve 'it' in these two sentences: (A) 'The trophy doesn't fit in the suitcase because it is too big.' (B) 'The trophy doesn't fit in the suitcase because it is too small.'
Sarcasm, Irony, and Figurative Language
In figurative language the intended meaning differs from the literal words. Sarcasm says the opposite of what is meant ('Oh great, another meeting'), hyperbole exaggerates, metaphors map one domain onto another, and idioms such as 'kick the bucket' have meanings unrelated to their parts. A sentiment model that sums word polarities reads 'great' as positive and misses the complaint. The usual cue to sarcasm is incongruity, positive wording about a negative situation, which needs knowledge of what situations are normally pleasant. Tone of voice and facial expression are lost in text, and even human annotators disagree on sarcasm, which makes labeled data noisy and evaluation unreliable.
Sarcasm inverts the literal sentiment: 'Great, another meeting' has positive lexicon but negative intent. Formally, even though surface features predict positive. Detecting sarcasm requires modeling the gap between expected and observed sentiment — incongruity theory says sarcasm occurs when context makes the literal meaning absurd.
A sentiment analyzer classifies 'What a wonderful way to spend a Saturday --- stuck in traffic for three hours' as positive. Why did it fail?
Multilingual and Low-Resource Challenges
Most NLP research and data cover a handful of the world's 7,000 or so languages. Joshi et al. (2020) found that most languages have almost no labeled data, so methods that need millions of annotated examples do not transfer. Languages also differ structurally. Agglutinative languages such as Turkish and Finnish stack suffixes, so a single root yields thousands of word forms and word-level vocabularies explode. Chinese, Japanese, and Thai do not mark word boundaries with spaces, so segmentation becomes a task in itself. Multilingual models such as mBERT and XLM-R share one subword vocabulary across about 100 languages and transfer some skill from high-resource to low-resource languages.
A multilingual model with shared vocabulary across languages must handle different morphological systems. Zipf's law says the -th most common word has frequency , but the distribution shape varies by language. Agglutinative languages (Turkish, Finnish) have much larger effective vocabularies: Turkish can form valid word forms from a single root, making word-level tokenization impractical.
Turkish is agglutinative: 'evlerinizden' = 'from your houses'. How does this affect NLP compared to English?
Theory Exercise
Problem:
Design a test suite of 5 sentences that would challenge an NLP sentiment analysis system. Each sentence should exploit a different NLP challenge (ambiguity, sarcasm, negation, context-dependence, figurative language). Explain what makes each one hard.
Coding Exercise
Problem:
Write a function that detects potential sarcasm in text using simple heuristics: (1) positive words combined with negative context, (2) exaggeration markers (all-caps, excessive punctuation), (3) contradictory sentiment within the same sentence.
Related Problems on PixelBank
A user types "python snake not programming" into a search box, a traveler points a phone at a German menu, a customer writes that a shirt arrived damaged, and a doctor dictates a note full of abbreviations. Each expects a useful answer in seconds. None of these products is a single NLP task; each chains several of the tasks and representations from this chapter, and each fails in its own characteristic way.
The previous topic, Challenges in NLP, catalogued what makes language hard: ambiguity, context, figurative meaning, and linguistic diversity. This topic shows how real applications cope with those challenges. It starts with search and information retrieval, which combines TF-IDF-style lexical matching with dense embeddings. Machine translation follows, the field's oldest goal, now handled by Transformer encoder-decoders. Conversational AI then chains intent detection, entity extraction, and generation within a dialogue. The topic ends with healthcare NLP, where domain vocabulary and high stakes demand specialized models. Each application is a case study in combining components.
Definition
An NLP application is an end-to-end system that composes core tasks, such as tokenization, classification, entity recognition, retrieval, and generation, to serve a user goal. It is evaluated by task-level metrics and by outcomes for users, such as relevance, translation quality, or task completion.
In this topic
- 1Search and Information Retrieval
- 2Machine Translation
- 3Conversational AI and Chatbots
- 4Healthcare and Biomedical NLP
Search and Information Retrieval
Search ranks documents by relevance to a query. The formula scores a document for a query by summing, over each query term , the term's TF-IDF weight in the document times its IDF, so rare query words that appear often in the document count most. BM25 refines this by saturating term frequency and normalizing for document length. Lexical matching fails on synonyms: a query for 'car' misses a page that only says 'automobile'. Dense retrieval embeds queries and documents as vectors and compares them, and DPR beat a BM25 baseline by 9 to 19 points in top-20 passage accuracy. Production systems combine both, then rerank the top results.
Search engines rank documents by relevance score . BM25 refines this: where controls term frequency saturation and controls document length normalization.
A user searches "python snake not programming". How should the search engine interpret this?
Machine Translation
Machine translation maps a source sentence to a target sentence . The formula factors the probability autoregressively: each target token is predicted from the source and the tokens already produced, and decoding searches for a high-probability , usually with beam search. The field moved from word-for-word rules to statistical phrase tables and then to neural encoder-decoders; Google's 2016 neural system cut translation errors by an average of 60 percent compared with its phrase-based system. Today's Transformer models learn from hundreds of millions of sentence pairs. They still struggle with idioms, rare terminology, low-resource languages, and preserving tone.
Machine translation maximizes autoregressively. BLEU score measures quality by counting -gram precision: where is the fraction of predicted -grams found in the reference. The brevity penalty BP penalizes translations shorter than the reference.
Why is translating 'It's raining cats and dogs' literally into another language problematic?
Conversational AI and Chatbots
Conversational systems carry on multi-turn dialogue. Task-oriented assistants help a user complete a goal, such as booking a flight or getting a refund, and are traditionally built as a pipeline: intent classification finds what the user wants, slot filling extracts the needed parameters, dialogue state tracking remembers what has been said, a policy decides the next action, and generation phrases the reply. Open-domain chatbots handle free conversation. Large language models fine-tuned with human feedback now perform most of these steps in one model, but production systems still extract structured intents and slots so they can call backend APIs reliably and check their actions.
A dialogue system models where are user turns and are system responses. The context window grows linearly with conversation length. With turns of average tokens, attention cost is . This quadratic growth explains why long conversations degrade — the model must attend over thousands of tokens to maintain coherence.
A customer says: 'I ordered a blue shirt last Tuesday and it arrived damaged. I want a refund, not a replacement.' Identify the NLP tasks needed to handle this.
Healthcare and Biomedical NLP
Clinical notes, research papers, and patient records hold information that structured databases miss. Biomedical NLP extracts it: clinical NER finds diseases, drugs, doses, and symptoms; medical coding maps diagnoses to ICD codes for billing and statistics; relation extraction finds drug interactions in the literature; and trial matching links patients to eligibility criteria. General models struggle because clinical text is telegraphic and full of abbreviations, and because negation matters ('no fever' is not a fever). Models pretrained on biomedical text, such as BioBERT, which continued BERT's training on PubMed, outperform general models on these tasks. Privacy rules and the cost of errors make deployment harder than in most domains.
Clinical NER extracts entities from medical text: drug names, dosages, conditions, procedures. The challenge is that medical vocabulary is vast ( terms in UMLS) and highly specialized. Transfer learning helps: pre-train on general text (BERT), then fine-tune on biomedical corpora (BioBERT). The domain-specific vocabulary is handled by continued pre-training on PubMed abstracts ( documents).
A doctor's note reads: 'Pt presents with 3-day h/o productive cough, low-grade fever. Started amoxicillin 500mg TID. F/u in 1 week.' Extract structured information.
Theory Exercise
Problem:
Design an NLP pipeline for an automated email triage system for a company that receives 10,000 emails per day. What NLP components would you need, how would you handle edge cases, and what are the risks of automation?
Coding Exercise
Problem:
Build a simple FAQ chatbot that matches user questions to a knowledge base using TF-IDF similarity. The chatbot should find the most relevant FAQ entry and return the answer, with a confidence threshold below which it says 'I don't know'.