Lecture 1 · Introduction and Fundamentals: One Recipe Behind (Almost) Every NLP System

Advanced Natural Language Processing · Lecture 01。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: CMU 11-711 Spring 2026, Lecture 1 (01/13), slides anlp-s2026-01-intro.pdf; course demo code 01_intro/ (rule_based_classifier.ipynb, trained_bow_classifier.ipynb, originally from Graham Neubig’s anlp-code). Readings: K. Cho, Natural Language Understanding with Distributed Representation (2015), ch. 1; K. Cho, Machine Learning: a Lecture Note (2025), ch. 1. Sources: the public slides and notebooks above, the two readings, and the classic papers cited in each section. The slides are terse; this lecture expands them. All experiments, and every number labelled “measured”, come from the code written for these notes (code/lecture01/) and were run on the author’s machine (Apple M4 Pro, macOS, Python 3.13 and 3.9 give identical output). Code: code/lecture01/ — standard library only, every script finishes in seconds. Reading time: ~100 minutes for the prose; ~30 more if you run and read every demo.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Say what an NLP system does in three verbs — represent, generate, act — and why language is hard for computers (ambiguity, variability, sparsity, compositionality, many languages).
  2. Describe any NLP task as a function from an input space X\mathcal{X} to an output space Y\mathcal{Y}, and choose between rules, supervised learning and reinforcement learning by what data each needs.
  3. Build a rule-based sentiment classifier and explain, with measurements, why rules plateau.
  4. State the general recipe: a parameterized scoring function sθ(x,y)s_\theta(x, y), and its three ingredients — model/parameterization, learning, inference.
  5. Implement a bag-of-words linear classifier, train it with the perceptron and with logistic regression (cross-entropy + SGD), and read what it learned.
  6. Prove two things a linear bag of words can never do (tell apart sentences with the same words; handle negation as an XOR), and connect them to the course’s later answers.
  7. Turn scores into probabilities with the softmax, and see how the same recipe covers ranking, generation and decision-making (policies learned from rewards).
  8. Place every later lecture of the course on this map.

0.2 Prerequisites and scope

  • Prerequisites: Python; basic probability (distributions, expectation); linear algebra (vectors, dot products). No machine-learning background is assumed for this lecture; Lecture 2 introduces neural networks.
  • Scope: the framework of the whole course, made concrete with the simplest possible models — linear functions of word counts. Every limitation we hit today is the motivation for a later lecture, and the text points forward each time.
  • Not in scope today: neural networks (Lecture 2), language models (Lecture 3), Transformers (Lecture 5). When they appear, it is as a forward pointer.

0.3 Section → code map

SectionIdeaDemo in code/lecture01/
§3a rule-based classifier; the bias trap; iterating on rules; the difficult cases01_rule_based.py
§4.1–4.3features, weights, scores; binary vs general s(x,y)s(x, y); a weight matrix02_scoring_function.py Parts A–B
§4.4–4.5the perceptron; averaging; learning curve vs rules; what was learned; other languages; real SST03_perceptron.py
§4.6logistic regression = minimizing cross-entropy; step sizes; calibration04_loss_and_limits.py Parts A–B
§4.7what a bag of words is missing: minimal pairs, the negation XOR, unseen words, feature engineering02_scoring_function.py Parts C–D, 04_loss_and_limits.py Parts C–E
§5softmax and temperature; ranking; generation over sentences; policies from rewards05_beyond_classification.py
allthe dataset every demo usesreview_world.py (run it to see one review of every kind)

0.4 Notation

SymbolMeaning
x∈Xx \in \mathcal{X}, y∈Yy \in \mathcal{Y}an input (e.g. a review) and an output (e.g. a label in {−1,0,+1}\{-1, 0, +1\})
D={(xi,yi)}i=1N\mathcal{D} = \{(x_i, y_i)\}_{i=1}^Na dataset of NN input–output pairs
f(x)∈Rhf(x) \in \mathbb{R}^ha feature vector (特征向量) computed from xx
w∈Rhw \in \mathbb{R}^h, W∈Rh×KW \in \mathbb{R}^{h \times K}weights (权重): one vector (binary) or one column per label (KK labels)
sθ(x,y)s_\theta(x, y)the score (得分) of output yy for input xx; θ\theta = all parameters
g(x)g(x) or y^\hat ythe decision (prediction)
VVthe vocabulary (set of word types); ∣V∣\lvert V\rvert its size
L(θ,D)\mathcal{L}(\theta, \mathcal{D})the total loss (损失) of parameters θ\theta on dataset D\mathcal{D}

Accuracies in this lecture are on Cinema World’s dev split (1,000 reviews) unless stated otherwise; §3.1 introduces it.


1. What is NLP, and why is it hard?

1.1 Three things an NLP system does

The slides define natural language processing (自然语言处理, NLP) as technology that enables computers to process, generate, and interact with language, and single out three aspects. They are worth keeping apart, because the course’s three halves roughly follow them.

  1. Learn useful representations (表示). Capture meaning in a structured way that other computations can use. A review becomes a vector; a classifier reads the vector. A search engine turns queries and documents into vectors and compares them. Lectures 2–5 are about learning good representations.
  2. Generate language (生成). Produce text (or code) for dialogue, translation, summarization, question answering. Generation is harder than classification because the output space is astronomically large (§5.4). Lectures 3, 6–9 and 15 are about generation.
  3. Bridge language and action (语言与行动). Use language to do things: call tools, browse the web, edit code, operate a computer. Lectures 16–18 are about acting.

The opening slides show one example of each, all generated in January 2025: a chat model (DeepSeek-V3) answering a question, OpenScholar answering a research question with citations to papers it retrieved, and OpenHands, an agent that writes and runs code in a sandbox. The course’s promise is that by the end you will understand the fundamental concepts and practical techniques under systems like these.

1.2 Why language is hard for computers

Before building anything, it helps to list why the problem is hard, because every difficulty we meet today is an instance of one of these.

Property of languageExampleWhat it does to a system
Ambiguity (歧义)“I saw the man with the telescope” (who has the telescope?); “bank” (river or money)the same string has several meanings; context must choose
Variability (多样性)“I loved it” / “an absolute delight” / “worth every penny”many strings, one meaning; a system must generalize across paraphrases
Sparsity (稀疏性) — Zipf’s lawin any corpus a few words are very frequent and most words are raremany test inputs contain words never seen in training
Compositionality (组合性)“not good”, “good, but too long”meaning depends on structure, not just on which words occur
Figurative language (比喻)“has all the depth of a wading pool”the words do not mean what they literally say
Many languages (多语言)~7,000 living languages, most with little dataanything hand-built for English must be rebuilt

Keep this table in mind: §3.5 measures each of these on a sentiment classifier, one by one.

1.3 A one-paragraph history, seen through the recipe

NLP has gone through roughly four eras, and the cleanest way to see the difference between them is to ask which parts of a system a human designs and which parts are learned from data.

EraTypical systemDesigned by handLearned from data
Rules (1950s–1980s)Georgetown–IBM translation demo (1954), ELIZA (1966), SHRDLU (1970), expert systemseverything: features, weights, decisionsnothing
Statistical (late 1980s–2000s)IBM translation models, HMM taggers, n-gram language models, SVMs / logistic regression over hand-built featuresfeaturesweights
Neural (2010s)word2vec (2013), sequence-to-sequence (2014), attention (2014–15), the Transformer (2017)architecturefeatures and weights
Pretrained / LLM (2018–)BERT, GPT-2/3, instruction-tuned and RL-trained chat models, reasoning modelsarchitecture, data, training objectivesgeneral-purpose representations from raw text; task behaviour from prompts, fine-tuning, rewards

The history of NLP is largely the history of moving things from the “designed by hand” column to the “learned from data” column. This lecture walks through that move on one small task, in miniature: first everything by hand (§3), then learned weights over hand-designed features (§4), then a look at what can only be fixed by learning the features too (§4.7, and Lecture 2 onward).


2. Tasks as functions, and three ways to build them

2.1 Input → output

Many NLP tasks have an input x∈Xx \in \mathcal{X} and an output y∈Yy \in \mathcal{Y}, where xx and/or yy involve language:

Input xxOutput yyTask
texta labeltext classification (文本分类): sentiment, topic, spam, toxicity
texttext in another languagemachine translation (机器翻译)
imagetextimage captioning (图像描述)
search querya list of documentsretrieval (检索) / ranking
the state of an environmentan actiondecision-making / agent tasks (智能体任务)
question (+ documents)answerquestion answering
long textshort textsummarization
sentencea tree / a tag per wordparsing, named-entity recognition (structured prediction)

What changes from row to row is the output space: a handful of labels, a ranking of documents, the set of all sentences, the set of all actions. What does not change, as we will see, is the shape of the solution.

2.2 Three ways to build the function

The slides name three approaches:

  1. Rules (规则). A person writes the function directly. The slide’s example classifies a sentence as “sports” if it contains one of baseball, soccer, football, tennis.
  2. Supervised learning (监督学习). A person collects examples (x,y)(x, y) — “I love to play baseball” → sports, “The stock price is going up” → other — and a learning algorithm builds the function. Note the slide’s sly examples: “He got a hat-trick yesterday” (sports, no keyword) and “He is wearing tennis shoes” (other, despite the keyword). A rule is fooled both times; a learner that has seen enough examples need not be.
  3. Reinforcement learning (强化学习). The system acts in an environment and receives a reward (奖励); it learns to choose actions that maximize reward. Nobody tells it the right answer, only how good its own answer was.

2.3 What each approach needs: data requirements

ApproachWhat you needWhat you get
rules (or a prompt) written from intuitionno datano performance guarantee at all
rules (or a prompt) refined by spot-checksa small amount of input data xx (you look at examples and their outputs)some confidence on what you looked at
supervised learningan additional training set of (x,y)(x, y) pairs; more is usually betterperformance that improves with data, measurable on held-out data
reinforcement learningan environment: inputs, states, actions, transitions, and a reward functionbehaviour optimized for the reward (for better or worse)

Notice that the slide puts prompting next to rules. Writing a prompt for a large language model is, in this table, the modern version of writing rules: you encode your intuition in natural language instead of Python, you need no training data, and you get no guarantee until you measure. Everything this lecture says about the limits of hand-written rules (§3.6) applies to prompts too, which is why later lectures care so much about evaluation (Lecture 13).

2.4 Three splits of data, and why the third one is sacred

Whenever data is involved, it is split three ways:

  • training set (训练集) Dtrain\mathcal{D}_\text{train}: used to set the parameters;
  • development set (开发集) Ddev\mathcal{D}_\text{dev}, also called validation set: used to compare choices — which rules, which features, how many epochs — as often as you like;
  • test set (测试集) Dtest\mathcal{D}_\text{test}: used once, at the very end, to estimate how the final system will do on new data.

Why can’t you just report the dev number? Because every choice you made by looking at dev results has slightly fitted the dev set — including, as in §3.4, choosing rules by reading dev errors. The test set is the only data that never influenced a decision, so it is the only honest estimate. (In our demos the dev and test numbers end up close, e.g. 78.2% vs 79.0% for the final rules, because Cinema World’s dev and test sets come from the same simple generator. On real benchmarks that are reused for years, the gap between “tuned on” and “fresh” data can be large.)


3. A rule-based NLP system

3.1 The task and our dataset

The running example of the lecture is sentiment analysis (情感分析): given a movie review xx, decide whether its label yy is positive (+1+1), negative (−1-1) or neutral (00). Formally we want a classifier g:X→Yg : \mathcal{X} \to \mathcal{Y} with Y={−1,0,+1}\mathcal{Y} = \{-1, 0, +1\}, and we are given a dataset D={(xi,yi)}i=1N\mathcal{D} = \{(x_i, y_i)\}_{i=1}^N.

The course’s notebooks use the Stanford Sentiment Treebank (SST) (Socher et al., 2013): 11,855 single sentences from movie reviews, here with three labels (8,544 train / 1,101 dev / 2,210 test sentences). Real data is the ultimate test, but it has a drawback for learning about methods: when a classifier fails on “Has all the depth of a wading pool .”, you cannot tell whether the cause is the metaphor, the rare words, or a noisy label.

So the demos run on Cinema World (review_world.py), a synthetic review dataset in the same format (lowercase, space-tokenized, labels −1/0/+1-1/0/+1) where every review is generated from a template and records which linguistic phenomenon decides its label:

KindExample (from the dev split)True label
plainthe soundtrack feels interminable .−1 (the adjective)
morphologythe acting is awkwardly paced .−1 (an inflected verb or derived adverb)
negationthe movie is not bland .+1 (negation flips polarity)
contrasteven though the ending is silly , the film is enjoyable .+1 (the main clause decides)
idiomthe jokes land with a thud .−1 (a fixed phrase of non-sentiment words)
neutral_adjthe cast is short .0
factualit is a drama set in the desert .0
mixedit is dull in places and gripping in others .0 (balanced)

Sentiment adjectives come in three frequency tiers (common / mid / rare), imitating Zipf’s law (齐普夫定律). Reviews also carry neutral filler sentences (cast, running time, genre). The genre word is weakly correlated with the label by design (horror is more common in negative reviews), a spurious cue (虚假线索) that a learner might pick up. Training labels are corrupted with probability 5%, like annotation mistakes; dev and test labels are clean. Finally, every review also exists in Zorbian, a made-up language: each English word maps to a fixed invented word, and word order inside each sentence is reversed.

Cinema World is far simpler than real language (639 word types in the training split, 338 of them numbers). Treat its numbers as a microscope slide: good for seeing mechanisms, not a benchmark. Where possible we cross-check against real SST (§4.5).

3.2 Features, score, decision

The notebook’s rule-based classifier has a structure that will survive the whole course:

  1. Extract a feature vector f(x)∈Rhf(x) \in \mathbb{R}^h — numbers that summarize the input. In the notebook: good_word_count (how many words from a list of 6 positive words occur), bad_word_count (7 negative words), and bias, which is always 1.
  2. Compute a score as a weighted sum: s(x)=w⊤f(x)=∑kwkfk(x)s(x) = w^\top f(x) = \sum_k w_k f_k(x), with weights ww = (good: +1+1, bad: −1-1, bias: +0.5+0.5).
  3. Decide with the sign of the score:
g(x)={+1s(x)>0+0s(x)=0−1s(x)<0g(x) = \begin{cases} +1 & s(x) > 0 \\ \phantom{+}0 & s(x) = 0 \\ -1 & s(x) < 0 \end{cases}

The parameters θ\theta are here just ww, and a human chose them.

Why this shape? A weighted sum is the simplest way to combine many weak pieces of evidence: each feature votes, the weight says how strongly and in which direction, and the sign of the total is the verdict. It also makes the system inspectable: for any decision you can list each feature’s contribution wkfk(x)w_k f_k(x) and see why (demo 02 Part A prints exactly this table).

3.3 The bias trap (demo 01, Part A)

What does the bias +0.5+0.5 do? A review containing none of the 13 keywords has score exactly 0.5>00.5 > 0, so it is called positive. Measured on Cinema World:

rule setdev accpredicts +1predicts 0predicts −1
notebook rules, bias 0.542.3%93.7%0.0%6.3%
same rules, bias 026.5%7.3%86.4%6.3%
always predict −1 (majority class)40.8%

864 of the 1,000 dev reviews contain none of the 13 keywords, so the bias decides almost everything. The bias-0.5 version beats the bias-0 version only because “positive” is a common label; it barely beats the trivial majority-class baseline (多数类基线). On real SST the notebook’s rules score 42.1% on dev (demo 03 --sst; the notebook itself prints 0.4214), against 40.3% for always predicting +1+1.

Two lessons that apply far beyond rules:

  • Always report the trivial baseline. “42% accuracy” sounds like something until you learn that saying “positive” every time gets 40%.
  • The bias is the answer for “no evidence”. With bias 0, “no evidence” means “neutral”; with bias 0.5, it means “positive”. This is a modeling decision, and it should be made on purpose.

3.4 Iterating on rules (demo 01, Part B)

Let us play the rule writer’s game honestly, one idea at a time, and measure each step on dev. For each version, “fixed” and “broke” count the dev reviews that it got right/wrong relative to the previous version.

versiondevplainmorphnegcontridiomn-adjfactmixedfixedbroke
v1 intuition lexicon (31 words)36.1%49002101001005911721
v2 + spot-checked words and word forms56.3%875001401001007622826
v3 + negation flip64.1%87508614010010076780
v4 + contrast clauses73.1%87508686010010076900
v5 + spotted idioms (7 of 14)78.2%875086864910010076510

(Per-phenomenon columns are % correct. The final rules score 79.0% on the test split, evaluated once.)

What each version encodes:

  • v1 is a sentiment lexicon (情感词典) written from intuition without looking at any data: good, great, love, excellent, … and bad, terrible, awful, boring, …. The neutral columns are perfect (no keyword → score 0 → neutral), but most opinions are missed.
  • v2 adds what a careful person adds after spot-checking about 50 dev reviews: inflected forms (loved, loves, hated, …), adverbs (beautifully, clumsily, …) and mid-frequency adjectives (gripping, contrived, …). Biggest single gain: +20.2 points.
  • v3 adds a negation (否定) rule: a sentiment word preceded within 3 tokens by not / n't / never / no counts with the opposite sign. Negation accuracy goes 0% → 86%.
  • v4 adds a contrast (转折) rule: in a sentence with “but”, only the clause after “but” counts; a clause introduced by “even though” does not count. Contrast goes 14% → 86%.
  • v5 adds the idioms the writer happened to notice (edge of my seat, checking my watch, …): 7 of the world’s 14.

Two things in the “broke” column deserve attention:

  1. Adding words breaks things. v1 broke 21 reviews (13 mixed, 4 contrast) and v2 broke 26 (19 contrast, 7 mixed). How can a bigger lexicon hurt? With a small lexicon, a contrast review like “the pacing is brilliant , but overall it is banal .” might contain only one known word, which by luck could be the decisive one. Once the lexicon knows both words, they cancel (score 0 → neutral) or the wrong one wins. Rules interact, and an improvement in one place can be a regression in another.
  2. The negation, contrast and idiom rules broke nothing — but only because they copy Cinema World’s grammar exactly. I wrote both the world and the rules, so the rule writer here has perfect knowledge of how sentences are built. On real text such rules misfire: “not only good but great” is not negative, and “but” sometimes introduces the weaker clause. Read the v3–v5 rows as the best case for hand-written structure.

3.5 The difficult cases, measured (demo 01, Parts C–D)

The slides list five difficult cases for rules, with real SST examples. Cinema World lets us measure each one separately.

Low-frequency words. “The action switches between past and present, but the material link is too tenuous to anchor the emotional connections that purport to span a 125-year divide.” — negative, but which word would you put in the lexicon? For the plain Cinema World reviews, grouped by how common the decisive adjective is, the final rules (v5) score:

adjective tiern (dev)rules v5 accuracy
common (good, dull, …)145100.0%
mid (gripping, contrived, …)8076.2%
rare (luminous, turgid, interminable, …)190.0%

Every rare adjective scores 0 → neutral. A spot-check of 50 reviews would never meet “stultifying”. This is Zipf’s law at work: however many words you add, the tail is longer than your patience.

Conjugation (word forms). “An operatic, sprawling picture that’s entertainingly acted, magnificently shot…” — “entertainingly” and “magnificently” are forms of words a lexicon might contain (“entertaining”, “magnificent”) but do not match them. The slide’s suggestion — “use the root form and part-of-speech” — is what stemming (词干提取) and lemmatization (词形还原) do. In Cinema World, even after v2 added common inflections, morphology reviews are only 50% right (relished, detesting, loathing, … keep coming).

Negation. “This one is not nearly as dreadful as expected.” — positive. Without a negation rule, Cinema World’s negation reviews are 0% right (the rules see dreadful-type words and are confidently wrong); the v3 rule fixes most of them in this world. The slide’s proposed rule, “if a negation modifies a word, disregard it”, already shows the difficulty: “not dull” is not neutral, it is (mildly) positive — and in real English “not bad” is lukewarm, not enthusiastic.

Metaphor and analogy. “Has all the depth of a wading pool.” — the slide’s proposed solution is literally ”???”. Idioms are made of neutral words; the only rule-based remedy is to list them. Cinema World’s v5 lists 7 of its 14 idioms and gets 48.6% of idiom reviews.

Other languages. (A Japanese review.) — “Learn Japanese and re-do all the work?” Demo 01 runs the full v5 rule set on the Zorbian translation of the same dev reviews:

languagedev accuracypredicts 0
English78.2%38.5%
Zorbian19.1%100.0%

No keyword ever matches, every score is 0, every review is called neutral, and the accuracy equals the share of neutral reviews (19.1%). All the work — lexicon, inflections, negation and contrast rules, idioms — is English-specific and worth nothing in another language.

3.6 Why rules plateau

Rules are not stupid: on the phenomena they were written for, they are excellent (86% on negation and contrast here, better than the learned models of §4). They plateau for four structural reasons:

  1. Coverage. Language has a long tail (rare words, new idioms, typos, slang); a human enumerates only the head.
  2. Interaction. Rules combine in ways their author did not foresee; fixes break other cases (47 breakages from lexicon growth in §3.4).
  3. No notion of confidence. A rule fires or it does not; there is no graded “probably positive”, and no principled way to combine conflicting rules.
  4. Portability. Every rule is tied to a language and a domain (§3.5’s Zorbian row).

Fred Jelinek’s (possibly apocryphal) remark from IBM’s speech group in the 1980s — that every time he fired a linguist, his recognizer got better — is usually quoted as an attack on linguistics. The fairer reading is about where knowledge enters the system. Knowledge that a person can state precisely (negation flips polarity) can be written as a rule. Knowledge that lives in the statistics of millions of examples (that “stultifying” is negative, that “a feast for the eyes” is praise) is better learned. The rest of this lecture moves the weights, and then the features, from the person to the data.


4. Learning the scoring function

4.1 A more general recipe: scoring every output

Section 3 scored the input, s(x)s(x), and then took a sign. That only works for two labels. The general recipe scores each candidate output:

sθ(x,y)∈R:how compatible is output y with input x?s_\theta(x, y) \in \mathbb{R}: \quad \text{how compatible is output } y \text{ with input } x?

A higher score means more compatible. Inference picks the most compatible output:

y^=arg⁡max⁡y∈Ysθ(x,y).\hat y = \arg\max_{y \in \mathcal{Y}} s_\theta(x, y).

The negative score is often called an energy (能量), E(x,y)=−sθ(x,y)E(x, y) = -s_\theta(x, y), a term from physics via LeCun et al.’s A Tutorial on Energy-Based Learning (2006) and used in Cho’s 2025 lecture note (one of today’s readings): low energy = compatible, and inference = finding the minimum-energy output.

Three concrete instances, all linear in a feature vector fϕ(x)f_\phi(x) produced by a feature extractor with parameters ϕ\phi (for a fixed, hand-designed extractor, ϕ\phi is empty):

  • Binary, y∈{−1,+1}y \in \{-1, +1\}: sθ(x)=w⊤fϕ(x)s_\theta(x) = w^\top f_\phi(x) and sθ(x,y)=y⋅sθ(x)s_\theta(x, y) = y \cdot s_\theta(x), with w∈Rhw \in \mathbb{R}^{h}.
  • Multi-class, y∈{1,…,K}y \in \{1, \dots, K\}: sθ(x)=W⊤fϕ(x)∈RKs_\theta(x) = W^\top f_\phi(x) \in \mathbb{R}^K and sθ(x,y)=sθ(x)[y]s_\theta(x, y) = s_\theta(x)[y], with W∈Rh×KW \in \mathbb{R}^{h \times K} — one column of weights per label.
  • In both cases θ=(w,ϕ)\theta = (w, \phi) or (W,ϕ)(W, \phi).

Why the binary case is not special. With s(x,y)=y⋅s(x)s(x, y) = y \cdot s(x):

arg⁡max⁡y∈{−1,+1}y⋅s(x)={+1s(x)>0−1s(x)<0=sign⁡(s(x)),\arg\max_{y \in \{-1, +1\}} y \cdot s(x) = \begin{cases} +1 & s(x) > 0 \\ -1 & s(x) < 0 \end{cases} = \operatorname{sign}(s(x)),

because +s(x)>−s(x)+s(x) > -s(x) exactly when s(x)>0s(x) > 0. Demo 02 Part B checks this on every dev review: the two decisions agree on all 490 reviews with s(x)≠0s(x) \ne 0 (the other 510 are ties, which the sign rule calls neutral). So the rule-based classifier of §3 was already an instance of the general recipe.

Why bother with s(x,y)s(x, y)? Because it does not care what yy is. Replace “label” with “document”, “sentence” or “action” and nothing in the recipe changes except how hard the argmax is (§5).

4.2 Three ingredients

Every system in this course is specified by three decisions:

  1. Model / parameterization (模型 / 参数化): the form of sθs_\theta and which parameters it has. Today: a linear function of word counts. Later: neural networks (Lectures 2–5), with billions of parameters.
  2. Learning (学习): how parameters are set from supervision — labelled pairs (supervised), raw text (self-supervised pretraining, Lecture 6), or rewards (Lectures 16–17).
  3. Inference (推断): how a decision is made with the learned function — argmax over a few labels today; search or sampling over sentences later (Lectures 9, 23).

In §3, the parameterization was “counts of keywords”, learning was a person editing lists, and inference was the sign. Now we keep a richer parameterization and hand learning to an algorithm.

4.3 The bag-of-words parameterization (demo 02)

Idea. Let the vocabulary VV be every word seen in training. Give every word its own feature: f(x)∈R∣V∣f(x) \in \mathbb{R}^{\lvert V\rvert} with fw(x)f_w(x) = the number of times word ww occurs in xx. Equivalently: look up a one-hot vector (独热向量) xt∈{0,1}∣V∣x_t \in \{0, 1\}^{\lvert V\rvert} for each token and add them up. This is the bag of words (词袋模型, BoW): word order is thrown away, only the multiset of words remains.

Then the score is

s(x)=w⊤f(x)=∑t=1Twxt(plus a bias),s(x) = w^\top f(x) = \sum_{t=1}^{T} w_{x_t} \quad (\text{plus a bias}),

the sum of one learned number per token. In the binary case each word has a single scalar — positive numbers mean “positive”, negative mean “negative”. In the multi-class case each word has KK numbers, one per label: a row of WW.

Demo 02 Part A prints this for one review, “the acting is clumsy but i loved it . it runs 101 minutes .”, with the hand weights of the v2 lexicon (+1+1 / −1-1):

  • f(x)f(x) has 13 nonzero entries, while the training vocabulary has 639 word types. Feature vectors in NLP are sparse (稀疏): almost all entries are 0, so we store only the nonzero ones (a Python dict), and a dot product costs as many multiplications as the review has distinct words.
  • The contributions are clumsy −1-1 and loved +1+1; everything else is 0. So s(x)=0s(x) = 0 and the decision is neutral — although a human reads the review as positive, because the clause after “but” wins. Hold that thought until §4.7.

Part B shows a hand-made 3-column weight matrix (one column per label) and the score table it produces. The column for “neutral” holds a positive bias weight. Neutral then wins whenever no sentiment word speaks, and the multi-class model gets a real, learnable notion of “no opinion” instead of “score exactly 0”.

Which problems from §3.5 can a bag of words solve? It gives every word a weight, so in principle it handles rare words (if they appear in training), word forms (each form is just another word), idioms (their words become sentiment-bearing) and any language (it never looks at what the words are). It cannot, in principle, handle anything that depends on order or structure. §4.5 and §4.7 measure both halves of that statement.

4.4 Learning with the perceptron

The problem. We want weights such that, on training data, the correct label gets the highest score. Write this as minimizing a loss:

min⁡θ L(θ,Dtrain),L(θ,D)=∑(x,y)∈DL(x,y,θ).\min_\theta \ \mathcal{L}(\theta, \mathcal{D}_\text{train}), \qquad \mathcal{L}(\theta, \mathcal{D}) = \sum_{(x, y) \in \mathcal{D}} L(x, y, \theta).

The simplest algorithm for linear scores is the perceptron (感知机) (Rosenblatt, 1958). The course notebook’s version:

feature_weights = {}
for x, y in data:
    features = extract_features(x)
    predicted_y = run_classifier(features)          # sign(w . f(x))
    if predicted_y != y:                            # only learn from mistakes
        for feature in features:
            feature_weights[feature] = feature_weights.get(feature, 0) + y * features[feature]

Intuition. If a positive review (y=+1y = +1) was scored too low, add its features to ww: every word in it becomes a little more positive. If a negative review was scored too high, subtract. After the update, the same review’s score has moved in the right direction by exactly ∥f(x)∥2\lVert f(x) \rVert^2:

y⋅(w+yf)⊤f=y w⊤f+y2∥f∥2=y w⊤f+∥f∥2.y \cdot (w + y f)^\top f = y\, w^\top f + y^2 \lVert f \rVert^2 = y\, w^\top f + \lVert f \rVert^2 .

The multi-class perceptron does the same with one weight vector per label: predict y^=arg⁡max⁡ywy⊤f(x)\hat y = \arg\max_y w_y^\top f(x); on a mistake, wy+=f(x)w_y \mathrel{+}= f(x) and wy^−=f(x)w_{\hat y} \mathrel{-}= f(x) — raise the truth, lower the wrong winner. The course calls it the structured perceptron: Collins (2002) showed that the identical update works when yy is a structure (a tag sequence, a parse tree). You add the features of the true structure and subtract those of the predicted one.

Does it converge? If the data are linearly separable with margin γ\gamma — some unit-length weight vector scores every correct label at least γ\gamma above every wrong one — and every ∥f(x)∥≤R\lVert f(x)\rVert \le R, then the perceptron makes at most (R/γ)2(R / \gamma)^2 mistakes in total, however many passes it makes (Novikoff, 1962). Real data are never separable: label noise alone guarantees it, and §4.7 shows that negation makes Cinema World non-separable for a bag of words even without noise. On non-separable data the perceptron never settles. Every remaining mistake keeps kicking the weights, and the final weights depend on which examples came last.

The fix: averaging. Return the average of the weight vector over all training steps instead of its final value (the averaged perceptron (平均感知机), Freund & Schapire, 1999). Late kicks then move the answer only slightly. Computing the average naively costs a full pass over all weights at every step; textclf.train_perceptron uses the standard trick of accumulating “update × timestamp” in a second dictionary and subtracting at the end.

Measured (demo 03, Parts A–B).

learner on Cinema World (N = 2,000)dev accuracy
notebook-style binary perceptron (trained on ±1 only, sign decision), 5 epochs, seeds 0 / 1 / 254.3% / 59.7% / 52.0%
multi-class perceptron, final weights, 10 epochs75.1%
multi-class perceptron, averaged weights, 10 epochs81.2%
  • The notebook’s binary perceptron skips neutral reviews in training and can output 0 only when the score is exactly 0. Once the bias and frequent words carry weights, that almost never happens (it predicts 0 for 1–3% of reviews), so the 19% neutral reviews are lost. The nearly 8-point spread across shuffling seeds (52.0% to 59.7%) shows how much the last few updates matter.
  • With three labels, the neutral class gets its own weight vector, and averaging adds another 6 points over the final weights. Across epochs 1 → 20, averaged dev accuracy goes 76.1 → 77.7 → 80.5 → 81.2 → 81.4%. Training accuracy keeps rising slowly (86.4% at 20 epochs) and can never reach 100%, because the data are not separable.

4.5 How much data beats hand-written rules? What does the model learn?

The learning curve (demo 03, Part C). Train the averaged perceptron on random subsets of a pool of 8,000 noisy training reviews (3 subsets per size) and compare with the rule sets of §3.4:

N labelled reviews25501002004001,0002,0004,0008,000
dev accuracy (mean of 3)39.9%45.2%47.5%60.9%69.8%76.0%80.9%83.8%84.2%

Hand rules: v1 (intuition) 36.1%, v2 (spot-checked lexicon) 56.3%, v5 (all rules) 78.2%.

  • 200 labelled reviews beat the hand lexicon (60.9% vs 56.3%). A learned lexicon covers every word that appears in training; a written one covers what a person thought of.
  • About 2,000 beat all the rules (80.9% vs 78.2%), including the negation and contrast rules that were written with perfect knowledge of the world’s grammar.
  • The curve flattens near 84%: more data stops helping when the remaining errors are things a bag of words cannot represent (§4.7).

What did it learn? (Part D.) For each feature, the margin w+1[k]−w−1[k]w_{+1}[k] - w_{-1}[k] says how hard it pushes toward positive:

  • Most positive: loved +23.5, witty +20.9, enjoyed +20.8, powerfully +18.4, relished +18.2, … and eyes +16.2, feast +16.2 (from the idiom “a feast for the eyes”).
  • Most negative: hated −21.5, awkward −19.9, clumsily −19.4, loathed −17.7, … insomnia, cure −16.2 (“a cure for insomnia”), and 1958 −15.3.

The learner rediscovered the lexicon and the idioms, with no linguist involved. It also learned things we did not want. “1958” is a year from a filler sentence that happened to occur in a few negative training reviews: pure noise, memorized. And the genre words, which never decide a label, got margins from horror −12.6 to documentary +9.6 and romance +9.3. By design only horror and documentary carry any (weak) signal, so the romance weight is noise-fitting too. A learned model absorbs every correlation in its training data, including the spurious ones, and nothing in the accuracy number warns you. You have to look at the weights (or, for neural models, use the tools of later lectures).

Learned vs rules, per phenomenon.

kindnrules v5learned BoWwinner
plain33387.1%85.0%rules
morphology15549.7%97.4%learned
negation9185.7%9.9%rules
contrast12585.6%58.4%rules
idiom10548.6%100.0%learned
neutral / factual68 / 74100% / 100%100% / 100%tie
mixed4975.5%100.0%learned
all1,00078.2%81.2%learned

This table is the whole lecture in miniature. Learning wins wherever the knowledge is lexical — which words and phrases signal what — because it reads every training example and forgets nothing. The rules win wherever the knowledge is structural — what “not” and “but” do to other words — because a person can state that knowledge and a bag of words cannot even represent it. Negation is the starkest case: the learned model gets 9.9%, far below chance. It sees “not … dull” and votes for dull.

Other languages (Part E). Train and test the same learner on Zorbian: 81.2%, with identical predictions on all 1,000 dev reviews. The top Zorbian features are gutelavo (= loved) +23.5, tagezala (= witty) +20.9, … The algorithm never knew what language it was reading. “Learn Japanese and redo the work?” — no: collect Japanese labels and rerun.

Real data (Part F, --sst). On SST, the same code gives: notebook rules 42.1%; binary perceptron 58.7% (train 75.2%); averaged 3-class perceptron 59.5% (train 95.7%). The ordering matches Cinema World, at a much lower absolute level. Real reviews are full of sarcasm, comparison, world knowledge and a vocabulary that never ends (“Sam Mendes has become valedictorian at the School for Soft Landings and Easy Ways Out”), and the 95.7% vs 59.5% gap shows a model memorizing its training sentences rather than learning anything that transfers.

4.6 Learning as loss minimization: logistic regression

The perceptron learns only from mistakes and gives only a label. A more principled route — and the one the rest of the course takes — turns scores into probabilities and maximizes the probability of the observed labels.

From scores to probabilities. The softmax (软最大化 / 归一化指数函数) maps any vector of scores to a distribution:

pθ(y∣x)=exp⁡sθ(x,y)∑y′exp⁡sθ(x,y′).p_\theta(y \mid x) = \frac{\exp s_\theta(x, y)}{\sum_{y'} \exp s_\theta(x, y')}.

Why the exponential? It makes every score positive (probabilities must be), it is monotone (the argmax does not change), it is smooth (we can take gradients), and it makes log⁡p\log p linear in the score, which keeps the loss’s gradient simple. (It is also the maximum-entropy distribution consistent with given expected scores, and the Boltzmann distribution of physics, which is where the word “energy” came from.) Adding the same constant to all scores leaves pp unchanged, which the code uses to avoid overflow: compute exp⁡(s−max⁡s)\exp(s - \max s).

The loss. Choose θ\theta to make the training labels likely: minimize the cross-entropy (交叉熵), or negative log-likelihood (负对数似然),

L(x,y,θ)=−log⁡pθ(y∣x).L(x, y, \theta) = -\log p_\theta(y \mid x).

A model that knows nothing — p=(1/3,1/3,1/3)p = (1/3, 1/3, 1/3) — pays log⁡3≈1.099\log 3 \approx 1.099 nats per example; a perfect, confident model pays 0. For linear scores s(x,k)=wk⊤f(x)s(x, k) = w_k^\top f(x), the gradient has a beautiful form:

∂L∂wk=(pθ(k∣x)−1[k=y]) f(x).\frac{\partial L}{\partial w_k} = \big(p_\theta(k \mid x) - \mathbb{1}[k = y]\big)\, f(x).

Push the true label’s weights up in proportion to how much probability it is missing (1−p(y∣x)1 - p(y \mid x)), and push every other label down in proportion to the probability it wrongly holds. Unlike the perceptron, this keeps learning from examples it gets right but without confidence. This model is (multinomial) logistic regression (逻辑回归).

Stochastic gradient descent (随机梯度下降, SGD). Visit training examples in random order and take a small step against each example’s gradient: θ←θ−η∇θL(x,y,θ)\theta \leftarrow \theta - \eta \nabla_\theta L(x, y, \theta), where η\eta is the learning rate (学习率).

Seen this way, the perceptron is SGD with step size 1 on the “perceptron loss” max⁡y′s(x,y′)−s(x,y)\max_{y'} s(x, y') - s(x, y), which is 0 when the prediction is right and otherwise has gradient +f+f for the wrong winner and −f-f for the truth. The two learners optimize different losses over the same model.

Measured (demo 04, Part A), with step size 0.1/(1+epoch)0.1 / (1 + \text{epoch}) and a little L2 regularization:

epoch1235810
train log loss0.6930.5120.4780.4630.4360.428
dev log loss0.7170.5320.4990.4730.4570.450
dev accuracy72.1%76.6%79.3%80.4%81.6%81.9%

Logistic regression ends at 81.9% vs the averaged perceptron’s 81.2%: same model family, different learning rule, nearly the same result. The gap between train and dev loss is what the model has memorized about its particular training set.

Why the step size must shrink. With a constant step of 0.3, dev accuracy after each epoch goes 70, 74, 70, 66, 76, 69, 78, 76, 72, 78% — swings of up to 9.6 points. Examples that the model cannot fit (negation, noisy labels) keep yanking the weights back and forth. With the decaying schedule 0.3/(1+e)0.3/(1 + e): 70, 76, 78, 78, 80, 80, 81, 81, 82, 81% — after epoch 3 the largest jump is 2.7 points. The classical condition (Robbins & Monro, 1951) is that step sizes must sum to infinity (so SGD can travel any distance) while their squares sum to something finite (so the noise eventually dies down); 1/(1+e)1/(1+e) satisfies both. Averaging the perceptron is the same idea in another form.

Are the probabilities trustworthy? (Part B.) Bucket dev predictions by the model’s confidence max⁡yp(y∣x)\max_y p(y \mid x):

confidence binnmean confidenceaccuracy
0.33–0.504746.2%63.8%
0.50–0.7035961.0%67.7%
0.70–0.9038179.7%87.7%
0.90–1.0021395.0%99.5%

Overall the model is under-confident (mean confidence 74.7%, accuracy 81.9%), most likely because the L2 penalty and the shrinking steps stop the weights before they grow large. But per phenomenon the picture flips: on negation reviews the model is 67.0% confident and 5.5% accurate. A probability is a statement by the model about itself. It inherits every blind spot of the features, and a model that cannot represent negation cannot know that it cannot. Calibration (校准) returns in Lecture 13.

4.7 What is missing? (demo 02 Parts C–D, demo 04 Parts C–E)

The slides list three things a bag of words lacks: conjugated or compound words (I loved this movie vs I love this movie), word similarity (I love vs I adore), and sentence structure (It has an interesting story, but is boring overall). Each can be made precise.

1. Structure: same bag, opposite meaning. Take every contrast review in dev and swap its two adjectives: “even though the ending is silly , the film is enjoyable .” (+1) becomes “even though the ending is enjoyable , the film is silly .” (−1). The two have the identical bag of words (the code asserts it). Any bag-of-words model, however trained, must give both the same score and hence the same label. So it gets at most one of each such minimal pair (最小对立对) right. Measured on 125 pairs: the trained BoW perceptron gets both twins right in 0 of 125 pairs. Adding bigram and clause-marker features (below) breaks the tie: 56 of 125 pairs fully right.

2. Interaction: negation is an XOR. Consider four sentences: “the plot is great .” (+), ”… dull .” (−), ”… not great .” (−), ”… not dull .” (+). A linear model on word counts gives them scores wg+bw_g + b, wd+bw_d + b, wg+wn+bw_g + w_n + b, wd+wn+bw_d + w_n + b, where bb absorbs the bias and the shared words. Getting all four right requires

wg+b>0(1)wg+wn+b<0(3)wd+b<0(2)wd+wn+b>0(4)\begin{aligned} w_g + b &> 0 &(1) \qquad\qquad w_g + w_n + b &< 0 &(3)\\ w_d + b &< 0 &(2) \qquad\qquad w_d + w_n + b &> 0 &(4) \end{aligned}

Adding (1) and (4) gives wg+wd+wn+2b>0w_g + w_d + w_n + 2b > 0; adding (2) and (3) gives the same expression <0< 0. No weights exist. Demo 02 confirms by brute force over 83,521 weight settings: the best is 3 of 4. The word “not” does not have a polarity of its own. It flips the polarity of what follows, an interaction (交互) between features, and a sum of per-word weights cannot express a product. (This is the same XOR that Minsky and Papert used in 1969 to show the limits of a single-layer perceptron.) Add one feature for the word pair, not|dull, and the four become separable (4 of 4 with w[not|great]=−2w[\text{not|great}] = -2, w[not|dull]=+2w[\text{not|dull}] = +2).

3. Similarity: unseen words are invisible. A word never seen in training has weight 0 in every class: the model is blind to it, even if it means the same as a word it knows well. Grouping plain and morphology reviews by how often their decisive word occurred in training:

training setunseenseen 1–2×seen 3–10×seen >10×
N = 20044.1% (111 reviews)64.3% (235)64.1% (142)— (0)
N = 2,00050.0% (2)77.3% (22)91.5% (130)88.9% (334)

With 200 training reviews, 111 of the 488 plain and morphology dev reviews (23%) hinge on a word the model has never seen, and it is little better than guessing on them. With 2,000, Cinema World’s small vocabulary is almost covered (2 reviews left), but real text never gets there: its long tail does not end. What would help is a representation in which “luminous” sits near “brilliant”, learned from the vast amount of unlabelled text in which both words appear in similar contexts. That is the distributional hypothesis (分布假说), and it is where Lecture 2 begins.

Repairing the bag of words by hand: feature engineering. The classic response (the statistical era of §1.3) was to design better features:

featuresdevplainmorphnegcontrZorbian dev
unigrams (bag of words)81.2%8597105881.2%
+ bigrams (adjacent word pairs)86.7%9190556686.4%
+ stems (crude_stem: loved, loves, loving → lov)81.4%869885981.4%
+ negation scope: words after a negator up to punctuation get a NOT_ copy (Das & Chen, 2001; Pang et al., 2002)87.2%9194665681.2%
+ clause markers: after_but: / conceded: copies83.9%8497128281.2%
all of the above89.0%9295587386.2%

Each feature family fixes the phenomenon it was designed for (negation 10 → 66 with NOT_, contrast 58 → 82 with clause markers), and together they lift dev accuracy from 81.2% to 89.0%. Look at the last column, though. In Zorbian only the bigrams still help, because they look at adjacent tokens and assume nothing about the language. The NOT_ and clause features never fire (they look for the English words “not”, “but”, “even though”), and the English stemmer merely merges unrelated Zorbian words that happen to end in -s or -ed (+0.2 points, by luck). Feature engineering is the rule writer’s job in disguise: it is language-specific labour, and it encodes only the phenomena someone thought of.

What is left? The all-features model still makes 110 errors on 1,000 dev reviews. 72 are negation or contrast (the hand features capture structure only partly: NOT_inventive is useless if that pair never occurred in training), 36 are plain or morphology reviews, and 12 hinge on a decisive word seen at most twice. Demo 04’s error analysis shows why individual errors happen by listing the features that pushed toward the wrong label rather than the right one, fk(x) (wwrong[k]−wright[k])f_k(x)\,(w_{\text{wrong}}[k] - w_{\text{right}}[k]). The culprits include the name otis (another spurious feature learned from noise) and the bigram is|charming from a conceded clause.

4.8 A better parameterization: learn the features too

Everything above kept f(x)f(x) fixed and learned only ww. The slides’ next step is to make the feature extractor itself a learned function — a neural network (神经网络) fϕ(x)f_\phi(x) with parameters ϕ\phi trained jointly with ww:

sθ(x)=w⊤fϕ(x),θ=(w,ϕ).s_\theta(x) = w^\top f_\phi(x), \qquad \theta = (w, \phi).

Each word is first looked up as a dense vector (an embedding (嵌入)), and a “complicated function learned from data” combines the vectors into fϕ(x)f_\phi(x). If similar words get similar vectors, the unseen-word problem shrinks. If the combination function can model interactions and order, negation and contrast become learnable instead of hand-coded. And none of it is language-specific. This raises the questions the next lectures answer: which architecture (Lecture 2: feed-forward networks; 4: recurrent networks; 5: Transformers), and which learning algorithm (gradient descent through the whole network: backpropagation, Lecture 2).


5. From classification to general tasks

5.1 The general recipe, once more

Build a parameterized scoring function sθ(x,y)s_\theta(x, y) that says how compatible output yy is with input xx; model its form; learn its parameters from supervision (labels, rewards); infer an output, y^=g(sθ,x)\hat y = g(s_\theta, x), by maximization or by sampling. Depending on what yy is, the same recipe is:

  • Classification: high scores for correct classes, low for incorrect ones (§§3–4).
  • Ranking: given a query xx, score documents y1,y2,…y_1, y_2, \dots so that they come out in the right order.
  • Probabilistic modeling: scores that define distributions p(y∣x)p(y \mid x) — e.g. xx an English sentence and yy a Japanese one; xx a conversation and yy the next response.

5.2 Ranking: yy is a document (demo 05, Part B)

Let yy range over a collection of documents, and score each by word overlap with the query, s(x,y)=∑w∈xfw(y)s(x, y) = \sum_{w \in x} f_w(y) — a bag-of-words dot product. Sort by score and you have a search engine. On 400 Cinema World reviews, the query “witty comedy” finds documents containing those words; but “hilarious” matches 0 documents, because the collection never uses that word, even though 8 of those 400 reviews call something “funny”. The failure is the unseen-word problem of §4.7 again. Retrieval systems solve it the same way NLP does: by learning dense representations where meanings, not strings, are compared (Lecture 10).

5.3 Probabilities, temperature, argmax vs sampling (demo 05, Part A)

With a probabilistic model we have two ways to infer: take the most probable output (y^=arg⁡max⁡ypθ(y∣x)\hat y = \arg\max_y p_\theta(y \mid x)), or sample one (y^∼pθ(y∣x)\hat y \sim p_\theta(y \mid x)). The trained logistic regression scores “i hated this movie .” as s=(−1: +2.05, 0: −2.16, +1: +0.11)s = (-1{:}\ +2.05,\ 0{:}\ -2.16,\ +1{:}\ +0.11), giving p(−1∣x)=86.4%p(-1 \mid x) = 86.4\%. Drawing 10,000 samples yields −1 in 86.7% of them: argmax always answers −1, while sampling answers something else 13.3% of the time.

A temperature (温度) TT rescales the scores before the softmax, pT(y∣x)∝exp⁡(s(x,y)/T)p_T(y \mid x) \propto \exp(s(x, y) / T):

temperaturep(−1 | x)p(0 | x)p(+1 | x)
T = 0.598.0%0.0%2.0%
T = 186.4%1.3%12.4%
T = 266.7%8.1%25.2%
T = 1040.3%26.5%33.2%

As T→0T \to 0 the distribution collapses onto the argmax; as T→∞T \to \infty it becomes uniform. For a three-way label, sampling is rarely what you want. For generating text, choosing between “always the most likely” and “varied” is a central design decision (Lecture 9).

5.4 Generation: yy is a whole sentence (demo 05, Part C)

Now let the output space be any sequence of words. The formula does not change:

pθ(y∣x)=exp⁡sθ(x,y)∑y′exp⁡sθ(x,y′).p_\theta(y \mid x) = \frac{\exp s_\theta(x, y)}{\sum_{y'} \exp s_\theta(x, y')}.

For “I hate this movie” we might now produce ”… because it isn’t creative.” — generation by sampling. Demo 05 does this exactly for a toy output space: all sentences of 4 words from a 12-word vocabulary (124=20,73612^4 = 20{,}736 candidates), each followed by ”.”, scored by

s(x,y)=log⁡Pbigram(y)⏟fluency+2⋅log⁡pclassifier(negative∣y)⏟agrees with x.s(x, y) = \underbrace{\log P_\text{bigram}(y)}_{\text{fluency}} + 2 \cdot \underbrace{\log p_\text{classifier}(\text{negative} \mid y)}_{\text{agrees with } x}.

The fluency term is a tiny bigram language model estimated from Cinema World text (Lecture 3’s subject). Enumerating all 20,736 sentences and normalizing gives exact probabilities: “the acting is dull .” 18.25%, “the plot is dull .” 17.25%, “the ending is dull .” 11.28%, …; the top 100 sentences hold 99.9% of the mass, and samples look like “the plot is boring .” and “the ending is silly .”.

Why this cannot scale. The denominator sums over every possible output:

vocabulary ∣V∣\lvert V\rvertlength TTnumber of outputs ∣V∣T\lvert V\rvert^T
124104.310^{4.3}
50,00010104710^{47}
50,00020109410^{94}
50,0001001047010^{470}

There are roughly 108010^{80} atoms in the observable universe. No computer will ever sum 109410^{94} terms. The way out, and the foundation of modern NLP, is to factorize the distribution over a sequence into one small softmax per token:

pθ(y∣x)=∏t=1Tpθ(yt∣y<t,x),p_\theta(y \mid x) = \prod_{t=1}^{T} p_\theta(y_t \mid y_{<t}, x),

each over only ∣V∣\lvert V\rvert choices. That is an autoregressive language model (自回归语言模型) (Lecture 3), and choosing a good yy under it without enumerating all of them is decoding (Lecture 9). Large language models are this recipe at scale: the course covers the modeling, learning and inference decisions needed to make it work.

5.5 Actions: yy is what to do next (demo 05, Part D)

A probabilistic model over outputs can also serve as a policy (策略): a distribution over actions aa given a state ss,

π(a∣s)  ⟺  pθ(y=a∣x=s).\pi(a \mid s) \iff p_\theta(y = a \mid x = s).

The slide’s example: the state is a movie-streaming website where the user said “I hate this movie”; the action is [CLICK] pause button. AI agents (Lecture 18) are policies whose states are web pages, terminals or screens.

The new element is how the policy learns. With supervised learning, every example names the correct action. In reinforcement learning, the policy tries an action and receives only a reward: right or wrong, more or less. Demo 05 sets this up as a one-step problem (a contextual bandit (上下文老虎机)). The state is a review, the actions are “recommend” (+1), “ask a friend” (0) and “skip” (−1), and the reward is 1 if the action fits the review’s true sentiment. The same linear softmax policy is trained two ways on the same stream of states:

  • from labels: one SGD step of logistic regression per state (the correct action is given);
  • from rewards only, with REINFORCE (Williams, 1992): sample a∼π(⋅∣s)a \sim \pi(\cdot \mid s), observe reward rr, and update wk+=η (r−b) (1[k=a]−π(k∣s)) f(s)w_k \mathrel{+}= \eta\,(r - b)\,(\mathbb{1}[k = a] - \pi(k \mid s))\,f(s). The update makes the sampled action more likely if it did better than the baseline (基线) bb (a running average of recent rewards) and less likely if it did worse.
interactions5001,0002,0004,0008,00016,00032,000
labels (mean of 3 seeds)52.9%62.1%68.8%77.2%75.8%79.1%80.1%
rewards only (mean of 3 seeds)40.6%41.1%41.3%43.8%57.5%69.0%75.4%

For its first ~4,000 interactions, the reward-trained policy stays within 5 points of “always skip” (40.8%, the majority action); it then learns, reaching 75.4% after 32,000 interactions — but with a huge spread across seeds (59.4% to 84.8%) — while the label-trained policy reached 77% after 4,000. Why so much slower?

  • A label tells you which of the three actions is right. A reward tells you only whether the action you happened to sample was right; after a wrong guess you still do not know which of the other two was correct.
  • The policy decides what it gets to learn about: once it leans toward one action, it rarely samples the others, so it rarely learns that they could be better. That is the exploration (探索) problem.
  • The reward signal is noisy, so updates have high variance; the baseline helps, and better variance reduction is a large part of RL algorithm design (Lecture 16). With many steps per episode there is also credit assignment: which of the actions earned the reward? It is absent here (one step), and central for agents and reasoning (Lectures 16–18, 23).

So why use rewards at all? Because for many tasks we cannot write down the correct output, but we can check one: a human can say which of two responses is better (Lecture 17, RLHF), a unit test can say whether code works, and a math checker can say whether an answer is right. Rewards are weaker supervision that is available where labels are not.


6. Roadmap of the course

Goal: build good learning-based systems for any NLP task. Along the two axes of the recipe:

  • Modeling / parameterization: neural network architectures; autoregressive, diffusion and flow models; images, retrieval, tools.
  • Learning: from unstructured data (pretraining), from paired data (fine-tuning, distillation), from an environment with a reward function (RL).
  • Inference: optimization and sampling; multi-sample strategies; efficient strategies.
ThemeLectures
Fundamentals: the general framework (1), deep learning and learned representations (2), language modeling (3)1–3
Architectures: recurrent networks (4), attention and Transformers (5); advanced: mixture of experts (21), long-sequence models (22)4–5, 21–22
Learning and inference: pretraining (6), scaling laws and in-context learning (7), fine-tuning and distillation (8), decoding (9); advanced: test-time scaling (23)6–9, 23
Generative models: autoregressive models (3), retrieval and RAG (10), multimodal models (11–12); advanced: diffusion and flows (15)3, 10–12, 15
Evaluation and research skills: evaluation techniques (13), experimental design (14)13–14
Reinforcement learning and agents: RL fundamentals (16), RL for language models (17), agents (18)16–18
Scaling and efficiency: quantization (19), parallel and distributed training (20), plus 21–2319–23

Relation to other CMU courses (from the slides): 11-711 covers the fundamentals and foundations of current NLP, including LLMs; LLM Applications (11-766) focuses on applying LLMs; Advanced Deep Learning (10-707) on building blocks of deep learning; Multimodal ML (11-777) on non-text modalities; Deep RL (10-703) on reinforcement learning; Code generation (11-891) on code; Inference for LMs (11-664) on inference; and LLM Systems (11-868) / 15-642 on systems, scaling and efficiency.


7. Summary

  1. NLP systems represent, generate and act; language is hard because of ambiguity, variability, sparsity (Zipf), compositionality, figurative language and the number of languages.
  2. Tasks are functions x→yx \to y, built by rules, supervised learning or RL, which need respectively no data (and give no guarantee), labelled pairs, or an environment with rewards. Prompting an LLM sits in the “rules” row.
  3. One recipe: a scoring function sθ(x,y)s_\theta(x, y); three ingredients — model, learning, inference. The rule-based classifier, the perceptron and logistic regression are all instances; binary sign⁡(s(x))\operatorname{sign}(s(x)) is arg⁡max⁡yy s(x)\arg\max_y y\, s(x).
  4. Rules are precise where a person can state the knowledge (negation, contrast: 86% here) and fail on coverage, interactions and portability (rare words 0%, Zorbian 19.1%).
  5. Learning a bag of words with the (averaged) perceptron or logistic regression beats a hand lexicon with ~200 labels and all hand rules with ~2,000 (81–82% vs 78.2%), works unchanged in any language, and absorbs spurious correlations as eagerly as real ones.
  6. Learning = minimizing a loss: cross-entropy for logistic regression, whose gradient is (p−one-hot)⋅f(p - \text{one-hot}) \cdot f; SGD needs shrinking steps on data it cannot fit.
  7. A linear bag of words provably cannot separate same-bag minimal pairs or represent negation (XOR); it cannot generalize to unseen words. Hand-built features help (89.0%) but are language-specific labour — the motivation for learning features (Lecture 2 on).
  8. The same recipe covers ranking, probabilistic generation (where ∣V∣T\lvert V\rvert^T forces token-by-token factorization, Lecture 3) and policies, which can learn from rewards — more slowly and less stably than from labels, but where labels do not exist.

Common pitfalls

  • Reporting accuracy without the majority baseline. The notebook’s ~42% rule set is 1.5 points above the majority-class baseline on Cinema World (always −1: 40.8%) and 1.8 above it on SST (always +1: 40.3%).
  • Tuning on the test set. Rules written by reading errors, features chosen by looking at results, epochs picked by peeking — all belong on dev. Test is touched once.
  • Treating learned weights as word meanings. “1958” got a margin of −15.3 and “romance” +9.3; weights record correlations in this training set, spurious ones included.
  • Using the final weights of a perceptron on non-separable data. Average them (75.1% → 81.2% here).
  • Training with a constant learning rate and reading one epoch’s number. On noisy data, dev accuracy can swing ~10 points between consecutive epochs.
  • Reading a probability as a guarantee. 67% average confidence on negation reviews came with 5.5% accuracy.
  • Concluding that rules (or structure) are useless. The hand-written negation and contrast rules beat the learned bag of words by 76 and 27 points on those phenomena. The lesson is to learn structure, not to ignore it.
  • Confusing “no evidence” with “neutral”. The bias decides what a model says when nothing fires; choose it deliberately.

Exercises

  1. Scoring by hand. With weights great +2, dull −2, not −0.5, bias +0.5 (binary, sign decision), compute s(x)s(x) and g(x)g(x) for (a) “the plot is great .”, (b) “the plot is not great .”, (c) “the film runs 99 minutes .”, (d) “the plot is not dull .”. Which are wrong, and why can no choice of these four weights fix all of them?

    Answer(a) 2 + 0.5 = 2.5 → +1 ✓. (b) 2 − 0.5 + 0.5 = 2 → +1 ✗ (should be −1). (c) 0.5 → +1 ✗ (should be 0; the bias decides "no evidence" = positive). (d) −2 − 0.5 + 0.5 = −2 → −1 ✗ (should be +1). (b) and (d) together are the negation XOR of §4.7: the conditions for great / dull / not great / not dull are contradictory for any per-word weights. (c) can be fixed with bias 0; (b)/(d) need a pair feature such as `not|great`.
  2. Binary as a special case. Show that for s(x,y)=y s(x)s(x, y) = y\, s(x) with y∈{−1,+1}y \in \{-1, +1\}, arg⁡max⁡ys(x,y)=sign⁡(s(x))\arg\max_y s(x, y) = \operatorname{sign}(s(x)) whenever s(x)≠0s(x) \ne 0. What happens at s(x)=0s(x) = 0, and how do the notebook and the multi-class model treat that case differently?

    AnswerThe two candidates score $+s(x)$ and $-s(x)$; the first is larger iff $s(x) > 0$. At $s(x) = 0$ they tie: the notebook's sign rule outputs 0 (neutral), which is the only way it can ever say neutral. A 3-class model gives "neutral" its own score $w_0^\top f(x)$, so neutral can win by evidence (e.g. a bias weight) instead of only by an exact tie.
  3. Perceptron by hand. Features are word counts plus a bias. Train a binary perceptron (start at w=0w = 0, predict with sign, treat 0 as a mistake) on, in order: (“good film”, +1), (“bad film”, −1), (“good plot”, +1), (“bad plot”, −1). Give ww after one epoch. Does a second epoch change anything?

    AnswerStep 1: score 0 → mistake, add: good +1, film +1, bias +1. Step 2: "bad film" scores film + bias = 2 → +1, mistake, subtract: bad −1, film 0, bias 0. Step 3: "good plot" scores 1 → +1 ✓. Step 4: "bad plot" scores −1 → −1 ✓. After epoch 1: good +1, bad −1, film 0, bias 0, plot 0. Epoch 2 makes no mistakes (scores +1, −1, +1, −1), so nothing changes: the data are separable and the perceptron has converged.
  4. Why the update helps. Show that after a binary perceptron update on a mistaken example (x,y)(x, y), the quantity y w⊤f(x)y\, w^\top f(x) increases by exactly ∥f(x)∥2\lVert f(x) \rVert^2. Does that guarantee the example is classified correctly afterwards?

    Answer$y (w + y f)^\top f = y w^\top f + y^2 f^\top f = y w^\top f + \lVert f\rVert^2$. No: if $y w^\top f$ was very negative (a confident mistake), one step may not be enough to cross 0, and later updates for other examples can undo it. The convergence theorem bounds the *total* number of mistakes on separable data, not each example's.
  5. The cross-entropy gradient. For p=softmax⁡(s)p = \operatorname{softmax}(s) with sk=wk⊤fs_k = w_k^\top f, derive ∂(−log⁡py)/∂wk=(pk−1[k=y])f\partial(-\log p_y) / \partial w_k = (p_k - \mathbb{1}[k = y]) f. What is the gradient when the model is already certain and correct (py=1p_y = 1)? When it is uniform over 3 labels?

    Answer$-\log p_y = -s_y + \log \sum_j e^{s_j}$. Differentiating with respect to $s_k$: $-\mathbb{1}[k=y] + e^{s_k}/\sum_j e^{s_j} = p_k - \mathbb{1}[k=y]$; the chain rule through $s_k = w_k^\top f$ multiplies by $f$. Certain and correct: $p_y = 1$, others 0, so every gradient is 0 — nothing to learn. Uniform: the true label gets $(1/3 - 1) f = -\tfrac{2}{3} f$ (so SGD adds $\tfrac{2}{3}\eta f$ to $w_y$) and each other label $+\tfrac{1}{3} f$ (SGD subtracts $\tfrac{1}{3}\eta f$).
  6. Softmax properties. (a) Show softmax is unchanged by adding a constant cc to every score. (b) Show that as T→0T \to 0, softmax⁡(s/T)\operatorname{softmax}(s/T) puts all mass on arg⁡max⁡s\arg\max s (assume a unique maximum), and as T→∞T \to \infty it becomes uniform.

    Answer(a) $e^{s_k + c} / \sum_j e^{s_j + c} = e^c e^{s_k} / (e^c \sum_j e^{s_j})$. (b) Divide numerator and denominator by $e^{s_\max/T}$: each term becomes $e^{(s_j - s_\max)/T}$, which → 0 for $s_j < s_\max$ and = 1 for the max as $T \to 0$. As $T \to \infty$ every exponent → 0, every term → 1, so each probability → $1/K$.
  7. The neutral class in the notebook. The notebook’s binary perceptron skips neutral examples during training. Suppose instead it trained on them with the same update rule w += y * f. What would happen, and why?

    AnswerFor $y = 0$ the update adds $0 \cdot f = 0$: nothing is learned from neutral examples, but every neutral example counts as a mistake unless the score is exactly 0. So including them changes nothing. The binary model has no parameter that can push a score toward exactly 0. Neutral needs its own label score, i.e. a multi-class model.
  8. Counting the output space. A model generates replies of exactly 50 tokens from a 32,000-token vocabulary. How many decimal digits does the number of possible replies have? If a computer could evaluate 101810^{18} scores per second, how long would it take to compute the softmax denominator? How many softmax terms does an autoregressive factorization need per reply?

    Answer$32000^{50} = 10^{50 \log_{10} 32000} = 10^{225.3}$, a 226-digit number. At $10^{18}$/s: $10^{207}$ seconds ≈ $10^{200}$ years (the universe is ~$1.4 \times 10^{10}$ years old). Autoregressively: 50 softmaxes of 32,000 terms each, $1.6 \times 10^6$ terms.
  9. Data budget. Using demo 03’s learning curve, estimate how many labelled reviews are worth one rule writer’s afternoon (v2 lexicon) and one rule writer’s week (v5, all rules). Then name two situations in which you would still write rules or a prompt rather than collect labels.

    AnswerAbout 200 labels beat v2 (60.9% vs 56.3%); about 2,000 beat v5 (80.9% vs 78.2%; 1,000 gives 76.0%). Rules/prompts still make sense when (a) there is no labelled data and you need something today (a zero-shot prompt is exactly this); (b) the knowledge is precise and rare in data — a legal requirement, a safety filter for a specific phrase, a format constraint; (c) as features or constraints *inside* a learned system (the hand-made `NOT_` features of §4.7).
  10. Label vs reward. In demo 05 Part D, each label carries log⁡23≈1.58\log_2 3 \approx 1.58 bits about the correct action. How much does one reward carry, at most? Why does the reward-only learner sit at the majority action for thousands of steps before improving?

AnswerA 0/1 reward carries at most 1 bit, and less when its outcome is predictable. After a wrong guess it says only "not this one": the correct action is still one of the other two. Early on, the policy drifts toward the most frequently rewarded action (skip = the majority label, 40.8%), samples the others less and less, and so learns little about when they are better. Only when the review-specific weights accumulate enough evidence does it break out — and when that happens depends on the random seed (59–85% at 32,000 steps).
  • Assignment 1 — Build your own LLaMa (released after Lecture 5). Today’s recipe is its outline. The model is a Transformer (Lectures 2–5), learning is the cross-entropy loss of §4.6 applied to every next token, and inference is the sampling of §5.3–5.4, one token at a time. These notes do not provide assignment code.
  • Assignment 2 — End-to-end NLP system building. The workflow of §§2–4 — define xx and yy, collect data, split train/dev/test, start from a baseline (always report the majority class), iterate on dev, test once — is the backbone of that assignment.

Further reading

  • K. Cho, Natural Language Understanding with Distributed Representation, arXiv:1511.07916 (2015), ch. 1 — classification as the starting point, and the case for learned representations (course reading).
  • K. Cho, Machine Learning: a Lecture Note, arXiv:2505.03861 (2025), ch. 1 — machine learning framed through energy (score) functions, learning and inference (course reading).
  • Y. LeCun, S. Chopra, R. Hadsell, M. Ranzato, F. J. Huang, “A Tutorial on Energy-Based Learning”, in Predicting Structured Data, MIT Press, 2006 — the energy view of §4.1.
  • F. Rosenblatt, “The Perceptron: A Probabilistic Model for Information Storage and Organization in the Brain”, Psychological Review 65(6), 1958; A. B. J. Novikoff, “On Convergence Proofs on Perceptrons”, 1962 — the perceptron and its mistake bound.
  • Y. Freund and R. E. Schapire, “Large Margin Classification Using the Perceptron Algorithm”, Machine Learning 37(3), 1999 — voted/averaged perceptron.
  • M. Collins, “Discriminative Training Methods for Hidden Markov Models: Theory and Experiments with Perceptron Algorithms”, EMNLP 2002 — the structured perceptron.
  • B. Pang, L. Lee, S. Vaithyanathan, “Thumbs up? Sentiment Classification using Machine Learning Techniques”, EMNLP 2002 — learned bag-of-words sentiment classifiers vs human-written word lists, and negation tagging.
  • R. Socher et al., “Recursive Deep Models for Semantic Compositionality Over a Sentiment Treebank”, EMNLP 2013 — the SST dataset, built precisely to study negation and contrast.
  • D. Jurafsky and J. H. Martin, Speech and Language Processing (3rd ed. draft), chapters on Naive Bayes and logistic regression — a gentle textbook treatment of §4.
  • R. J. Williams, “Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning”, Machine Learning 8, 1992 — REINFORCE (§5.5; Lecture 16).

Preview of Lecture 2 — Learned representations

Today’s model gave every word an independent weight, so “luminous” learned nothing from “brilliant”, and a word never seen in training was invisible. Next we replace one-hot words with dense vectors (embeddings) learned from how words are used: two words that appear in similar contexts get similar vectors. Along the way we ask what a “word” even is. We look at tokenization: words vs characters vs byte-pair encoding, the scheme every modern LLM uses. Then we build neural classifiers, in which the features themselves are learned, and the algorithm that makes this possible: backpropagation. We will rerun today’s Cinema World failure cases — rare words, word forms, other languages — to see which ones learned representations fix, and which ones still need the architectures of Lectures 4–5.


术语表 (Glossary, English → 中文)

English中文
natural language processing (NLP)自然语言处理
representation / learned representation表示 / 学习得到的表示
generation生成
agent / action / policy智能体 / 动作 / 策略
ambiguity / variability / sparsity歧义 / 多样性 / 稀疏性
compositionality组合性
figurative language / idiom / metaphor比喻性语言 / 习语 / 隐喻
Zipf’s law / long tail齐普夫定律 / 长尾
text classification / sentiment analysis文本分类 / 情感分析
machine translation / image captioning机器翻译 / 图像描述
retrieval / ranking检索 / 排序
structured prediction结构化预测
rule-based system / lexicon / keyword基于规则的系统 / 词典 / 关键词
prompt / prompting提示词 / 提示
supervised learning / reinforcement learning监督学习 / 强化学习
reward / reward function / environment奖励 / 奖励函数 / 环境
training set / development (validation) set / test set训练集 / 开发(验证)集 / 测试集
spot-check抽查
label / gold label / label noise / annotator标签 / 真实标签 / 标签噪声 / 标注者
majority-class baseline多数类基线
feature / feature vector / feature extractor特征 / 特征向量 / 特征提取器
sparse / dense vector稀疏 / 稠密向量
weight / bias / parameter权重 / 偏置 / 参数
score / scoring function / energy得分 / 打分函数 / 能量
model / parameterization模型 / 参数化
learning / inference学习 / 推断
argmax / decision rule取最大者 / 决策规则
bag of words (BoW) / one-hot vector / vocabulary词袋模型 / 独热向量 / 词表
unigram / bigram一元词 / 二元词组
perceptron / averaged perceptron / structured perceptron感知机 / 平均感知机 / 结构化感知机
linearly separable / margin线性可分 / 间隔
epoch / shuffle轮次 / 打乱顺序
loss function / objective损失函数 / 目标函数
logistic regression (multinomial)(多项)逻辑回归
softmax / temperature软最大化(归一化指数函数) / 温度
cross-entropy / negative log-likelihood / log loss交叉熵 / 负对数似然 / 对数损失
gradient / stochastic gradient descent (SGD)梯度 / 随机梯度下降
learning rate / step-size schedule / decay学习率 / 步长调度 / 衰减
regularization (L2)(L2)正则化
overfitting / memorization过拟合 / 记忆
calibration / confidence校准 / 置信度
spurious correlation / spurious cue虚假相关 / 虚假线索
error analysis / feature contribution错误分析 / 特征贡献
negation / negation scope否定 / 否定作用域
contrast / clause / concessive clause转折 / 分句 / 让步从句
morphology / inflection / conjugation形态学 / 屈折变化 / 动词变位
stemming / lemmatization / root form词干提取 / 词形还原 / 词根形式
minimal pair最小对立对
interaction (between features) / XOR(特征间的)交互 / 异或
feature engineering特征工程
distributional hypothesis分布假说
embedding / neural network嵌入 / 神经网络
probabilistic model / distribution概率模型 / 分布
sampling / argmax decoding采样 / 取最大解码
language model / autoregressive model / factorization语言模型 / 自回归模型 / 分解
decoding解码
contextual bandit上下文老虎机
REINFORCE / baseline / varianceREINFORCE 算法 / 基线 / 方差
exploration / credit assignment探索 / 信用分配
synthetic dataset / toy world合成数据集 / 玩具世界
← 返回课程目录