{"ed3bookaug20_2024.pdf": "Speech and Language Processing\nAn Introduction to Natural Language Processing,\nComputational Linguistics, and Speech Recognition\nwith Language Models\nThird Edition draft\nDaniel Jurafsky\nStanford University\nJames H. Martin\nUniversity of Colorado at Boulder\nCopyright \u00a92024. All rights reserved.\nDraft of August 20, 2024. Comments and typos welcome! Summary of Contents\nI Fundamental Algorithms for NLP 1\n1 Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3\n2 Regular Expressions, Tokenization, Edit Distance . . . . . . . . . . . . . . . 4\n3 N-gram Language Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32\n4 Naive Bayes, Text Classi\ufb01cation, and Sentiment . . . . . . . . . . . . . . . . . 56\n5 Logistic Regression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77\n6 Vector Semantics and Embeddings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101\n7 Neural Networks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132\n8 RNNs and LSTMs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158\n9 The Transformer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184\n10 Large Language Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203\n11 Masked Language Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223\n12 Model Alignment, Prompting, and In-Context Learning . . . . . . . . . 242\nII NLP Applications 261\n13 Machine Translation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263\n14 Question Answering, Information Retrieval, and RAG . . . . . . . . . . 289\n15 Chatbots & Dialogue Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309\n16 Automatic Speech Recognition and Text-to-Speech . . . . . . . . . . . . . . 331\nIII Annotating Linguistic Structure 359\n17 Sequence Labeling for Parts of Speech and Named Entities . . . . . . 362\n18 Context-Free Grammars and Constituency Parsing . . . . . . . . . . . . . 387\n19 Dependency Parsing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411\n20 Information Extraction: Relations, Events, and Time. . . . . . . . . . . . 435\n21 Semantic Role Labeling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461\n22 Lexicons for Sentiment, Affect, and Connotation . . . . . . . . . . . . . . . . 481\n23 Coreference Resolution and Entity Linking . . . . . . . . . . . . . . . . . . . . . 501\n24 Discourse Coherence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531\nBibliography. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553\nSubject Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585\n2 Contents\nI Fundamental Algorithms for NLP 1\n1 Introduction 3\n2 Regular Expressions, Tokenization, Edit Distance 4\n2.1 Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . 5\n2.2 Words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13\n2.3 Corpora . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15\n2.4 Simple Unix Tools for Word Tokenization . . . . . . . . . . . . . 17\n2.5 Word and Subword Tokenization . . . . . . . . . . . . . . . . . . 18\n2.6 Word Normalization, Lemmatization and Stemming . . . . . . . . 23\n2.7 Sentence Segmentation . . . . . . . . . . . . . . . . . . . . . . . 25\n2.8 Minimum Edit Distance . . . . . . . . . . . . . . . . . . . . . . . 25\n2.9 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29\nBibliographical and Historical Notes . . . . . . . . . . . . . . . . . . . . 30\nExercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31\n3 N-gram Language Models 32\n3.1 N-Grams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33\n3.2 Evaluating Language Models: Training and Test Sets . . . . . . . 38\n3.3 Evaluating Language Models: Perplexity . . . . . . . . . . . . . . 39\n3.4 Sampling sentences from a language model . . . . . . . . . . . . . 42\n3.5 Generalizing vs. over\ufb01tting the training set . . . . . . . . . . . . . 43\n3.6 Smoothing, Interpolation, and Backoff . . . . . . . . . . . . . . . 45\n3.7 Advanced: Perplexity\u2019s Relation to Entropy . . . . . . . . . . . . 49\n3.8 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52\nBibliographical and Historical Notes . . . . . . . . . . . . . . . . . . . . 52\nExercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54\n4 Naive Bayes, Text Classi\ufb01cation, and Sentiment 56\n4.1 Naive Bayes Classi\ufb01ers . . . . . . . . . . . . . . . . . . . . . . . 57\n4.2 Training the Naive Bayes Classi\ufb01er . . . . . . . . . . . . . . . . . 60\n4.3 Worked example . . . . . . . . . . . . . . . . . . . . . . . . . . . 61\n4.4 Optimizing for Sentiment Analysis . . . . . . . . . . . . . . . . . 62\n4.5 Naive Bayes for other text classi\ufb01cation tasks . . . . . . . . . . . 64\n4.6 Naive Bayes as a Language Model . . . . . . . . . . . . . . . . . 65\n4.7 Evaluation: Precision, Recall, F-measure . . . . . . . . . . . . . . 66\n4.8 Test sets and Cross-validation . . . . . . . . . . . . . . . . . . . . 69\n4.9 Statistical Signi\ufb01cance Testing . . . . . . . . . . . . . . . . . . . 70\n4.10 Avoiding Harms in Classi\ufb01cation . . . . . . . . . . . . . . . . . . 73\n4.11 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74\nBibliographical and Historical Notes . . . . . . . . . . . . . . . . . . . . 75\nExercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76\n5 Logistic Regression 77\n5.1 The sigmoid function . . . . . . . . . . . . . . . . . . . . . . . . 78\n5.2 Classi\ufb01cation with Logistic Regression . . . . . . . . . . . . . . . 80\n5.3 Multinomial logistic regression . . . . . . . . . . . . . . . . . . . 84\n5.4 Learning in Logistic Regression . . . . . . . . . . . . . . . . . . . 87\n3 4CONTENTS\n5.5 The cross-entropy loss function . . . . . . . . . . . . . . . . . . . 88\n5.6 Gradient Descent . . . . . . . . . . . . . . . . . . . . . . . . . . 89\n5.7 Regularization . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95\n5.8 Learning in Multinomial Logistic Regression . . . . . . . . . . . . 96\n5.9 Interpreting models . . . . . . . . . . . . . . . . . . . . . . . . . 98\n5.10 Advanced: Deriving the Gradient Equation . . . . . . . . . . . . . 98\n5.11 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99\nBibliographical and Historical Notes . . . . . . . . . . . . . . . . . . . . 100\nExercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100\n6 Vector Semantics and Embeddings 101\n6.1 Lexical Semantics . . . . . . . . . . . . . . . . . . . . . . . . . . 102\n6.2 Vector Semantics . . . . . . . . . . . . . . . . . . . . . . . . . . 105\n6.3 Words and Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . 106\n6.4 Cosine for measuring similarity . . . . . . . . . . . . . . . . . . . 110\n6.5 TF-IDF: Weighing terms in the vector . . . . . . . . . . . . . . . 111\n6.6 Pointwise Mutual Information (PMI) . . . . . . . . . . . . . . . . 114\n6.7 Applications of the tf-idf or PPMI vector models . . . . . . . . . . 116\n6.8 Word2vec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117\n6.9 Visualizing Embeddings . . . . . . . . . . . . . . . . . . . . . . . 123\n6.10 Semantic properties of embeddings . . . . . . . . . . . . . . . . . 124\n6.11 Bias and Embeddings . . . . . . . . . . . . . . . . . . . . . . . . 126\n6.12 Evaluating Vector Models . . . . . . . . . . . . . . . . . . . . . . 127\n6.13 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128\nBibliographical and Historical Notes . . . . . . . . . . . . . . . . . . . . 129\nExercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131\n7 Neural Networks 132\n7.1 Units . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133\n7.2 The XOR problem . . . . . . . . . . . . . . . . . . . . . . . . . . 135\n7.3 Feedforward Neural Networks . . . . . . . . . . . . . . . . . . . . 138\n7.4 Feedforward networks for NLP: Classi\ufb01cation . . . . . . . . . . . 142\n7.5 Training Neural Nets . . . . . . . . . . . . . . . . . . . . . . . . 145\n7.6 Feedforward Neural Language Modeling . . . . . . . . . . . . . . 152\n7.7 Training the neural language model . . . . . . . . . . . . . . . . . 155\n7.8 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156\nBibliographical and Historical Notes . . . . . . . . . . . . . . . . . . . . 157\n8 RNNs and LSTMs 158\n8.1 Recurrent Neural Networks . . . . . . . . . . . . . . . . . . . . . 158\n8.2 RNNs as Language Models . . . . . . . . . . . . . . . . . . . . . 162\n8.3 RNNs for other NLP tasks . . . . . . . . . . . . . . . . . . . . . . 165\n8.4 Stacked and Bidirectional RNN architectures . . . . . . . . . . . . 168\n8.5 The LSTM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170\n8.6 Summary: Common RNN NLP Architectures . . . . . . . . . . . 174\n8.7 The Encoder-Decoder Model with RNNs . . . . . . . . . . . . . . 174\n8.8 Attention . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179\n8.9 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181\nBibliographical and Historical Notes . . . . . . . . . . . . . . . . . . . . 182\n9 The Transformer 184\n9.1 Attention . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 CONTENTS 5\n9.2 Transformer Blocks . . . . . . . . . . . . . . . . . . . . . . . . . 190\n9.3 Parallelizing computation using a single matrix X. . . . . . . . . 193\n9.4 The input: embeddings for token and position . . . . . . . . . . . 196\n9.5 The Language Modeling Head . . . . . . . . . . . . . . . . . . . 198\n9.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201\nBibliographical and Historical Notes . . . . . . . . . . . . . . . . . . . . 201\n10 Large Language Models 203\n10.1 Large Language Models with Transformers . . . . . . . . . . . . . 204\n10.2 Sampling for LLM Generation . . . . . . . . . . . . . . . . . . . 207\n10.3 Pretraining Large Language Models . . . . . . . . . . . . . . . . 210\n10.4 Evaluating Large Language Models . . . . . . . . . . . . . . . . . 214\n10.5 Dealing with Scale . . . . . . . . . . . . . . . . . . . . . . . . . . 216\n10.6 Potential Harms from Language Models . . . . . . . . . . . . . . 219\n10.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220\nBibliographical and Historical Notes . . . . . . . . . . . . . . . . . . . . 220\n11 Masked Language Models 223\n11.1 Bidirectional Transformer Encoders . . . . . . . . . . . . . . . . . 223\n11.2 Training Bidirectional Encoders . . . . . . . . . . . . . . . . . . . 226\n11.3 Contextual Embeddings . . . . . . . . . . . . . . . . . . . . . . . 230\n11.4 Fine-Tuning for Classi\ufb01cation . . . . . . . . . . . . . . . . . . . . 234\n11.5 Fine-Tuning for Sequence Labelling: Named Entity Recognition . 237\n11.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240\nBibliographical and Historical Notes . . . . . . . . . . . . . . . . . . . . 241\n12 Model Alignment, Prompting, and In-Context Learning 242\n12.1 Prompting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243\n12.2 Post-training and Model Alignment . . . . . . . . . . . . . . . . . 248\n12.3 Model Alignment: Instruction Tuning . . . . . . . . . . . . . . . . 249\n12.4 Chain-of-Thought Prompting . . . . . . . . . . . . . . . . . . . . 254\n12.5 Automatic Prompt Optimization . . . . . . . . . . . . . . . . . . . 255\n12.6 Evaluating Prompted Language Models . . . . . . . . . . . . . . . 258\n12.7 Model Alignment with Human Preferences: RLHF and DPO . . . 259\n12.8 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259\nBibliographical and Historical Notes . . . . . . . . . . . . . . . . . . . . 259\nII NLP Applications 261\n13 Machine Translation 263\n13.1 Language Divergences and Typology . . . . . . . . . . . . . . . . 264\n13.2 Machine Translation using Encoder-Decoder . . . . . . . . . . . . 268\n13.3 Details of the Encoder-Decoder Model . . . . . . . . . . . . . . . 272\n13.4 Decoding in MT: Beam Search . . . . . . . . . . . . . . . . . . . 274\n13.5 Translating in low-resource situations . . . . . . . . . . . . . . . . 278\n13.6 MT Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280\n13.7 Bias and Ethical Issues . . . . . . . . . . . . . . . . . . . . . . . 284\n13.8 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285\nBibliographical and Historical Notes . . . . . . . . . . . . . . . . . . . . 286\nExercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288\n14 Question Answering, Information Retrieval, and RAG 289 6CONTENTS\n14.1 Information Retrieval . . . . . . . . . . . . . . . . . . . . . . . . 290\n14.2 Information Retrieval with Dense Vectors . . . . . . . . . . . . . . 298\n14.3 Answering Questions with RAG . . . . . . . . . . . . . . . . . . 301\n14.4 Evaluating Question Answering . . . . . . . . . . . . . . . . . . . 304\n14.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306\nBibliographical and Historical Notes . . . . . . . . . . . . . . . . . . . . 306\nExercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308\n15 Chatbots & Dialogue Systems 309\n15.1 Properties of Human Conversation . . . . . . . . . . . . . . . . . 311\n15.2 Frame-Based Dialogue Systems . . . . . . . . . . . . . . . . . . . 314\n15.3 Dialogue Acts and Dialogue State . . . . . . . . . . . . . . . . . . 317\n15.4 Chatbots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321\n15.5 Dialogue System Design . . . . . . . . . . . . . . . . . . . . . . . 325\n15.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327\nBibliographical and Historical Notes . . . . . . . . . . . . . . . . . . . . 328\nExercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330\n16 Automatic Speech Recognition and Text-to-Speech 331\n16.1 The Automatic Speech Recognition Task . . . . . . . . . . . . . . 332\n16.2 Feature Extraction for ASR: Log Mel Spectrum . . . . . . . . . . 334\n16.3 Speech Recognition Architecture . . . . . . . . . . . . . . . . . . 339\n16.4 CTC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341\n16.5 ASR Evaluation: Word Error Rate . . . . . . . . . . . . . . . . . 346\n16.6 TTS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348\n16.7 Other Speech Tasks . . . . . . . . . . . . . . . . . . . . . . . . . 353\n16.8 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354\nBibliographical and Historical Notes . . . . . . . . . . . . . . . . . . . . 354\nExercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357\nIII Annotating Linguistic Structure 359\n17 Sequence Labeling for Parts of Speech and Named Entities 362\n17.1 (Mostly) English Word Classes . . . . . . . . . . . . . . . . . . . 363\n17.2 Part-of-Speech Tagging . . . . . . . . . . . . . . . . . . . . . . . 365\n17.3 Named Entities and Named Entity Tagging . . . . . . . . . . . . . 367\n17.4 HMM Part-of-Speech Tagging . . . . . . . . . . . . . . . . . . . 369\n17.5 Conditional Random Fields (CRFs) . . . . . . . . . . . . . . . . . 376\n17.6 Evaluation of Named Entity Recognition . . . . . . . . . . . . . . 381\n17.7 Further Details . . . . . . . . . . . . . . . . . . . . . . . . . . . 381\n17.8 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383\nBibliographical and Historical Notes . . . . . . . . . . . . . . . . . . . . 384\nExercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385\n18 Context-Free Grammars and Constituency Parsing 387\n18.1 Constituency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388\n18.2 Context-Free Grammars . . . . . . . . . . . . . . . . . . . . . . . 388\n18.3 Treebanks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392\n18.4 Grammar Equivalence and Normal Form . . . . . . . . . . . . . . 394\n18.5 Ambiguity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395\n18.6 CKY Parsing: A Dynamic Programming Approach . . . . . . . . 397\n18.7 Span-Based Neural Constituency Parsing . . . . . . . . . . . . . . 403 CONTENTS 7\n18.8 Evaluating Parsers . . . . . . . . . . . . . . . . . . . . . . . . . . 405\n18.9 Heads and Head-Finding . . . . . . . . . . . . . . . . . . . . . . 406\n18.10 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407\nBibliographical and Historical Notes . . . . . . . . . . . . . . . . . . . . 408\nExercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409\n19 Dependency Parsing 411\n19.1 Dependency Relations . . . . . . . . . . . . . . . . . . . . . . . . 412\n19.2 Transition-Based Dependency Parsing . . . . . . . . . . . . . . . 416\n19.3 Graph-Based Dependency Parsing . . . . . . . . . . . . . . . . . 425\n19.4 Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431\n19.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432\nBibliographical and Historical Notes . . . . . . . . . . . . . . . . . . . . 433\nExercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434\n20 Information Extraction: Relations, Events, and Time 435\n20.1 Relation Extraction . . . . . . . . . . . . . . . . . . . . . . . . . 436\n20.2 Relation Extraction Algorithms . . . . . . . . . . . . . . . . . . . 438\n20.3 Extracting Events . . . . . . . . . . . . . . . . . . . . . . . . . . 446\n20.4 Representing Time . . . . . . . . . . . . . . . . . . . . . . . . . . 447\n20.5 Representing Aspect . . . . . . . . . . . . . . . . . . . . . . . . . 450\n20.6 Temporally Annotated Datasets: TimeBank . . . . . . . . . . . . . 451\n20.7 Automatic Temporal Analysis . . . . . . . . . . . . . . . . . . . . 452\n20.8 Template Filling . . . . . . . . . . . . . . . . . . . . . . . . . . . 456\n20.9 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458\nBibliographical and Historical Notes . . . . . . . . . . . . . . . . . . . . 459\nExercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460\n21 Semantic Role Labeling 461\n21.1 Semantic Roles . . . . . . . . . . . . . . . . . . . . . . . . . . . 462\n21.2 Diathesis Alternations . . . . . . . . . . . . . . . . . . . . . . . . 462\n21.3 Semantic Roles: Problems with Thematic Roles . . . . . . . . . . 464\n21.4 The Proposition Bank . . . . . . . . . . . . . . . . . . . . . . . . 465\n21.5 FrameNet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466\n21.6 Semantic Role Labeling . . . . . . . . . . . . . . . . . . . . . . . 468\n21.7 Selectional Restrictions . . . . . . . . . . . . . . . . . . . . . . . 472\n21.8 Primitive Decomposition of Predicates . . . . . . . . . . . . . . . 476\n21.9 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477\nBibliographical and Historical Notes . . . . . . . . . . . . . . . . . . . . 478\nExercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480\n22 Lexicons for Sentiment, Affect, and Connotation 481\n22.1 De\ufb01ning Emotion . . . . . . . . . . . . . . . . . . . . . . . . . . 482\n22.2 Available Sentiment and Affect Lexicons . . . . . . . . . . . . . . 484\n22.3 Creating Affect Lexicons by Human Labeling . . . . . . . . . . . 485\n22.4 Semi-supervised Induction of Affect Lexicons . . . . . . . . . . . 487\n22.5 Supervised Learning of Word Sentiment . . . . . . . . . . . . . . 490\n22.6 Using Lexicons for Sentiment Recognition . . . . . . . . . . . . . 495\n22.7 Using Lexicons for Affect Recognition . . . . . . . . . . . . . . . 496\n22.8 Lexicon-based methods for Entity-Centric Affect . . . . . . . . . . 497\n22.9 Connotation Frames . . . . . . . . . . . . . . . . . . . . . . . . . 497\n22.10 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499 8CONTENTS\nBibliographical and Historical Notes . . . . . . . . . . . . . . . . . . . . 500\nExercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500\n23 Coreference Resolution and Entity Linking 501\n23.1 Coreference Phenomena: Linguistic Background . . . . . . . . . . 504\n23.2 Coreference Tasks and Datasets . . . . . . . . . . . . . . . . . . . 509\n23.3 Mention Detection . . . . . . . . . . . . . . . . . . . . . . . . . . 510\n23.4 Architectures for Coreference Algorithms . . . . . . . . . . . . . 513\n23.5 Classi\ufb01ers using hand-built features . . . . . . . . . . . . . . . . . 515\n23.6 A neural mention-ranking algorithm . . . . . . . . . . . . . . . . 517\n23.7 Entity Linking . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520\n23.8 Evaluation of Coreference Resolution . . . . . . . . . . . . . . . . 524\n23.9 Winograd Schema problems . . . . . . . . . . . . . . . . . . . . . 525\n23.10 Gender Bias in Coreference . . . . . . . . . . . . . . . . . . . . . 526\n23.11 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527\nBibliographical and Historical Notes . . . . . . . . . . . . . . . . . . . . 528\nExercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530\n24 Discourse Coherence 531\n24.1 Coherence Relations . . . . . . . . . . . . . . . . . . . . . . . . . 533\n24.2 Discourse Structure Parsing . . . . . . . . . . . . . . . . . . . . . 536\n24.3 Centering and Entity-Based Coherence . . . . . . . . . . . . . . . 540\n24.4 Representation learning models for local coherence . . . . . . . . 544\n24.5 Global Coherence . . . . . . . . . . . . . . . . . . . . . . . . . . 546\n24.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549\nBibliographical and Historical Notes . . . . . . . . . . . . . . . . . . . . 550\nExercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552\nBibliography 553\nSubject Index 585 Part I\nFUNDAMENTAL ALGORITHMS FOR\nNLP\nIn the \ufb01rst part of the book we introduce the fundamental suite of algorithmic\ntools that make up the modern neural language model that is the heart of end-to-end\nNLP systems. We begin with tokenization and preprocessing, as well as useful algo-\nrithms like computing edit distance, and then proceed to the tasks of classi\ufb01cation,\nlogistic regression, neural networks, proceeding through feedforward networks, re-\ncurrent networks, and then transformers. We\u2019ll also see the role of embeddings as a\nmodel of word meaning. CHAPTER\n1Introduction\nLa derni `ere chose qu\u2019on trouve en faisant un ouvrage est de savoir celle qu\u2019il faut\nmettre la premi `ere.\n[The last thing you \ufb01gure out in writing a book is what to put \ufb01rst.]\nPascal\n3 4CHAPTER 2 \u2022 R EGULAR EXPRESSIONS , TOKENIZATION , EDITDISTANCE\nCHAPTER\n2Regular Expressions, Tok-\nenization, Edit Distance\nUser: I am unhappy.\nELIZA: DO YOU THINK COMING HERE WILL HELP YOU NOT TO BE UNHAPPY\nUser: I need some help, that much seems certain.\nELIZA: WHAT WOULD IT MEAN TO YOU IF YOU GOT SOME HELP\nUser: Perhaps I could learn to get along with my mother.\nELIZA: TELL ME MORE ABOUT YOUR FAMILY\nUser: My mother takes care of me.\nELIZA: WHO ELSE IN YOU FAMILY TAKES CARE OF YOU\nUser: My father.\nELIZA: YOUR FATHER\nUser: You are like my father in some ways.\nWeizenbaum (1966)\nThe dialogue above is from ELIZA , an early natural language processing system ELIZA\nthat could carry on a limited conversation with a user by imitating the responses of\na Rogerian psychotherapist (Weizenbaum, 1966). ELIZA is a surprisingly simple\nprogram that uses pattern matching to recognize phrases like \u201cI need X\u201d and translate\nthem into suitable outputs like \u201cWhat would it mean to you if you got X?\u201d. This\nsimple technique succeeds in this domain because ELIZA doesn\u2019t actually need to\nknow anything to mimic a Rogerian psychotherapist. As Weizenbaum notes, this is\none of the few dialogue genres where listeners can act as if they know nothing of the\nworld. ELIZA\u2019s mimicry of human conversation was remarkably successful: many\npeople who interacted with ELIZA came to believe that it really understood them\nand their problems, many continued to believe in ELIZA\u2019s abilities even after the\nprogram\u2019s operation was explained to them (Weizenbaum, 1976), and even today\nsuch chatbots are a fun diversion. chatbots\nOf course modern conversational agents are much more than a diversion; they\ncan answer questions, book \ufb02ights, or \ufb01nd restaurants, functions for which they rely\non a much more sophisticated understanding of the user\u2019s intent, as we will see in\nChapter 15. Nonetheless, the simple pattern-based methods that powered ELIZA\nand other chatbots play a crucial role in natural language processing.\nWe\u2019ll begin with the most important tool for describing text patterns: the regular\nexpression . Regular expressions can be used to specify strings we might want to\nextract from a document, from transforming \u201cI need X\u201d in ELIZA above, to de\ufb01ning\nstrings like $199 or$24.99 for extracting tables of prices from a document.\nWe\u2019ll then turn to a set of tasks collectively called text normalization , in whichtext\nnormalization\nregular expressions play an important part. Normalizing text means converting it\nto a more convenient, standard form. For example, most of what we are going to\ndo with language relies on \ufb01rst separating out or tokenizing words from running\ntext, the task of tokenization . English words are often separated from each other tokenization\nby whitespace, but whitespace is not always suf\ufb01cient. New York androck \u2019n\u2019 roll\nare sometimes treated as large words despite the fact that they contain spaces, while\nsometimes we\u2019ll need to separate I\u2019minto the two words Iandam. For processing\ntweets or texts we\u2019ll need to tokenize emoticons like:)orhashtags like#nlproc . 2.1 \u2022 R EGULAR EXPRESSIONS 5\nSome languages, like Japanese, don\u2019t have spaces between words, so word tokeniza-\ntion becomes more dif\ufb01cult.\nAnother part of text normalization is lemmatization , the task of determining lemmatization\nthat two words have the same root, despite their surface differences. For example,\nthe words sang ,sung , and sings are forms of the verb sing. The word sing is the\ncommon lemma of these words, and a lemmatizer maps from all of these to sing.\nLemmatization is essential for processing morphologically complex languages like\nArabic. Stemming refers to a simpler version of lemmatization in which we mainly stemming\njust strip suf\ufb01xes from the end of the word. Text normalization also includes sen-\ntence segmentation : breaking up a text into individual sentences, using cues likesentence\nsegmentation\nperiods or exclamation points.\nFinally, we\u2019ll need to compare words and other strings. We\u2019ll introduce a metric\ncalled edit distance that measures how similar two strings are based on the number\nof edits (insertions, deletions, substitutions) it takes to change one string into the\nother. Edit distance is an algorithm with applications throughout language process-\ning, from spelling correction to speech recognition to coreference resolution.\n2.1 Regular Expressions\nOne of the most useful tools for text processing in computer science has been the\nregular expression (often shortened to regex ), a language for specifying text searchregular\nexpression\nstrings. This practical language is used in every computer language, in text process-\ning tools like the Unix tools grep, and in editors like vim or Emacs. Formally, a\nregular expression is an algebraic notation for characterizing a set of strings. Reg-\nular expressions are particularly useful for searching in texts, when we have a pat-\ntern to search for and a corpus of texts to search through. A regular expression corpus\nsearch function will search through the corpus, returning all texts that match the\npattern. The corpus can be a single document or a collection. For example, the\nUnix command-line tool grep takes a regular expression and returns every line of\nthe input document that matches the expression.\nA search can be designed to return every match on a line, if there are more than\none, or just the \ufb01rst match. In the following examples we generally underline the\nexact part of the pattern that matches the regular expression and show only the \ufb01rst\nmatch. We\u2019ll show regular expressions delimited by slashes but note that slashes are\nnotpart of the regular expressions.\nRegular expressions come in many variants. We\u2019ll be describing extended regu-\nlar expressions ; different regular expression parsers may only recognize subsets of\nthese, or treat some expressions slightly differently. Using an online regular expres-\nsion tester is a handy way to test out your expressions and explore these variations.\n2.1.1 Basic Regular Expression Patterns\nThe simplest kind of regular expression is a sequence of simple characters; putting\ncharacters in sequence is called concatenation . To search for woodchuck , we type concatenation\n/woodchuck/ . The expression /Buttercup/ matches any string containing the\nsubstring Buttercup ;grep with that expression would return the line I\u2019m called lit-\ntle Buttercup . The search string can consist of a single character (like /!/) or a\nsequence of characters (like /urgl/ ) (see Fig. 2.1).\nRegular expressions are case sensitive ; lower case /s/ is distinct from upper 6CHAPTER 2 \u2022 R EGULAR EXPRESSIONS , TOKENIZATION , EDITDISTANCE\nRegex Example Patterns Matched\n/woodchucks/ \u201cinteresting links to woodchucks and lemurs\u201d\n/a/ \u201cMary Ann stopped by Mona\u2019s\u201d\n/!/ \u201cYou\u2019ve left the burglar behind again! \u201d said Nori\nFigure 2.1 Some simple regex searches.\ncase/S/ (/s/ matches a lower case sbut not an upper case S). This means that\nthe pattern /woodchucks/ will not match the string Woodchucks . We can solve this\nproblem with the use of the square braces [and]. The string of characters inside the\nbraces speci\ufb01es a disjunction of characters to match. For example, Fig. 2.2 shows\nthat the pattern /[wW]/ matches patterns containing either worW.\nRegex Match Example Patterns\n/[wW]oodchuck/ Woodchuck or woodchuck \u201cWoodchuck \u201d\n/[abc]/ \u2018a\u2019, \u2018b\u2019, or\u2018c\u2019 \u201cIn uomini, in solda ti\u201d\n/[1234567890]/ any digit \u201cplenty of 7 to 5\u201d\nFigure 2.2 The use of the brackets []to specify a disjunction of characters.\nThe regular expression /[1234567890]/ speci\ufb01es any single digit. While such\nclasses of characters as digits or letters are important building blocks in expressions,\nthey can get awkward (e.g., it\u2019s inconvenient to specify\n/[ABCDEFGHIJKLMNOPQRSTUVWXYZ]/ (2.1)\nto mean \u201cany capital letter\u201d). In cases where there is a well-de\ufb01ned sequence asso-\nciated with a set of characters, the brackets can be used with the dash ( -) to specify\nany one character in a range . The pattern /[2-5]/ speci\ufb01es any one of the charac- range\nters2,3,4, or5. The pattern /[b-g]/ speci\ufb01es one of the characters b,c,d,e,f, or\ng. Some other examples are shown in Fig. 2.3.\nRegex Match Example Patterns Matched\n/[A-Z]/ an upper case letter \u201cwe should call it \u2018D renched Blossoms\u2019 \u201d\n/[a-z]/ a lower case letter \u201cmy beans were impatient to be hoed!\u201d\n/[0-9]/ a single digit \u201cChapter 1 : Down the Rabbit Hole\u201d\nFigure 2.3 The use of the brackets []plus the dash -to specify a range.\nThe square braces can also be used to specify what a single character cannot be,\nby use of the caret ^. If the caret ^is the \ufb01rst symbol after the open square brace [,\nthe resulting pattern is negated. For example, the pattern /[^a]/ matches any single\ncharacter (including special characters) except a. This is only true when the caret\nis the \ufb01rst symbol after the open square brace. If it occurs anywhere else, it usually\nstands for a caret; Fig. 2.4 shows some examples.\nRegex Match (single characters) Example Patterns Matched\n/[^A-Z]/ not an upper case letter \u201cOyfn pripetchik\u201d\n/[^Ss]/ neither \u2018S\u2019 nor \u2018s\u2019 \u201cIhave no exquisite reason for\u2019t\u201d\n/[^.]/ not a period \u201cour resident Djinn\u201d\n/[e^]/ either \u2018e\u2019 or \u2018 ^\u2019 \u201clook up \u02c6 now\u201d\n/a^b/ the pattern \u2018 a^b\u2019 \u201clook up a\u02c6 b now\u201d\nFigure 2.4 The caret ^for negation or just to mean ^. See below re: the backslash for escaping the period. 2.1 \u2022 R EGULAR EXPRESSIONS 7\nHow can we talk about optional elements, like an optional sinwoodchuck and\nwoodchucks ? We can\u2019t use the square brackets, because while they allow us to say\n\u201cs or S\u201d, they don\u2019t allow us to say \u201cs or nothing\u201d. For this we use the question mark\n/?/, which means \u201cthe preceding character or nothing\u201d, as shown in Fig. 2.5.\nRegex Match Example Patterns Matched\n/woodchucks?/ woodchuck or woodchucks \u201cwoodchuck \u201d\n/colou?r/ color or colour \u201ccolor \u201d\nFigure 2.5 The question mark ?marks optionality of the previous expression.\nWe can think of the question mark as meaning \u201czero or one instances of the\nprevious character\u201d. That is, it\u2019s a way of specifying how many of something that\nwe want, something that is very important in regular expressions. For example,\nconsider the language of certain sheep, which consists of strings that look like the\nfollowing:\nbaa!\nbaaa!\nbaaaa!\n. . .\nThis language consists of strings with a b, followed by at least two a\u2019s, followed\nby an exclamation point. The set of operators that allows us to say things like \u201csome\nnumber of as\u201d are based on the asterisk or *, commonly called the Kleene * (gen- Kleene *\nerally pronounced \u201ccleany star\u201d). The Kleene star means \u201czero or more occurrences\nof the immediately previous character or regular expression\u201d. So /a*/ means \u201cany\nstring of zero or more as\u201d. This will match aoraaaaaa , but it will also match the\nempty string at the start of Off Minor since the string Off Minor starts with zero a\u2019s.\nSo the regular expression for matching one or more ais/aa*/ , meaning one afol-\nlowed by zero or more as. More complex patterns can also be repeated. So /[ab]*/\nmeans \u201czero or more a\u2019s or b\u2019s\u201d (not \u201czero or more right square braces\u201d). This will\nmatch strings like aaaa orababab orbbbb , as well as the empty string.\nFor specifying multiple digits (useful for \ufb01nding prices) we can extend /[0-9]/ ,\nthe regular expression for a single digit. An integer (a string of digits) is thus\n/[0-9][0-9]*/ . (Why isn\u2019t it just /[0-9]*/ ?)\nSometimes it\u2019s annoying to have to write the regular expression for digits twice,\nso there is a shorter way to specify \u201cat least one\u201d of some character. This is the\nKleene + , which means \u201cone or more occurrences of the immediately preceding Kleene +\ncharacter or regular expression\u201d. Thus, the expression /[0-9]+/ is the normal way\nto specify \u201ca sequence of digits\u201d. There are thus two ways to specify the sheep\nlanguage: /baaa*!/ or/baa+!/ .\nOne very important special character is the period ( /./), awildcard expression\nthat matches any single character ( except a carriage return), as shown in Fig. 2.6.\nRegex Match Example Matches\n/beg.n/ any character between begandn begin , beg\u2019n , begun\nFigure 2.6 The use of the period .to specify any character.\nThe wildcard is often used together with the Kleene star to mean \u201cany string of\ncharacters\u201d. For example, suppose we want to \ufb01nd any line in which a particular\nword, for example, aardvark , appears twice. We can specify this with the regular\nexpression /aardvark.*aardvark/ . 8CHAPTER 2 \u2022 R EGULAR EXPRESSIONS , TOKENIZATION , EDITDISTANCE\nAnchors are special characters that anchor regular expressions to particular places anchors\nin a string. The most common anchors are the caret ^and the dollar sign $. The caret\n^matches the start of a line. The pattern /^The/ matches the word Theonly at the\nstart of a line. Thus, the caret ^has three uses: to match the start of a line, to in-\ndicate a negation inside of square brackets, and just to mean a caret. (What are the\ncontexts that allow grep or Python to know which function a given caret is supposed\nto have?) The dollar sign $matches the end of a line. So the pattern $is a useful\npattern for matching a space at the end of a line, and /^The dog\\.$/ matches a\nline that contains only the phrase The dog. (We have to use the backslash here since\nwe want the .to mean \u201cperiod\u201d and not the wildcard.)\nRegex Match\n^ start of line\n$ end of line\n\\b word boundary\n\\B non-word boundary\nFigure 2.7 Anchors in regular expressions.\nThere are also two other anchors: \\bmatches a word boundary, and \\Bmatches\na non word-boundary. Thus, /\\bthe\\b/ matches the word thebut not the word\nother . A \u201cword\u201d for the purposes of a regular expression is de\ufb01ned based on the\nde\ufb01nition of words in programming languages as a sequence of digits, underscores,\nor letters. Thus /\\b99\\b/ will match the string 99inThere are 99 bottles of beer on\nthe wall (because 99 follows a space) but not 99inThere are 299 bottles of beer on\nthe wall (since 99 follows a number). But it will match 99in$99(since 99follows\na dollar sign ($), which is not a digit, underscore, or letter).\n2.1.2 Disjunction, Grouping, and Precedence\nSuppose we need to search for texts about pets; perhaps we are particularly interested\nin cats and dogs. In such a case, we might want to search for either the string cator\nthe string dog. Since we can\u2019t use the square brackets to search for \u201ccat or dog\u201d (why\ncan\u2019t we say /[catdog]/ ?), we need a new operator, the disjunction operator, also disjunction\ncalled the pipe symbol|. The pattern /cat|dog/ matches either the string cator\nthe string dog.\nSometimes we need to use this disjunction operator in the midst of a larger se-\nquence. For example, suppose I want to search for information about pet \ufb01sh for\nmy cousin David. How can I specify both guppy andguppies ? We cannot simply\nsay/guppy|ies/ , because that would match only the strings guppy andies. This\nis because sequences like guppy take precedence over the disjunction operator |. precedence\nTo make the disjunction operator apply only to a speci\ufb01c pattern, we need to use the\nparenthesis operators (and). Enclosing a pattern in parentheses makes it act like\na single character for the purposes of neighboring operators like the pipe |and the\nKleene*. So the pattern /gupp(y|ies)/ would specify that we meant the disjunc-\ntion only to apply to the suf\ufb01xes yandies.\nThe parenthesis operator (is also useful when we are using counters like the\nKleene*. Unlike the |operator, the Kleene *operator applies by default only to\na single character, not to a whole sequence. Suppose we want to match repeated\ninstances of a string. Perhaps we have a line that has column labels of the form\nColumn 1 Column 2 Column 3 . The expression /Column [0-9]+ */ will not\nmatch any number of columns; instead, it will match a single column followed by 2.1 \u2022 R EGULAR EXPRESSIONS 9\nany number of spaces! The star here applies only to the space that precedes it,\nnot to the whole sequence. With the parentheses, we could write the expression\n/(Column [0-9]+ *)*/ to match the word Column , followed by a number and\noptional spaces, the whole pattern repeated zero or more times.\nThis idea that one operator may take precedence over another, requiring us to\nsometimes use parentheses to specify what we mean, is formalized by the operator\nprecedence hierarchy for regular expressions. The following table gives the orderoperator\nprecedence\nof RE operator precedence, from highest precedence to lowest precedence.\nParenthesis ()\nCounters * + ? {}\nSequences and anchors the ^my end$\nDisjunction |\nThus, because counters have a higher precedence than sequences,\n/the*/ matches theeeee but not thethe . Because sequences have a higher prece-\ndence than disjunction, /the|any/ matches theoranybut not thany ortheny .\nPatterns can be ambiguous in another way. Consider the expression /[a-z]*/\nwhen matching against the text once upon a time . Since/[a-z]*/ matches zero or\nmore letters, this expression could match nothing, or just the \ufb01rst letter o,on,onc,\noronce . In these cases regular expressions always match the largest string they can;\nwe say that patterns are greedy , expanding to cover as much of a string as they can. greedy\nThere are, however, ways to enforce non-greedy matching, using another mean- non-greedy\ning of the ?quali\ufb01er. The operator *?is a Kleene star that matches as little text as *?\npossible. The operator +?is a Kleene plus that matches as little text as possible. +?\n2.1.3 A Simple Example\nSuppose we wanted to write a RE to \ufb01nd cases of the English article the. A simple\n(but incorrect) pattern might be:\n/the/ (2.2)\nOne problem is that this pattern will miss the word when it begins a sentence and\nhence is capitalized (i.e., The). This might lead us to the following pattern:\n/[tT]he/ (2.3)\nBut we will still incorrectly return texts with the embedded in other words (e.g.,\nother ortheology ). So we need to specify that we want instances with a word bound-\nary on both sides:\n/\\b[tT]he\\b/ (2.4)\nSuppose we wanted to do this without the use of /\\b/ . We might want this since\n/\\b/ won\u2019t treat underscores and numbers as word boundaries; but we might want\nto \ufb01nd thein some context where it might also have underlines or numbers nearby\n(the orthe25 ). We need to specify that we want instances in which there are no\nalphabetic letters on either side of the the:\n/[^a-zA-Z][tT]he[^a-zA-Z]/ (2.5)\nBut there is still one more problem with this pattern: it won\u2019t \ufb01nd the word thewhen\nit begins a line. This is because the regular expression [^a-zA-Z] , which we used 10 CHAPTER 2 \u2022 R EGULAR EXPRESSIONS , TOKENIZATION , EDITDISTANCE\nto avoid embedded instances of the, implies that there must be some single (although\nnon-alphabetic) character before the the. We can avoid this by specifying that before\nthethewe require either the beginning-of-line or a non-alphabetic character, and the\nsame at the end of the line:\n/(^|[^a-zA-Z])[tT]he([^a-zA-Z]|$)/ (2.6)\nThe process we just went through was based on \ufb01xing two kinds of errors: false pos-\nitives , strings that we incorrectly matched like other orthere , and false negatives , false positives\nfalse negatives strings that we incorrectly missed, like The. Addressing these two kinds of errors\ncomes up again and again in language processing. Reducing the overall error rate\nfor an application thus involves two antagonistic efforts:\n\u2022 Increasing precision (minimizing false positives)\n\u2022 Increasing recall (minimizing false negatives)\nWe\u2019ll come back to precision and recall with more precise de\ufb01nitions in Chapter 4.\n2.1.4 More Operators\nFigure 2.8 shows some aliases for common ranges, which can be used mainly to\nsave typing. Besides the Kleene * and Kleene + we can also use explicit numbers as\ncounters, by enclosing them in curly brackets. The operator /{3}/ means \u201cexactly\n3 occurrences of the previous character or expression\u201d. So /a\\.{24}z/ will match\nafollowed by 24 dots followed by z(but not afollowed by 23 or 25 dots followed\nby a z).\nRegex Expansion Match First Matches\n\\d [0-9] any digit Party of 5\n\\D [^0-9] any non-digit Blue moon\n\\w [a-zA-Z0-9_] any alphanumeric/underscore Daiyu\n\\W [^\\w] a non-alphanumeric !!!!\n\\s [ \\r\\t\\n\\f] whitespace (space, tab) inConcord\n\\S [^\\s] Non-whitespace in Concord\nFigure 2.8 Aliases for common sets of characters.\nA range of numbers can also be speci\ufb01ed. So /{n,m}/ speci\ufb01es from ntom\noccurrences of the previous char or expression, and /{n,}/ means at least noccur-\nrences of the previous expression. REs for counting are summarized in Fig. 2.9.\nRegex Match\n* zero or more occurrences of the previous char or expression\n+ one or more occurrences of the previous char or expression\n? zero or one occurrence of the previous char or expression\n{n} exactly noccurrences of the previous char or expression\n{n,m} from ntomoccurrences of the previous char or expression\n{n,} at least noccurrences of the previous char or expression\n{,m} up to moccurrences of the previous char or expression\nFigure 2.9 Regular expression operators for counting.\nFinally, certain special characters are referred to by special notation based on the\nbackslash ( \\) (see Fig. 2.10). The most common of these are the newline character newline\n\\nand the tabcharacter\\t. To refer to characters that are special themselves (like\n.,*,[, and\\), precede them with a backslash, (i.e., /\\./ ,/\\*/ ,/\\[/ , and/\\\\/ ). 2.1 \u2022 R EGULAR EXPRESSIONS 11\nRegex Match First Patterns Matched\n\\* an asterisk \u201c*\u201d \u201cK* A*P*L*A*N\u201d\n\\. a period \u201c.\u201d \u201cDr. Livingston, I presume\u201d\n\\? a question mark \u201cWhy don\u2019t they come and lend a hand? \u201d\n\\n a newline\n\\t a tab\nFigure 2.10 Some characters that need to be escaped (via backslash).\n2.1.5 A More Complex Example\nLet\u2019s try out a more signi\ufb01cant example of the power of REs. Suppose our goal is\nhelp a user buy a computer on the Web who wants \u201cat least 6 GHz and 500 GB of\ndisk space for less than $1000\u201d. To do this kind of retrieval, we \ufb01rst need to be\nable to look for expressions like 6 GHz or500 GB or$999.99 . Let\u2019s work out some\nregular expressions for this task.\nFirst, let\u2019s complete our regular expression for prices. Here\u2019s a regular expres-\nsion for a dollar sign followed by a string of digits:\n/$[0-9]+/ (2.7)\nNote that the $character has a different function here than the end-of-line function\nwe discussed earlier. Most regular expression parsers are smart enough to realize\nthat$here doesn\u2019t mean end-of-line. (As a thought experiment, think about how\nregex parsers might \ufb01gure out the function of $from the context.)\nNow we just need to deal with fractions of dollars. We\u2019ll add a decimal point\nand two digits afterwards:\n/$[0-9]+\\.[0-9][0-9]/ (2.8)\nThis pattern only allows $199.99 but not $199 . We need to make the cents optional\nand to make sure we\u2019re at a word boundary:\n/(^|\\W)$[0-9]+(\\.[0-9][0-9])?\\b/ (2.9)\nOne last catch! This pattern allows prices like $199999.99 which would be far too\nexpensive! We need to limit the dollars:\n/(^|\\W)$[0-9]{0,3}(\\.[0-9][0-9])?\\b/ (2.10)\nFurther \ufb01xes (like avoiding matching a dollar sign with no price after it) are left as\nan exercise for the reader.\nHow about disk space? We\u2019ll need to allow for optional fractions again ( 5.5 GB );\nnote the use of ?for making the \ufb01nal soptional, and the use of / */ to mean \u201czero\nor more spaces\u201d since there might always be extra spaces lying around:\n/\\b[0-9]+(\\.[0-9]+)? *(GB|[Gg]igabytes?)\\b/ (2.11)\nModifying this regular expression so that it only matches more than 500 GB is left\nas an exercise for the reader.\n2.1.6 Substitution, Capture Groups, and ELIZA\nAn important use of regular expressions is in substitutions . For example, the substi- substitution 12 CHAPTER 2 \u2022 R EGULAR EXPRESSIONS , TOKENIZATION , EDITDISTANCE\ntution operator s/regexp1/pattern/ used in Python and in Unix commands like\nvimorsedallows a string characterized by a regular expression to be replaced by\nanother string:\ns/colour/color/ (2.12)\nIt is often useful to be able to refer to a particular subpart of the string matching\nthe \ufb01rst pattern. For example, suppose we wanted to put angle brackets around all\nintegers in a text, for example, changing the 35 boxes tothe<35>boxes . We\u2019d\nlike a way to refer to the integer we\u2019ve found so that we can easily add the brackets.\nTo do this, we put parentheses (and)around the \ufb01rst pattern and use the number\noperator\\1in the second pattern to refer back. Here\u2019s how it looks:\ns/([0-9]+)/<\\1>/ (2.13)\nThe parenthesis and number operators can also specify that a certain string or ex-\npression must occur twice in the text. For example, suppose we are looking for the\npattern \u201cthe Xer they were, the Xer they will be\u201d, where we want to constrain the two\nX\u2019s to be the same string. We do this by surrounding the \ufb01rst X with the parenthesis\noperator, and replacing the second X with the number operator \\1, as follows:\n/the (.*)er they were, the \\1er they will be/ (2.14)\nHere the\\1will be replaced by whatever string matched the \ufb01rst item in parentheses.\nSo this will match the bigger they were, the bigger they will be but not the bigger\nthey were, the faster they will be .\nThis use of parentheses to store a pattern in memory is called a capture group . capture group\nEvery time a capture group is used (i.e., parentheses surround a pattern), the re-\nsulting match is stored in a numbered register . If you match two different sets of register\nparentheses, \\2means whatever matched the second capture group. Thus\n/the (.*)er they (.*), the \\1er we \\2/ (2.15)\nwill match the faster they ran, the faster we ran but not the faster they ran, the faster\nwe ate . Similarly, the third capture group is stored in \\3, the fourth is \\4, and so on.\nParentheses thus have a double function in regular expressions; they are used\nto group terms for specifying the order in which operators should apply, and they\nare used to capture something in a register. Occasionally we might want to use\nparentheses for grouping, but don\u2019t want to capture the resulting pattern in a register.\nIn that case we use a non-capturing group , which is speci\ufb01ed by putting the specialnon-capturing\ngroup\ncommands ?:after the open parenthesis, in the form (?: pattern ) .\n/(?:some|a few) (people|cats) like some \\1/ (2.16)\nwill match some cats like some cats but not some cats like some some .\nSubstitutions and capture groups are very useful in implementing simple chat-\nbots like ELIZA (Weizenbaum, 1966). Recall that ELIZA simulates a Rogerian\npsychologist by carrying on conversations like the following:\nUser 1: Men are all alike.\nELIZA 1:IN WHAT WAY\nUser 2: They\u2019re always bugging us about something or other.\nELIZA 2:CAN YOU THINK OF A SPECIFIC EXAMPLE\nUser 3: Well, my boyfriend made me come here.\nELIZA 3:YOUR BOYFRIEND MADE YOU COME HERE\nUser 4: He says I\u2019m depressed much of the time.\nELIZA 4:I AM SORRY TO HEAR YOU ARE DEPRESSED 2.2 \u2022 W ORDS 13\nELIZA works by having a series or cascade of regular expression substitutions\neach of which matches and changes some part of the input lines. After the input\nis uppercased, substitutions change all instances of MYtoYOUR , and I\u2019MtoYOU\nARE, and so on. That way when ELIZA repeats back part of the user utterance, it\nwill seem to be referring correctly to the user. The next set of substitutions matches\nand replaces other patterns in the input. Here are some examples:\ns/.* YOU ARE (depressed|sad) .*/I AM SORRY TO HEAR YOU ARE \\1/\ns/.* YOU ARE (depressed|sad) .*/WHY DO YOU THINK YOU ARE \\1/\ns/.* all .*/IN WHAT WAY/\ns/.* always .*/CAN YOU THINK OF A SPECIFIC EXAMPLE/\nSince multiple substitutions can apply to a given input, substitutions are assigned\na rank and applied in order. Creating patterns is the topic of Exercise 2.3, and we\nreturn to the details of the ELIZA architecture in Chapter 15.\n2.1.7 Lookahead Assertions\nFinally, there will be times when we need to predict the future: look ahead in the\ntext to see if some pattern matches, but not yet advance the pointer we always keep\nto where we are in the text, so that we can then deal with the pattern if it occurs, but\nif it doesn\u2019t we can check for something else instead.\nThese lookahead assertions make use of the (?syntax that we saw in the previ- lookahead\nous section for non-capture groups. The operator (?= pattern) is true ifpattern\noccurs, but is zero-width , i.e. the match pointer doesn\u2019t advance. The operator zero-width\n(?! pattern) only returns true if a pattern does not match, but again is zero-width\nand doesn\u2019t advance the pointer. Negative lookahead is commonly used when we\nare parsing some complex pattern but want to rule out a special case. For example\nsuppose we want to match, at the beginning of a line, any single word that doesn\u2019t\nstart with \u201cV olcano\u201d. We can use negative lookahead to do this:\n/^(?!Volcano)[A-Za-z]+/ (2.17)\n2.2 Words\nBefore we talk about processing words, we need to decide what counts as a word.\nLet\u2019s start by looking at one particular corpus (plural corpora ), a computer-readable corpus\ncorpora collection of text or speech. For example the Brown corpus is a million-word col-\nlection of samples from 500 written English texts from different genres (newspa-\nper, \ufb01ction, non-\ufb01ction, academic, etc.), assembled at Brown University in 1963\u201364\n(Ku\u02c7cera and Francis, 1967). How many words are in the following Brown sentence?\nHe stepped out into the hall, was delighted to encounter\na water brother.\nThis sentence has 13 words if we don\u2019t count punctuation marks as words, 15\nif we count punctuation. Whether we treat period (\u201c .\u201d), comma (\u201c ,\u201d), and so on as\nwords depends on the task. Punctuation is critical for \ufb01nding boundaries of things\n(commas, periods, colons) and for identifying some aspects of meaning (question\nmarks, exclamation marks, quotation marks). For some tasks, like part-of-speech\ntagging or parsing or speech synthesis, we sometimes treat punctuation marks as if\nthey were separate words. 14 CHAPTER 2 \u2022 R EGULAR EXPRESSIONS , TOKENIZATION , EDITDISTANCE\nThe Switchboard corpus of American English telephone conversations between\nstrangers was collected in the early 1990s; it contains 2430 conversations averaging\n6 minutes each, totaling 240 hours of speech and about 3 million words (Godfrey\net al., 1992). Such corpora of spoken language introduce other complications with\nregard to de\ufb01ning words. Let\u2019s look at one utterance from Switchboard; an utter-\nance is the spoken correlate of a sentence: utterance\nI do uh main- mainly business data processing\nThis utterance has two kinds of dis\ufb02uencies . The broken-off word main- is dis\ufb02uency\ncalled a fragment . Words like uhandumare called \ufb01llers or\ufb01lled pauses . Should fragment\n\ufb01lled pause we consider these to be words? Again, it depends on the application. If we are\nbuilding a speech transcription system, we might want to eventually strip out the\ndis\ufb02uencies.\nBut we also sometimes keep dis\ufb02uencies around. Dis\ufb02uencies like uhorum\nare actually helpful in speech recognition in predicting the upcoming word, because\nthey may signal that the speaker is restarting the clause or idea, and so for speech\nrecognition they are treated as regular words. Because different people use differ-\nent dis\ufb02uencies they can also be a cue to speaker identi\ufb01cation. In fact Clark and\nFox Tree (2002) showed that uhandumhave different meanings. What do you think\nthey are?\nPerhaps most important, in thinking about what is a word, we need to distinguish\ntwo ways of talking about words that will be useful throughout the book. Word types word type\nare the number of distinct words in a corpus; if the set of words in the vocabulary is\nV, the number of types is the vocabulary size jVj. Word instances are the total num- word instance\nberNof running words.1If we ignore punctuation, the following Brown sentence\nhas 14 types and 16 instances:\nThey picnicked by the pool, then lay back on the grass and\nlooked at the stars.\nWe still have decisions to make! For example, should we consider a capitalized\nstring (like They ) and one that is uncapitalized (like they) to be the same word type?\nThe answer is that it depends on the task! They andthey might be lumped together\nas the same type in some tasks, like speech recognition, where we care more about\nthe sequence of words and less about the formatting, while for other tasks, such\nas deciding whether a particular word is a name of a person or location (named-\nentity tagging), capitalization is a useful feature and is retained. Sometimes we keep\naround two versions of a particular NLP model, one with capitalization and one\nwithout capitalization.\nCorpus Types =jVjInstances = N\nShakespeare 31 thousand 884 thousand\nBrown corpus 38 thousand 1 million\nSwitchboard telephone conversations 20 thousand 2.4 million\nCOCA 2 million 440 million\nGoogle n-grams 13 million 1 trillion\nFigure 2.11 Rough numbers of wordform types and instances for some English language\ncorpora. The largest, the Google n-grams corpus, contains 13 million types, but this count\nonly includes types appearing 40 or more times, so the true number would be much larger.\n1In earlier tradition, and occasionally still, you might see word instances referred to as word tokens , but\nwe now try to reserve the word token instead to mean the output of subword tokenization algorithms. 2.3 \u2022 C ORPORA 15\nHow many words are there in English? When we speak about the number of\nwords in the language, we are generally referring to word types. Fig. 2.11 shows\nthe rough numbers of types and instances computed from some English corpora.\nThe larger the corpora we look at, the more word types we \ufb01nd, and in fact this\nrelationship between the number of types jVjand number of instances Nis called\nHerdan\u2019s Law (Herdan, 1960) or Heaps\u2019 Law (Heaps, 1978) after its discoverers Herdan\u2019s Law\nHeaps\u2019 Law (in linguistics and information retrieval respectively). It is shown in Eq. 2.18, where\nkandbare positive constants, and 0 >> text = 'That U.S.A. poster-print costs $12.40...'\n>>> pattern = r'''(?x) # set flag to allow verbose regexps\n... (?:[A-Z]\\.)+ # abbreviations, e.g. U.S.A.\n... | \\w+(?:-\\w+)* # words with optional internal hyphens\n... | \\$?\\d+(?:\\.\\d+)?%? # currency, percentages, e.g. $12.40, 82%\n... | \\.\\.\\. # ellipsis\n... | [][.,;\"'?():_`-] # these are separate tokens; includes ], [\n... '''\n>>> nltk.regexp_tokenize(text, pattern)\n['That', 'U.S.A.', 'poster-print', 'costs', '$12.40', '...']\nFigure 2.12 A Python trace of regular expression tokenization in the NLTK Python-based\nnatural language processing toolkit (Bird et al., 2009), commented for readability; the (?x)\nverbose \ufb02ag tells Python to strip comments and whitespace. Figure from Chapter 3 of Bird\net al. (2009).\nCarefully designed deterministic algorithms can deal with the ambiguities that\narise, such as the fact that the apostrophe needs to be tokenized differently when used\nas a genitive marker (as in the book\u2019s cover ), a quotative as in \u2018The other class\u2019, she\nsaid, or in clitics like they\u2019re .\nWord tokenization is more complex in languages like written Chinese, Japanese,\nand Thai, which do not use spaces to mark potential word-boundaries. In Chinese,\nfor example, words are composed of characters (called hanzi in Chinese). Each hanzi\ncharacter generally represents a single unit of meaning (called a morpheme ) and is\npronounceable as a single syllable. Words are about 2.4 characters long on average.\nBut deciding what counts as a word in Chinese is complex. For example, consider\nthe following sentence:\n(2.21)\u59da\u660e\u8fdb\u5165\u603b\u51b3\u8d5b y\u00b4ao m \u00b4\u0131ng j`\u0131n r`u z\u02c7ong ju \u00b4e s`ai\n\u201cYao Ming reaches the \ufb01nals\u201d\nAs Chen et al. (2017b) point out, this could be treated as 3 words (\u2018Chinese Tree-\nbank\u2019 segmentation):\n(2.22)\u59da\u660e\nYaoMing\u8fdb\u5165\nreaches\u603b\u51b3\u8d5b\n\ufb01nals\nor as 5 words (\u2018Peking University\u2019 segmentation):\n(2.23)\u59da\nYao\u660e\nMing\u8fdb\u5165\nreaches\u603b\noverall\u51b3\u8d5b\n\ufb01nals\nFinally, it is possible in Chinese simply to ignore words altogether and use characters\nas the basic elements, treating the sentence as a series of 7 characters:\n(2.24)\u59da\nYao\u660e\nMing\u8fdb\nenter\u5165\nenter\u603b\noverall\u51b3\ndecision\u8d5b\ngame\nIn fact, for most Chinese NLP tasks it turns out to work better to take characters\nrather than words as input, since characters are at a reasonable semantic level for\nmost applications, and since most word standards, by contrast, result in a huge vo-\ncabulary with large numbers of very rare words (Li et al., 2019b).\nHowever, for Japanese and Thai the character is too small a unit, and so algo-\nrithms for word segmentation are required. These can also be useful for Chineseword\nsegmentation 2.5 \u2022 W ORD AND SUBWORD TOKENIZATION 21\nin the rare situations where word rather than character boundaries are required. For\nthese situations we can use the subword tokenization algorithms introduced in the\nnext section.\n2.5.2 Byte-Pair Encoding: A Bottom-up Tokenization Algorithm\nThere is a third option to tokenizing text, one that is most commonly used by large\nlanguage models. Instead of de\ufb01ning tokens as words (whether delimited by spaces\nor more complex algorithms), or as characters (as in Chinese), we can use our data to\nautomatically tell us what the tokens should be. This is especially useful in dealing\nwith unknown words, an important problem in language processing. As we will\nsee in the next chapter, NLP algorithms often learn some facts about language from\none corpus (a training corpus) and then use these facts to make decisions about a\nseparate testcorpus and its language. Thus if our training corpus contains, say the\nwords low,new,newer , but not lower , then if the word lower appears in our test\ncorpus, our system will not know what to do with it.\nTo deal with this unknown word problem, modern tokenizers automatically in-\nduce sets of tokens that include tokens smaller than words, called subwords . Sub- subwords\nwords can be arbitrary substrings, or they can be meaning-bearing units like the\nmorphemes -estor-er. (A morpheme is the smallest meaning-bearing unit of a lan-\nguage; for example the word unwashable has the morphemes un-,wash , and -able .)\nIn modern tokenization schemes, most tokens are words, but some tokens are fre-\nquently occurring morphemes or other subwords like -er. Every unseen word like\nlower can thus be represented by some sequence of known subword units, such as\nlowander, or even as a sequence of individual letters if necessary.\nMost tokenization schemes have two parts: a token learner , and a token seg-\nmenter . The token learner takes a raw training corpus (sometimes roughly pre-\nseparated into words, for example by whitespace) and induces a vocabulary, a set\nof tokens. The token segmenter takes a raw test sentence and segments it into the\ntokens in the vocabulary. Two algorithms are widely used: byte-pair encoding\n(Sennrich et al., 2016), and unigram language modeling (Kudo, 2018), There is\nalso a SentencePiece library that includes implementations of both of these (Kudo\nand Richardson, 2018a), and people often use the name SentencePiece to simply\nmean unigram language modeling tokenization.\nIn this section we introduce the simplest of the three, the byte-pair encoding or\nBPE algorithm (Sennrich et al., 2016); see Fig. 2.13. The BPE token learner begins BPE\nwith a vocabulary that is just the set of all individual characters. It then examines the\ntraining corpus, chooses the two symbols that are most frequently adjacent (say \u2018A\u2019,\n\u2018B\u2019), adds a new merged symbol \u2018AB\u2019 to the vocabulary, and replaces every adjacent\n\u2019A\u2019 \u2019B\u2019 in the corpus with the new \u2018AB\u2019. It continues to count and merge, creating\nnew longer and longer character strings, until kmerges have been done creating\nknovel tokens; kis thus a parameter of the algorithm. The resulting vocabulary\nconsists of the original set of characters plus knew symbols.\nThe algorithm is usually run inside words (not merging across word boundaries),\nso the input corpus is \ufb01rst white-space-separated to give a set of strings, each corre-\nsponding to the characters of a word, plus a special end-of-word symbol , and its\ncounts. Let\u2019s see its operation on the following tiny input corpus of 18 word tokens\nwith counts for each word (the word lowappears 5 times, the word newer 6 times,\nand so on), which would have a starting vocabulary of 11 letters: 22 CHAPTER 2 \u2022 R EGULAR EXPRESSIONS , TOKENIZATION , EDITDISTANCE\ncorpus vocabulary\n5l o w , d, e, i, l, n, o, r, s, t, w\n2l o w e s t\n6n e w e r\n3w i d e r\n2n e w\nThe BPE algorithm \ufb01rst counts all pairs of adjacent symbols: the most frequent\nis the pair e rbecause it occurs in newer (frequency of 6) and wider (frequency of\n3) for a total of 9 occurrences.2We then merge these symbols, treating eras one\nsymbol, and count again:\ncorpus vocabulary\n5l o w , d, e, i, l, n, o, r, s, t, w, er\n2l o w e s t\n6n e w er\n3w i d er\n2n e w\nNow the most frequent pair is er , which we merge; our system has learned\nthat there should be a token for word-\ufb01nal er, represented as er:\ncorpus vocabulary\n5l o w ,d,e,i,l,n,o,r,s,t,w,er,er\n2l o w e s t\n6n e w er\n3w i d er\n2n e w\nNextn e(total count of 8) get merged to ne:\ncorpus vocabulary\n5l o w ,d,e,i,l,n,o,r,s,t,w,er,er,ne\n2l o w e s t\n6ne w er\n3w i d er\n2ne w\nIf we continue, the next merges are:\nmerge current vocabulary\n(ne, w) ,d,e,i,l,n,o,r,s,t,w,er,er,ne,new\n(l, o) ,d,e,i,l,n,o,r,s,t,w,er,er,ne,new,lo\n(lo, w) ,d,e,i,l,n,o,r,s,t,w,er,er,ne,new,lo,low\n(new, er ) ,d,e,i,l,n,o,r,s,t,w,er,er,ne,new,lo,low,newer\n(low,) ,d,e,i,l,n,o,r,s,t,w,er,er,ne,new,lo,low,newer ,low\nOnce we\u2019ve learned our vocabulary, the token segmenter is used to tokenize a\ntest sentence. The token segmenter just runs on the merges we have learned from\nthe training data on the test data. It runs them greedily, in the order we learned them.\n(Thus the frequencies in the test data don\u2019t play a role, just the frequencies in the\ntraining data). So \ufb01rst we segment each test sentence word into characters. Then\nwe apply the \ufb01rst rule: replace every instance of e rin the test corpus with er, and\nthen the second rule: replace every instance of er in the test corpus with er,\nand so on. By the end, if the test corpus contained the character sequence n e w e\n2Note that there can be ties; we could have instead chosen to merge r \ufb01rst, since that also has a\nfrequency of 9. 2.6 \u2022 W ORD NORMALIZATION , LEMMATIZATION AND STEMMING 23\nfunction BYTE-PAIR ENCODING (strings C, number of merges k)returns vocab V\nV all unique characters in C # initial set of tokens is characters\nfori= 1tokdo # merge tokens ktimes\ntL,tR Most frequent pair of adjacent tokens in C\ntNEW tL+tR # make new token by concatenating\nV V+tNEW # update the vocabulary\nReplace each occurrence of tL,tRinCwith tNEW # and update the corpus\nreturn V\nFigure 2.13 The token learner part of the BPE algorithm for taking a corpus broken up\ninto individual characters or bytes, and learning a vocabulary by iteratively merging tokens.\nFigure adapted from Bostrom and Durrett (2020).\nr, it would be tokenized as a full word. But the characters of a new (unknown)\nword like l o w e r would be merged into the two tokens lower .\nOf course in real settings BPE is run with many thousands of merges on a very\nlarge input corpus. The result is that most words will be represented as full symbols,\nand only the very rare words (and unknown words) will have to be represented by\ntheir parts.\n2.6 Word Normalization, Lemmatization and Stemming\nWord normalization is the task of putting words or tokens in a standard format. The normalization\nsimplest case of word normalization is case folding . Mapping everything to lower case folding\ncase means that Woodchuck andwoodchuck are represented identically, which is\nvery helpful for generalization in many tasks, such as information retrieval or speech\nrecognition. For sentiment analysis and other text classi\ufb01cation tasks, information\nextraction, and machine translation, by contrast, case can be quite helpful and case\nfolding is generally not done. This is because maintaining the difference between,\nfor example, USthe country and usthe pronoun can outweigh the advantage in\ngeneralization that case folding would have provided for other words. Sometimes\nwe produce both cased (i.e. including both upper and lower case words or tokens)\nand uncased versions of language models.\nSystems that use BPE or other kinds of bottom-up tokenization may do no fur-\nther word normalization. In other NLP systems, we may want to do further nor-\nmalizations, like choosing a single normal form for words with multiple forms like\nUSA andUSoruh-huh anduhhuh . This standardization may be valuable, despite\nthe spelling information that is lost in the normalization process. For information\nretrieval or information extraction about the US, we might want to see information\nfrom documents whether they mention the USor theUSA.\n2.6.1 Lemmatization\nFor other natural language processing situations we also want two morphologically\ndifferent forms of a word to behave similarly. For example in web search, someone\nmay type the string woodchucks but a useful system might want to also return pages\nthat mention woodchuck with no s. This is especially common in morphologically\ncomplex languages like Polish, where for example the word Warsaw has different 24 CHAPTER 2 \u2022 R EGULAR EXPRESSIONS , TOKENIZATION , EDITDISTANCE\nendings when it is the subject ( Warszawa ), or after a preposition like \u201cin Warsaw\u201d ( w\nWarszawie ), or \u201cto Warsaw\u201d ( do Warszawy ), and so on. Lemmatization is the task lemmatization\nof determining that two words have the same root, despite their surface differences.\nThe words am,are, and ishave the shared lemma be; the words dinner anddinners\nboth have the lemma dinner . Lemmatizing each of these forms to the same lemma\nwill let us \ufb01nd all mentions of words in Polish like Warsaw . The lemmatized form\nof a sentence like He is reading detective stories would thus be He be read detective\nstory .\nHow is lemmatization done? The most sophisticated methods for lemmatization\ninvolve complete morphological parsing of the word. Morphology is the study of\nthe way words are built up from smaller meaning-bearing units called morphemes . morpheme\nTwo broad classes of morphemes can be distinguished: stems \u2014the central mor- stem\npheme of the word, supplying the main meaning\u2014and af\ufb01xes \u2014adding \u201cadditional\u201d af\ufb01x\nmeanings of various kinds. So, for example, the word foxconsists of one morpheme\n(the morpheme fox) and the word cats consists of two: the morpheme catand the\nmorpheme -s. A morphological parser takes a word like cats and parses it into the\ntwo morphemes catands, or parses a Spanish word like amaren (\u2018if in the future\nthey would love\u2019) into the morpheme amar \u2018to love\u2019, and the morphological features\n3PL (third person plural) and future subjunctive .\nStemming: The Porter Stemmer\nLemmatization algorithms can be complex. For this reason we sometimes make\nuse of a simpler but cruder method, which mainly consists of chopping off word-\n\ufb01nal af\ufb01xes. This naive version of morphological analysis is called stemming . For stemming\nexample, the classic Porter stemmer (Porter, 1980), when applied to the following Porter stemmer\nparagraph:\nThis was not the map we found in Billy Bones's chest, but\nan accurate copy, complete in all things-names and heights\nand soundings-with the single exception of the red crosses\nand the written notes.\nproduces the following stemmed output:\nThi wa not the map we found in Billi Bone s chest but an\naccur copi complet in all thing name and height and sound\nwith the singl except of the red cross and the written note\nThe algorithm is based on rewrite rules run in series, with the output of each pass\nfed as input to the next pass. Some sample rules (more at https://tartarus.org/\nmartin/PorterStemmer/ ):\nATIONAL!ATE (e.g., relational !relate)\nING!\u000fif the stem contains a vowel (e.g., motoring !motor)\nSSES!SS (e.g., grasses !grass)\nSimple stemmers can be useful in cases where we need to collapse across dif-\nferent variants of the same lemma. Nonetheless, they are less commonly used in\nmodern systems since they commit errors of both over-generalizating (lemmatizing\npolicy topolice ) and under-generalizing (not lemmatizing European toEurope )\n(Krovetz, 1993). 2.7 \u2022 S ENTENCE SEGMENTATION 25\n2.7 Sentence Segmentation\nSentence segmentation is another important step in text processing. The most use-sentence\nsegmentation\nful cues for segmenting a text into sentences are punctuation, like periods, question\nmarks, and exclamation points. Question marks and exclamation points are rela-\ntively unambiguous markers of sentence boundaries. Periods, on the other hand, are\nmore ambiguous. The period character \u201c.\u201d is ambiguous between a sentence bound-\nary marker and a marker of abbreviations like Mr.orInc.The previous sentence that\nyou just read showed an even more complex case of this ambiguity, in which the \ufb01nal\nperiod of Inc. marked both an abbreviation and the sentence boundary marker. For\nthis reason, sentence tokenization and word tokenization may be addressed jointly.\nIn general, sentence tokenization methods work by \ufb01rst deciding (based on rules\nor machine learning) whether a period is part of the word or is a sentence-boundary\nmarker. An abbreviation dictionary can help determine whether the period is part\nof a commonly used abbreviation; the dictionaries can be hand-built or machine-\nlearned (Kiss and Strunk, 2006), as can the \ufb01nal sentence splitter. In the Stanford\nCoreNLP toolkit (Manning et al., 2014), for example sentence splitting is rule-based,\na deterministic consequence of tokenization; a sentence ends when a sentence-ending\npunctuation (., !, or ?) is not already grouped with other characters into a token (such\nas for an abbreviation or number), optionally followed by additional \ufb01nal quotes or\nbrackets.\n2.8 Minimum Edit Distance\nMuch of natural language processing is concerned with measuring how similar two\nstrings are. For example in spelling correction, the user typed some erroneous\nstring\u2014let\u2019s say graffe \u2013and we want to know what the user meant. The user prob-\nably intended a word that is similar to graffe . Among candidate similar words,\nthe wordgiraffe , which differs by only one letter from graffe , seems intuitively\nto be more similar than, say grail orgraf , which differ in more letters. Another\nexample comes from coreference , the task of deciding whether two strings such as\nthe following refer to the same entity:\nStanford President Marc Tessier-Lavigne\nStanford University President Marc Tessier-Lavigne\nAgain, the fact that these two strings are very similar (differing by only one word)\nseems like useful evidence for deciding that they might be coreferent.\nEdit distance gives us a way to quantify both of these intuitions about string sim-\nilarity. More formally, the minimum edit distance between two strings is de\ufb01nedminimum edit\ndistance\nas the minimum number of editing operations (operations like insertion, deletion,\nsubstitution) needed to transform one string into another.\nThe gap between intention andexecution , for example, is 5 (delete an i, substi-\ntuteeforn, substitute xfort, insertc, substitute uforn). It\u2019s much easier to see\nthis by looking at the most important visualization for string distances, an alignment alignment\nbetween the two strings, shown in Fig. 2.14. Given two sequences, an alignment is\na correspondence between substrings of the two sequences. Thus, we say Ialigns\nwith the empty string, NwithE, and so on. Beneath the aligned strings is another\nrepresentation; a series of symbols expressing an operation list for converting the 26 CHAPTER 2 \u2022 R EGULAR EXPRESSIONS , TOKENIZATION , EDITDISTANCE\ntop string into the bottom string: dfor deletion, sfor substitution, ifor insertion.\nINTE*NTION\njjjjjjjjjj\n*EXECUTION\nd s s i s\nFigure 2.14 Representing the minimum edit distance between two strings as an alignment .\nThe \ufb01nal row gives the operation list for converting the top string into the bottom string: d for\ndeletion, s for substitution, i for insertion.\nWe can also assign a particular cost or weight to each of these operations. The\nLevenshtein distance between two sequences is the simplest weighting factor in\nwhich each of the three operations has a cost of 1 (Levenshtein, 1966)\u2014we assume\nthat the substitution of a letter for itself, for example, tfort, has zero cost. The Lev-\nenshtein distance between intention andexecution is 5. Levenshtein also proposed\nan alternative version of his metric in which each insertion or deletion has a cost of\n1 and substitutions are not allowed. (This is equivalent to allowing substitution, but\ngiving each substitution a cost of 2 since any substitution can be represented by one\ninsertion and one deletion). Using this version, the Levenshtein distance between\nintention andexecution is 8.\n2.8.1 The Minimum Edit Distance Algorithm\nHow do we \ufb01nd the minimum edit distance? We can think of this as a search task, in\nwhich we are searching for the shortest path\u2014a sequence of edits\u2014from one string\nto another.\nn t e n t i o ni n t e c n t i o ni n x e n t i o ndelinssubsti n t e n t i o n\nFigure 2.15 Finding the edit distance viewed as a search problem\nThe space of all possible edits is enormous, so we can\u2019t search naively. However,\nlots of distinct edit paths will end up in the same state (string), so rather than recom-\nputing all those paths, we could just remember the shortest path to a state each time\nwe saw it. We can do this by using dynamic programming . Dynamic programmingdynamic\nprogramming\nis the name for a class of algorithms, \ufb01rst introduced by Bellman (1957), that apply\na table-driven method to solve problems by combining solutions to subproblems.\nSome of the most commonly used algorithms in natural language processing make\nuse of dynamic programming, such as the Viterbi algorithm (Chapter 17) and the\nCKY algorithm for parsing (Chapter 18).\nThe intuition of a dynamic programming problem is that a large problem can\nbe solved by properly combining the solutions to various subproblems. Consider\nthe shortest path of transformed words that represents the minimum edit distance\nbetween the strings intention andexecution shown in Fig. 2.16.\nImagine some string (perhaps it is exention ) that is in this optimal path (whatever\nit is). The intuition of dynamic programming is that if exention is in the optimal 2.8 \u2022 M INIMUM EDITDISTANCE 27\nn t e n t i o ni n t e n t i o n\ne t e n t i o n\ne x e n t i o n\ne x e n u t i o n\ne x e c u t i o ndelete i\nsubstitute n by e\nsubstitute t by x\ninsert u\nsubstitute n by c\nFigure 2.16 Path from intention toexecution .\noperation list, then the optimal sequence must also include the optimal path from\nintention toexention . Why? If there were a shorter path from intention toexention ,\nthen we could use it instead, resulting in a shorter overall path, and the optimal\nsequence wouldn\u2019t be optimal, thus leading to a contradiction.\nThe minimum edit distance algorithm was named by Wagner and Fischerminimum edit\ndistance\nalgorithm(1974) but independently discovered by many people (see the Historical Notes sec-\ntion of Chapter 17).\nLet\u2019s \ufb01rst de\ufb01ne the minimum edit distance between two strings. Given two\nstrings, the source string Xof length n, and target string Yof length m, we\u2019ll de\ufb01ne\nD[i;j]as the edit distance between X[1::i]andY[1::j], i.e., the \ufb01rst icharacters of X\nand the \ufb01rst jcharacters of Y. The edit distance between XandYis thus D[n;m].\nWe\u2019ll use dynamic programming to compute D[n;m]bottom up, combining so-\nlutions to subproblems. In the base case, with a source substring of length ibut an\nempty target string, going from icharacters to 0 requires ideletes. With a target\nsubstring of length jbut an empty source going from 0 characters to jcharacters\nrequires jinserts. Having computed D[i;j]for small i;jwe then compute larger\nD[i;j]based on previously computed smaller values. The value of D[i;j]is com-\nputed by taking the minimum of the three possible paths through the matrix which\narrive there:\nD[i;j] =min8\n<\n:D[i\u00001;j]+del-cost (source [i])\nD[i;j\u00001]+ins-cost (target [j])\nD[i\u00001;j\u00001]+sub-cost (source [i];target [j])(2.25)\nWe mentioned above two versions of Levenshtein distance, one in which substitu-\ntions cost 1 and one in which substitutions cost 2 (i.e., are equivalent to an insertion\nplus a deletion). Let\u2019s here use that second version of Levenshtein distance in which\nthe insertions and deletions each have a cost of 1 (ins-cost( \u0001) = del-cost(\u0001) = 1), and\nsubstitutions have a cost of 2 (except substitution of identical letters has zero cost).\nUnder this version of Levenshtein, the computation for D[i;j]becomes:\nD[i;j] =min8\n>><\n>>:D[i\u00001;j]+1\nD[i;j\u00001]+1\nD[i\u00001;j\u00001]+\u001a2; if source [i]6=target [j]\n0; if source [i] =target [j](2.26)\nThe algorithm is summarized in Fig. 2.17; Fig. 2.18 shows the results of applying\nthe algorithm to the distance between intention andexecution with the version of\nLevenshtein in Eq. 2.26.\nAlignment Knowing the minimum edit distance is useful for algorithms like \ufb01nd-\ning potential spelling error corrections. But the edit distance algorithm is important 28 CHAPTER 2 \u2022 R EGULAR EXPRESSIONS , TOKENIZATION , EDITDISTANCE\nfunction MIN-EDIT-DISTANCE (source ,target )returns min-distance\nn LENGTH (source )\nm LENGTH (target )\nCreate a distance matrix D[n+1,m+1]\n#Initialization: the zeroth row and column is the distance from the empty string\nD[0,0] = 0\nforeach row ifrom 1tondo\nD[i,0] D[i-1,0] + del-cost (source [i])\nforeach column jfrom 1tomdo\nD[0,j] D[0,j-1] + ins-cost (target [j])\n#Recurrence relation:\nforeach row ifrom 1tondo\nforeach column jfrom 1tomdo\nD[i, j] MIN(D[i\u00001,j] +del-cost (source [i]),\nD[i\u00001,j\u00001] + sub-cost (source [i],target [j]),\nD[i,j\u00001] + ins-cost (target [j]))\n#Termination\nreturn D[n,m]\nFigure 2.17 The minimum edit distance algorithm, an example of the class of dynamic\nprogramming algorithms. The various costs can either be \ufb01xed (e.g., 8x;ins-cost (x) =1)\nor can be speci\ufb01c to the letter (to model the fact that some letters are more likely to be in-\nserted than others). We assume that there is no cost for substituting a letter for itself (i.e.,\nsub-cost (x;x) =0).\nSrcnTar # e x e c u t i o n\n# 0 1 2 3 4 5 6 7 8 9\ni 1 2 3 4 5 6 7 6 7 8\nn 2 3 4 5 6 7 8 7 8 7\nt 3 4 5 6 7 8 7 8 9 8\ne 4 3 4 5 6 7 8 9 10 9\nn 5 4 5 6 7 8 9 10 11 10\nt 6 5 6 7 8 9 8 9 10 11\ni 7 6 7 8 9 10 9 8 9 10\no 8 7 8 9 10 11 10 9 8 9\nn 9 8 9 10 11 12 11 10 9 8\nFigure 2.18 Computation of minimum edit distance between intention andexecution with\nthe algorithm of Fig. 2.17, using Levenshtein distance with cost of 1 for insertions or dele-\ntions, 2 for substitutions.\nin another way; with a small change, it can also provide the minimum cost align-\nment between two strings. Aligning two strings is useful throughout speech and\nlanguage processing. In speech recognition, minimum edit distance alignment is\nused to compute the word error rate (Chapter 16). Alignment plays a role in ma-\nchine translation, in which sentences in a parallel corpus (a corpus with a text in two\nlanguages) need to be matched to each other.\nTo extend the edit distance algorithm to produce an alignment, we can start by\nvisualizing an alignment as a path through the edit distance matrix. Figure 2.19\nshows this path with boldfaced cells. Each boldfaced cell represents an alignment 2.9 \u2022 S UMMARY 29\nof a pair of letters in the two strings. If two boldfaced cells occur in the same row,\nthere will be an insertion in going from the source to the target; two boldfaced cells\nin the same column indicate a deletion.\nFigure 2.19 also shows the intuition of how to compute this alignment path. The\ncomputation proceeds in two steps. In the \ufb01rst step, we augment the minimum edit\ndistance algorithm to store backpointers in each cell. The backpointer from a cell\npoints to the previous cell (or cells) that we came from in entering the current cell.\nWe\u2019ve shown a schematic of these backpointers in Fig. 2.19. Some cells have mul-\ntiple backpointers because the minimum extension could have come from multiple\nprevious cells. In the second step, we perform a backtrace . In a backtrace, we start backtrace\nfrom the last cell (at the \ufb01nal row and column), and follow the pointers back through\nthe dynamic programming matrix. Each complete path between the \ufb01nal cell and the\ninitial cell is a minimum distance alignment. Exercise 2.7 asks you to modify the\nminimum edit distance algorithm to store the pointers and compute the backtrace to\noutput an alignment.\n# e x e c u t i o n\n# 0 1 2 3 4 5 6 7 8 9\ni\"1- \" 2- \" 3- \" 4- \" 5- \" 6- \" 7-6 7 8\nn\"2- \" 3- \" 4- \" 5- \" 6- \" 7- \" 8\"7- \" 8-7\nt\"3- \" 4- \" 5- \" 6- \" 7- \" 8-7 \"8- \" 9\"8\ne\"4-3 4- 5 6 7 \"8- \" 9- \" 10\"9\nn\"5\"4- \" 5- \" 6- \" 7- \" 8- \" 9- \" 10- \" 11-\"10\nt\"6\"5- \" 6- \" 7- \" 8- \" 9-8 9 10 \"11\ni\"7\"6- \" 7- \" 8- \" 9- \" 10\"9-8 9 10\no\"8\"7- \" 8- \" 9- \" 10- \" 11\"10\"9-8 9\nn\"9\"8- \" 9- \" 10- \" 11- \" 12\"11\"10\"9-8\nFigure 2.19 When entering a value in each cell, we mark which of the three neighboring\ncells we came from with up to three arrows. After the table is full we compute an alignment\n(minimum edit path) by using a backtrace , starting at the 8in the lower-right corner and\nfollowing the arrows back. The sequence of bold cells represents one possible minimum\ncost alignment between the two strings, again using Levenshtein distance with cost of 1 for\ninsertions or deletions, 2 for substitutions. Diagram design after Gus\ufb01eld (1997).\nWhile we worked our example with simple Levenshtein distance, the algorithm\nin Fig. 2.17 allows arbitrary weights on the operations. For spelling correction, for\nexample, substitutions are more likely to happen between letters that are next to\neach other on the keyboard. The Viterbi algorithm is a probabilistic extension of\nminimum edit distance. Instead of computing the \u201cminimum edit distance\u201d between\ntwo strings, Viterbi computes the \u201cmaximum probability alignment\u201d of one string\nwith another. We\u2019ll discuss this more in Chapter 17.\n2.9 Summary\nThis chapter introduced a fundamental tool in language processing, the regular ex-\npression , and showed how to perform basic text normalization tasks including\nword segmentation andnormalization ,sentence segmentation , and stemming .\nWe also introduced the important minimum edit distance algorithm for comparing\nstrings. Here\u2019s a summary of the main points we covered about these ideas: 30 CHAPTER 2 \u2022 R EGULAR EXPRESSIONS , TOKENIZATION , EDITDISTANCE\n\u2022 The regular expression language is a powerful tool for pattern-matching.\n\u2022 Basic operations in regular expressions include concatenation of symbols,\ndisjunction of symbols ( [],|),counters (*,+, and{n,m} ),anchors (^,$)\nand precedence operators ( (,)).\n\u2022Word tokenization and normalization are generally done by cascades of\nsimple regular expression substitutions or \ufb01nite automata.\n\u2022 The Porter algorithm is a simple and ef\ufb01cient way to do stemming , stripping\noff af\ufb01xes. It does not have high accuracy but may be useful for some tasks.\n\u2022 The minimum edit distance between two strings is the minimum number of\noperations it takes to edit one into the other. Minimum edit distance can be\ncomputed by dynamic programming , which also results in an alignment of\nthe two strings.\nBibliographical and Historical Notes\nKleene 1951; 1956 \ufb01rst de\ufb01ned regular expressions and the \ufb01nite automaton, based\non the McCulloch-Pitts neuron. Ken Thompson was one of the \ufb01rst to build regular\nexpressions compilers into editors for text searching (Thompson, 1968). His edi-\ntoredincluded a command \u201cg/regular expression/p\u201d, or Global Regular Expression\nPrint, which later became the Unix grep utility.\nText normalization algorithms have been applied since the beginning of the\n\ufb01eld. One of the earliest widely used stemmers was Lovins (1968). Stemming\nwas also applied early to the digital humanities, by Packard (1973), who built an\naf\ufb01x-stripping morphological parser for Ancient Greek. Currently a wide vari-\nety of code for tokenization and normalization is available, such as the Stanford\nTokenizer ( https://nlp.stanford.edu/software/tokenizer.shtml ) or spe-\ncialized tokenizers for Twitter (O\u2019Connor et al., 2010), or for sentiment ( http:\n//sentiment.christopherpotts.net/tokenizing.html ). See Palmer (2012)\nfor a survey of text preprocessing. NLTK is an essential tool that offers both useful\nPython libraries ( https://www.nltk.org ) and textbook descriptions (Bird et al.,\n2009) of many algorithms including text normalization and corpus interfaces.\nFor more on Herdan\u2019s law and Heaps\u2019 Law, see Herdan (1960, p. 28), Heaps\n(1978), Egghe (2007) and Baayen (2001); For more on edit distance, see Gus\ufb01eld\n(1997). Our example measuring the edit distance from \u2018intention\u2019 to \u2018execution\u2019\nwas adapted from Kruskal (1983). There are various publicly available packages to\ncompute edit distance, including Unix diff and the NIST sclite program (NIST,\n2005).\nIn his autobiography Bellman (1984) explains how he originally came up with\nthe term dynamic programming :\n\u201c...The 1950s were not good years for mathematical research. [the]\nSecretary of Defense ...had a pathological fear and hatred of the word,\nresearch... I decided therefore to use the word, \u201cprogramming\u201d. I\nwanted to get across the idea that this was dynamic, this was multi-\nstage... I thought, let\u2019s ... take a word that has an absolutely precise\nmeaning, namely dynamic... it\u2019s impossible to use the word, dynamic,\nin a pejorative sense. Try thinking of some combination that will pos-\nsibly give it a pejorative meaning. It\u2019s impossible. Thus, I thought\ndynamic programming was a good name. It was something not even a\nCongressman could object to.\u201d EXERCISES 31\nExercises\n2.1 Write regular expressions for the following languages.\n1. the set of all alphabetic strings;\n2. the set of all lower case alphabetic strings ending in a b;\n3. the set of all strings from the alphabet a;bsuch that each ais immedi-\nately preceded by and immediately followed by a b;\n2.2 Write regular expressions for the following languages. By \u201cword\u201d, we mean\nan alphabetic string separated from other words by whitespace, any relevant\npunctuation, line breaks, and so forth.\n1. the set of all strings with two consecutive repeated words (e.g., \u201cHum-\nbert Humbert\u201d and \u201cthe the\u201d but not \u201cthe bug\u201d or \u201cthe big bug\u201d);\n2. all strings that start at the beginning of the line with an integer and that\nend at the end of the line with a word;\n3. all strings that have both the word grotto and the word raven in them\n(but not, e.g., words like grottos that merely contain the word grotto );\n4. write a pattern that places the \ufb01rst word of an English sentence in a\nregister. Deal with punctuation.\n2.3 Implement an ELIZA-like program, using substitutions such as those described\non page 13. You might want to choose a different domain than a Rogerian psy-\nchologist, although keep in mind that you would need a domain in which your\nprogram can legitimately engage in a lot of simple repetition.\n2.4 Compute the edit distance (using insertion cost 1, deletion cost 1, substitution\ncost 1) of \u201cleda\u201d to \u201cdeal\u201d. Show your work (using the edit distance grid).\n2.5 Figure out whether drive is closer to brief or to divers and what the edit dis-\ntance is to each. You may use any version of distance that you like.\n2.6 Now implement a minimum edit distance algorithm and use your hand-computed\nresults to check your code.\n2.7 Augment the minimum edit distance algorithm to output an alignment; you\nwill need to store pointers and add a stage to compute the backtrace. 32 CHAPTER 3 \u2022 N- GRAM LANGUAGE MODELS\nCHAPTER\n3N-gram Language Models\n\u201cYou are uniformly charming!\u201d cried he, with a smile of associating and now\nand then I bowed and they perceived a chaise and four to wish for.\nRandom sentence generated from a Jane Austen trigram model\nPredicting is dif\ufb01cult\u2014especially about the future, as the old quip goes. But how\nabout predicting something that seems much easier, like the next word someone is\ngoing to say? What word, for example, is likely to follow\nThe water of Walden Pond is so beautifully ...\nYou might conclude that a likely word is blue , orgreen , orclear , but probably not\nrefrigerator northis . In this chapter we formalize this intuition by introducing\nlanguage models orLMs , models that assign a probability to each possible next language model\nLM word. Language models can also assign a probability to an entire sentence, telling\nus that the following sequence has a much higher probability of appearing in a text:\nall of a sudden I notice three guys standing on the sidewalk\nthan does this same set of words in a different order:\non guys all I of notice sidewalk three a sudden standing the\nWhy would we want to predict upcoming words, or know the probability of a sen-\ntence? One reason is for generation: choosing contextually better words. For ex-\nample we can correct grammar or spelling errors like Their are two midterms ,\nin whichThere was mistyped as Their , orEverything has improve , in which\nimprove should have been improved . The phrase There are is more probable\nthanTheir are , andhas improved thanhas improve , so a language model can\nhelp users select the more grammatical variant. Or for a speech system to recognize\nthat you said I will be back soonish and notI will be bassoon dish , it\nhelps to know that back soonish is a more probable sequence. Language models\ncan also help in augmentative and alternative communication (Trnka et al. 2007,\nKane et al. 2017). People can use AAC systems if they are physically unable to AAC\nspeak or sign but can instead use eye gaze or other movements to select words from\na menu. Word prediction can be used to suggest likely words for the menu.\nWord prediction is also central to NLP for another reason: large language mod-\nelsare built just by training them to predict words!! As we\u2019ll see in chapters 7-9,\nlarge language models learn an enormous amount about language solely from being\ntrained to predict upcoming words from neighboring words.\nIn this chapter we introduce the simplest kind of language model: the n-gram n-gram\nlanguage model. An n-gram is a sequence of nwords: a 2-gram (which we\u2019ll call\nbigram ) is a two-word sequence of words like The water , orwater of , and a 3-\ngram (a trigram ) is a three-word sequence of words like The water of , orwater 3.1 \u2022 N-G RAMS 33\nof Walden . But we also (in a bit of terminological ambiguity) use the word \u2018n-\ngram\u2019 to mean a probabilistic model that can estimate the probability of a word given\nthe n-1 previous words, and thereby also to assign probabilities to entire sequences.\nIn later chapters we will introduce the much more powerful neural large lan-\nguage models , based on the transformer architecture of Chapter 9. But because\nn-grams have a remarkably simple and clear formalization, we use them to intro-\nduce some major concepts of large language modeling, including training and test\nsets,perplexity ,sampling , and interpolation .\n3.1 N-Grams\nLet\u2019s begin with the task of computing P(wjh), the probability of a word wgiven\nsome history h. Suppose the history his \u201cThe water of Walden Pond is so\nbeautifully \u201d and we want to know the probability that the next word is blue :\nP(bluejThe water of Walden Pond is so beautifully ) (3.1)\nOne way to estimate this probability is directly from relative frequency counts: take a\nvery large corpus, count the number of times we see The water of Walden Pond\nis so beautifully , and count the number of times this is followed by blue . This\nwould be answering the question \u201cOut of the times we saw the history h, how many\ntimes was it followed by the word w\u201d, as follows:\nP(bluejThe water of Walden Pond is so beautifully ) =\nC(The water of Walden Pond is so beautifully blue )\nC(The water of Walden Pond is so beautifully )(3.2)\nIf we had a large enough corpus, we could compute these two counts and estimate\nthe probability from Eq. 3.2. But even the entire web isn\u2019t big enough to give us\ngood estimates for counts of entire sentences. This is because language is creative ;\nnew sentences are invented all the time, and we can\u2019t expect to get accurate counts\nfor such large objects as entire sentences. For this reason, we\u2019ll need more clever\nways to estimate the probability of a word wgiven a history h, or the probability of\nan entire word sequence W.\nLet\u2019s start with some notation. First, throughout this chapter we\u2019ll continue to\nrefer to words , although in practice we usually compute language models over to-\nkens like the BPE tokens of page 21. To represent the probability of a particular\nrandom variable Xitaking on the value \u201cthe\u201d, or P(Xi=\u201cthe\u201d), we will use the\nsimpli\ufb01cation P(the). We\u2019ll represent a sequence of nwords either as w1:::wnor\nw1:n. Thus the expression w1:n\u00001means the string w1;w2;:::;wn\u00001, but we\u2019ll also\nbe using the equivalent notation wat the beginning\nof the sentence, to give us the bigram context of the \ufb01rst word. We\u2019ll also need a\nspecial end-symbol .1\n I am Sam \n Sam I am \n I do not like green eggs and ham \nHere are the calculations for some of the bigram probabilities from this corpus\nP(I| ) =2\n3=0:67 P(Sam| ) =1\n3=0:33 P(am|I) =2\n3=0:67\nP(|Sam ) =1\n2=0:5 P(Sam|am ) =1\n2=0:5 P(do|I) =1\n3=0:33\nFor the general case of MLE n-gram parameter estimation:\nP(wnjwn\u0000N+1:n\u00001) =C(wn\u0000N+1:n\u00001wn)\nC(wn\u0000N+1:n\u00001)(3.12)\nEquation 3.12 (like Eq. 3.11) estimates the n-gram probability by dividing the\nobserved frequency of a particular sequence by the observed frequency of a pre\ufb01x.\nThis ratio is called a relative frequency . We said above that this use of relativerelative\nfrequency\nfrequencies as a way to estimate probabilities is an example of maximum likelihood\nestimation or MLE. In MLE, the resulting parameter set maximizes the likelihood of\nthe training set Tgiven the model M(i.e., P(TjM)). For example, suppose the word\nChinese occurs 400 times in a corpus of a million words. What is the probability\nthat a random word selected from some other text of, say, a million words will be the\nword Chinese ? The MLE of its probability is400\n1000000or 0:0004. Now 0 :0004 is not\nthe best possible estimate of the probability of Chinese occurring in all situations; it\n1We need the end-symbol to make the bigram grammar a true probability distribution. Without an end-\nsymbol, instead of the sentence probabilities of all sentences summing to one, the sentence probabilities\nfor all sentences of a given length would sum to one. This model would de\ufb01ne an in\ufb01nite set of probability\ndistributions, with one distribution per sentence length. See Exercise 3.5. 36 CHAPTER 3 \u2022 N- GRAM LANGUAGE MODELS\nmight turn out that in some other corpus or context Chinese is a very unlikely word.\nBut it is the probability that makes it most likely that Chinese will occur 400 times\nin a million-word corpus. We present ways to modify the MLE estimates slightly to\nget better probability estimates in Section 3.6.\nLet\u2019s move on to some examples from a real but tiny corpus, drawn from the\nnow-defunct Berkeley Restaurant Project, a dialogue system from the last century\nthat answered questions about a database of restaurants in Berkeley, California (Ju-\nrafsky et al., 1994). Here are some sample user queries (text-normalized, by lower\ncasing and with punctuation striped) (a sample of 9332 sentences is on the website):\ncan you tell me about any good cantonese restaurants close by\ntell me about chez panisse\ni\u2019m looking for a good place to eat breakfast\nwhen is caffe venezia open during the day\nFigure 3.1 shows the bigram counts from part of a bigram grammar from text-\nnormalized Berkeley Restaurant Project sentences. Note that the majority of the\nvalues are zero. In fact, we have chosen the sample words to cohere with each other;\na matrix selected from a random set of eight words would be even more sparse.\ni want to eat chinese food lunch spend\ni 5 827 0 9 0 0 0 2\nwant 2 0 608 1 6 6 5 1\nto 2 0 4 686 2 0 6 211\neat 0 0 2 0 16 2 42 0\nchinese 1 0 0 0 0 82 1 0\nfood 15 0 15 0 1 4 0 0\nlunch 2 0 0 0 0 1 0 0\nspend 1 0 1 0 0 0 0 0\nFigure 3.1 Bigram counts for eight of the words (out of V=1446) in the Berkeley Restau-\nrant Project corpus of 9332 sentences. Zero counts are in gray. Each cell shows the count of\nthe column label word following the row label word. Thus the cell in row iand column want\nmeans that want followed i827 times in the corpus.\nFigure 3.2 shows the bigram probabilities after normalization (dividing each cell\nin Fig. 3.1 by the appropriate unigram for its row, taken from the following set of\nunigram counts):\ni want to eat chinese food lunch spend\n2533 927 2417 746 158 1093 341 278\nHere are a few other useful probabilities:\nP(i| ) =0:25 P(english|want ) =0:0011\nP(food|english ) =0:5 P(|food ) =0:68\nNow we can compute the probability of sentences like I want English food or\nI want Chinese food by simply multiplying the appropriate bigram probabilities to-\ngether, as follows:\nP( i want english food )\n=P(i| )P(want|i )P(english|want )\nP(food|english )P(|food )\n=0:25\u00020:33\u00020:0011\u00020:5\u00020:68\n=0:000031 3.1 \u2022 N-G RAMS 37\ni want to eat chinese food lunch spend\ni 0.002 0.33 0 0.0036 0 0 0 0.00079\nwant 0.0022 0 0.66 0.0011 0.0065 0.0065 0.0054 0.0011\nto 0.00083 0 0.0017 0.28 0.00083 0 0.0025 0.087\neat 0 0 0.0027 0 0.021 0.0027 0.056 0\nchinese 0.0063 0 0 0 0 0.52 0.0063 0\nfood 0.014 0 0.014 0 0.00092 0.0037 0 0\nlunch 0.0059 0 0 0 0 0.0029 0 0\nspend 0.0036 0 0.0036 0 0 0 0 0\nFigure 3.2 Bigram probabilities for eight words in the Berkeley Restaurant Project corpus\nof 9332 sentences. Zero probabilities are in gray.\nWe leave it as Exercise 3.2 to compute the probability of i want chinese food .\nWhat kinds of linguistic phenomena are captured in these bigram statistics?\nSome of the bigram probabilities above encode some facts that we think of as strictly\nsyntactic in nature, like the fact that what comes after eatis usually a noun or an\nadjective, or that what comes after tois usually a verb. Others might be a fact about\nthe personal assistant task, like the high probability of sentences beginning with\nthe words I. And some might even be cultural rather than linguistic, like the higher\nprobability that people are looking for Chinese versus English food.\n3.1.3 Dealing with scale in large n-gram models\nIn practice, language models can be very large, leading to practical issues.\nLog probabilities Language model probabilities are always stored and computed\nin log space as log probabilities . This is because probabilities are (by de\ufb01nition) lesslog\nprobabilities\nthan or equal to 1, and so the more probabilities we multiply together, the smaller the\nproduct becomes. Multiplying enough n-grams together would result in numerical\nunder\ufb02ow. Adding in log space is equivalent to multiplying in linear space, so we\ncombine log probabilities by adding them. By adding log probabilities instead of\nmultiplying probabilities, we get results that are not as small. We do all computation\nand storage in log space, and just convert back into probabilities if we need to report\nprobabilities at the end by taking the exp of the logprob:\np1\u0002p2\u0002p3\u0002p4=exp(logp1+logp2+logp3+logp4) (3.13)\nIn practice throughout this book, we\u2019ll use log to mean natural log (ln) when the\nbase is not speci\ufb01ed.\nLonger context Although for pedagogical purposes we have only described bi-\ngram models, when there is suf\ufb01cient training data we use trigram models, which trigram\ncondition on the previous two words, or 4-gram or5-gram models. For these larger 4-gram\n5-gram n-grams, we\u2019ll need to assume extra contexts to the left and right of the sentence end.\nFor example, to compute trigram probabilities at the very beginning of the sentence,\nwe use two pseudo-words for the \ufb01rst trigram (i.e., P(I| ).\nSome large n-gram datasets have been created, like the million most frequent\nn-grams drawn from the Corpus of Contemporary American English (COCA), a\ncurated 1 billion word corpus of American English (Davies, 2020), Google\u2019s Web\n5-gram corpus from 1 trillion words of English web text (Franz and Brants, 2006),\nor the Google Books Ngrams corpora (800 billion tokens from Chinese, English,\nFrench, German, Hebrew, Italian, Russian, and Spanish) (Lin et al., 2012a)). 38 CHAPTER 3 \u2022 N- GRAM LANGUAGE MODELS\nIt\u2019s even possible to use extremely long-range n-gram context. The in\ufb01ni-gram\n(\u00a5-gram) project (Liu et al., 2024) allows n-grams of any length. Their idea is to\navoid the expensive (in space and time) pre-computation of huge n-gram count ta-\nbles. Instead, n-gram probabilities with arbitrary n are computed quickly at inference\ntime by using an ef\ufb01cient representation called suf\ufb01x arrays. This allows computing\nof n-grams of every length for enormous corpora of 5 trillion tokens.\nEf\ufb01ciency considerations are important when building large n-gram language\nmodels. It is standard to quantize the probabilities using only 4-8 bits (instead of\n8-byte \ufb02oats), store the word strings on disk and represent them in memory only as\na 64-bit hash, and represent n-grams in special data structures like \u2018reverse tries\u2019.\nIt is also common to prune n-gram language models, for example by only keeping\nn-grams with counts greater than some threshold or using entropy to prune less-\nimportant n-grams (Stolcke, 1998). Ef\ufb01cient language model toolkits like KenLM\n(Hea\ufb01eld 2011, Hea\ufb01eld et al. 2013) use sorted arrays and use merge sorts to ef\ufb01-\nciently build the probability tables in a minimal number of passes through a large\ncorpus.\n3.2 Evaluating Language Models: Training and Test Sets\nThe best way to evaluate the performance of a language model is to embed it in\nan application and measure how much the application improves. Such end-to-end\nevaluation is called extrinsic evaluation . Extrinsic evaluation is the only way toextrinsic\nevaluation\nknow if a particular improvement in the language model (or any component) is really\ngoing to help the task at hand. Thus for evaluating n-gram language models that are\na component of some task like speech recognition or machine translation, we can\ncompare the performance of two candidate language models by running the speech\nrecognizer or machine translator twice, once with each language model, and seeing\nwhich gives the more accurate transcription.\nUnfortunately, running big NLP systems end-to-end is often very expensive. In-\nstead, it\u2019s helpful to have a metric that can be used to quickly evaluate potential\nimprovements in a language model. An intrinsic evaluation metric is one that mea-intrinsic\nevaluation\nsures the quality of a model independent of any application. In the next section we\u2019ll\nintroduce perplexity , which is the standard intrinsic metric for measuring language\nmodel performance, both for simple n-gram language models and for the more so-\nphisticated neural large language models of Chapter 9.\nIn order to evaluate any machine learning model, we need to have at least three\ndistinct data sets: the training set , the development set , and the test set . training set\ndevelopment\nset\ntest setThe training set is the data we use to learn the parameters of our model; for\nsimple n-gram language models it\u2019s the corpus from which we get the counts that\nwe normalize into the probabilities of the n-gram language model.\nThetest set is a different, held-out set of data, not overlapping with the training\nset, that we use to evaluate the model. We need a separate test set to give us an\nunbiased estimate of how well the model we trained can generalize when we apply\nit to some new unknown dataset. A machine learning model that perfectly captured\nthe training data, but performed terribly on any other data, wouldn\u2019t be much use\nwhen it comes time to apply it to any new data or problem! We thus measure the\nquality of an n-gram model by its performance on this unseen test set or test corpus.\nHow should we choose a training and test set? The test set should re\ufb02ect the\nlanguage we want to use the model for. If we\u2019re going to use our language model 3.3 \u2022 E VALUATING LANGUAGE MODELS : PERPLEXITY 39\nfor speech recognition of chemistry lectures, the test set should be text of chemistry\nlectures. If we\u2019re going to use it as part of a system for translating hotel booking re-\nquests from Chinese to English, the test set should be text of hotel booking requests.\nIf we want our language model to be general purpose, then the test set should be\ndrawn from a wide variety of texts. In such cases we might collect a lot of texts\nfrom different sources, and then divide it up into a training set and a test set. It\u2019s\nimportant to do the dividing carefully; if we\u2019re building a general purpose model,\nwe don\u2019t want the test set to consist of only text from one document, or one author,\nsince that wouldn\u2019t be a good measure of general performance.\nThus if we are given a corpus of text and want to compare the performance of\ntwo different n-gram models, we divide the data into training and test sets, and train\nthe parameters of both models on the training set. We can then compare how well\nthe two trained models \ufb01t the test set.\nBut what does it mean to \u201c\ufb01t the test set\u201d? The standard answer is simple:\nwhichever language model assigns a higher probability to the test set\u2014which\nmeans it more accurately predicts the test set\u2014is a better model. Given two proba-\nbilistic models, the better model is the one that better predicts the details of the test\ndata, and hence will assign a higher probability to the test data.\nSince our evaluation metric is based on test set probability, it\u2019s important not to\nlet the test sentences into the training set. Suppose we are trying to compute the\nprobability of a particular \u201ctest\u201d sentence. If our test sentence is part of the training\ncorpus, we will mistakenly assign it an arti\ufb01cially high probability when it occurs\nin the test set. We call this situation training on the test set . Training on the test\nset introduces a bias that makes the probabilities all look too high, and causes huge\ninaccuracies in perplexity , the probability-based metric we introduce below.\nEven if we don\u2019t train on the test set, if we test our language model on the\ntest set many times after making different changes, we might implicitly tune to its\ncharacteristics, by noticing which changes seem to make the model better. For this\nreason, we only want to run our model on the test set once, or a very few number of\ntimes, once we are sure our model is ready.\nFor this reason we normally instead have a third dataset called a developmentdevelopment\ntest\ntest set or, devset . We do all our testing on this dataset until the very end, and then\nwe test on the test once to see how good our model is.\nHow do we divide our data into training, development, and test sets? We want\nour test set to be as large as possible, since a small test set may be accidentally un-\nrepresentative, but we also want as much training data as possible. At the minimum,\nwe would want to pick the smallest test set that gives us enough statistical power\nto measure a statistically signi\ufb01cant difference between two potential models. It\u2019s\nimportant that the devset be drawn from the same kind of text as the test set, since\nits goal is to measure how we would do on the test set.\n3.3 Evaluating Language Models: Perplexity\nWe said above that we evaluate language models based on which one assigns a\nhigher probability to the test set. A better model is better at predicting upcoming\nwords, and so it will be less surprised by (i.e., assign a higher probability to) each\nword when it occurs in the test set. Indeed, a perfect language model would correctly\nguess each next word in a corpus, assigning it a probability of 1, and all the other\nwords a probability of zero. So given a test corpus, a better language model will 40 CHAPTER 3 \u2022 N- GRAM LANGUAGE MODELS\nassign a higher probability to it than a worse language model.\nBut in fact, we do not use raw probability as our metric for evaluating language\nmodels. The reason is that the probability of a test set (or any sequence) depends\non the number of words or tokens in it; the probability of a test set gets smaller the\nlonger the text. We\u2019d prefer a metric that is per-word, normalized by length, so we\ncould compare across texts of different lengths. The metric we use is, a function of\nprobability called perplexity , is one of the most important metrics in NLP, used for\nevaluating large language models as well as n-gram models.\nTheperplexity (sometimes abbreviated as PP or PPL) of a language model on a perplexity\ntest set is the inverse probability of the test set (one over the probability of the test\nset), normalized by the number of words (or tokens). For this reason it\u2019s sometimes\ncalled the per-word or per-token perplexity. We normalize by the number of words\nNby taking the Nth root. For a test set W=w1w2:::wN,:\nperplexity (W) = P(w1w2:::wN)\u00001\nN (3.14)\n=Ns\n1\nP(w1w2:::wN)\nOr we can use the chain rule to expand the probability of W:\nperplexity (W) =NvuutNY\ni=11\nP(wijw1:::wi\u00001)(3.15)\nNote that because of the inverse in Eq. 3.15, the higher the probability of the word\nsequence, the lower the perplexity. Thus the the lower the perplexity of a model on\nthe data, the better the model . Minimizing perplexity is equivalent to maximizing\nthe test set probability according to the language model. Why does perplexity use\nthe inverse probability? It turns out the inverse arises from the original de\ufb01nition\nof perplexity from cross-entropy rate in information theory; for those interested, the\nexplanation is in the advanced Section 3.7. Meanwhile, we just have to remember\nthat perplexity has an inverse relationship with probability.\nThe details of computing the perplexity of a test set Wdepends on which lan-\nguage model we use. Here\u2019s the perplexity of Wwith a unigram language model\n(just the geometric mean of the inverse of the unigram probabilities):\nperplexity (W) =NvuutNY\ni=11\nP(wi)(3.16)\nThe perplexity of Wcomputed with a bigram language model is still a geometric\nmean, but now of the inverse of the bigram probabilities:\nperplexity (W) =NvuutNY\ni=11\nP(wijwi\u00001)(3.17)\nWhat we generally use for word sequence in Eq. 3.15 or Eq. 3.17 is the entire\nsequence of words in some test set. Since this sequence will cross many sentence\nboundaries, if our vocabulary includes a between-sentence token or separate\nbegin- and end-sentence markers and then we can include them in the 3.3 \u2022 E VALUATING LANGUAGE MODELS : PERPLEXITY 41\nprobability computation. If we do, then we also include one token per sentence in\nthe total count of word tokens N.2\nWe mentioned above that perplexity is a function of both the text and the lan-\nguage model: given a text W, different language models will have different perplex-\nities. Because of this, perplexity can be used to compare different language models.\nFor example, here we trained unigram, bigram, and trigram grammars on 38 million\nwords from the Wall Street Journal newspaper. We then computed the perplexity of\neach of these models on a WSJ test set using Eq. 3.16 for unigrams, Eq. 3.17 for\nbigrams, and the corresponding equation for trigrams. The table below shows the\nperplexity of the 1.5 million word test set according to each of the language models.\nUnigram Bigram Trigram\nPerplexity 962 170 109\nAs we see above, the more information the n-gram gives us about the word\nsequence, the higher the probability the n-gram will assign to the string. A trigram\nmodel is less surprised than a unigram model because it has a better idea of what\nwords might come next, and so it assigns them a higher probability. And the higher\nthe probability, the lower the perplexity (since as Eq. 3.15 showed, perplexity is\nrelated inversely to the probability of the test sequence according to the model). So\na lower perplexity tells us that a language model is a better predictor of the test set.\nNote that in computing perplexities, the language model must be constructed\nwithout any knowledge of the test set, or else the perplexity will be arti\ufb01cially low.\nAnd the perplexity of two language models is only comparable if they use identical\nvocabularies.\nAn (intrinsic) improvement in perplexity does not guarantee an (extrinsic) im-\nprovement in the performance of a language processing task like speech recognition\nor machine translation. Nonetheless, because perplexity usually correlates with task\nimprovements, it is commonly used as a convenient evaluation metric. Still, when\npossible a model\u2019s improvement in perplexity should be con\ufb01rmed by an end-to-end\nevaluation on a real task.\n3.3.1 Perplexity as Weighted Average Branching Factor\nIt turns out that perplexity can also be thought of as the weighted average branch-\ning factor of a language. The branching factor of a language is the number of\npossible next words that can follow any word. For example consider a mini arti\ufb01cial\nlanguage that is deterministic (no probabilities), any word can follow any word, and\nwhose vocabulary consists of only three colors:\nL=fred;blue;greeng (3.18)\nThe branching factor of this language is 3.\nNow let\u2019s make a probabilistic version of the same LM, let\u2019s call it A, where each\nword follows each other with equal probability1\n3(it was trained on a training set with\nequal counts for the 3 colors), and a test set T= \u201cred red red red blue \u201d.\nLet\u2019s \ufb01rst convince ourselves that if we compute the perplexity of this arti\ufb01cial\ndigit language on this test set (or any such test set) we indeed get 3. By Eq. 3.15, the\n2For example if we use both begin and end tokens, we would include the end-of-sentence marker \nbut not the beginning-of-sentence marker in our count of N; This is because the end-sentence token is\nfollowed directly by the begin-sentence token with probability almost 1, so we don\u2019t want the probability\nof that fake transition to in\ufb02uence our perplexity. 42 CHAPTER 3 \u2022 N- GRAM LANGUAGE MODELS\nperplexity of AonTis:\nperplexityA(T) = PA(red red red red blue )\u00001\n5\n= \u00121\n3\u00135!\u00001\n5\n=\u00121\n3\u0013\u00001\n=3 (3.19)\nBut now suppose redwas very likely in the training set a different LM B, and so B\nhas the following probabilities:\nP(red) =0:8P(green ) =0:1P(blue) =0:1 (3.20)\nWe should expect the perplexity of the same test set red red red red blue for\nlanguage model Bto be lower since most of the time the next color will be red, which\nis very predictable, i.e. has a high probability. So the probability of the test set will\nbe higher, and since perplexity is inversely related to probability, the perplexity will\nbe lower. Thus, although the branching factor is still 3, the perplexity or weighted\nbranching factor is smaller:\nperplexityB(T) = PB(red red red red blue )\u00001=5\n=0:04096\u00001\n5\n=0:527\u00001=1:89 (3.21)\n3.4 Sampling sentences from a language model\n010.06the.060.03of0.02a0.02toin.09.11.13.15\u2026however(p=0.0003)polyphonicp=0.0000018\u20260.02.66.99\u2026\nFigure 3.3 A visualization of the sampling distribution for sampling sentences by repeat-\nedly sampling unigrams. The blue bar represents the relative frequency of each word (we\u2019ve\nordered them from most frequent to least frequent, but the choice of order is arbitrary). The\nnumber line shows the cumulative probabilities. If we choose a random number between 0\nand 1, it will fall in an interval corresponding to some word. The expectation for the random\nnumber to fall in the larger intervals of one of the frequent words ( the,of,a) is much higher\nthan in the smaller interval of one of the rare words ( polyphonic ).\nOne important way to visualize what kind of knowledge a language model em-\nbodies is to sample from it. Sampling from a distribution means to choose random sampling\npoints according to their likelihood. Thus sampling from a language model\u2014which\nrepresents a distribution over sentences\u2014means to generate some sentences, choos-\ning each sentence according to its likelihood as de\ufb01ned by the model. Thus we are\nmore likely to generate sentences that the model thinks have a high probability and\nless likely to generate sentences that the model thinks have a low probability. 3.5 \u2022 G ENERALIZING VS .OVERFITTING THE TRAINING SET 43\nThis technique of visualizing a language model by sampling was \ufb01rst suggested\nvery early on by Shannon (1948) and Miller and Selfridge (1950). It\u2019s simplest to\nvisualize how this works for the unigram case. Imagine all the words of the English\nlanguage covering the number line between 0 and 1, each word covering an interval\nproportional to its frequency. Fig. 3.3 shows a visualization, using a unigram LM\ncomputed from the text of this book. We choose a random value between 0 and 1,\n\ufb01nd that point on the probability line, and print the word whose interval includes this\nchosen value. We continue choosing random numbers and generating words until\nwe randomly generate the sentence-\ufb01nal token .\nWe can use the same technique to generate bigrams by \ufb01rst generating a ran-\ndom bigram that starts with (according to its bigram probability). Let\u2019s say the\nsecond word of that bigram is w. We next choose a random bigram starting with w\n(again, drawn according to its bigram probability), and so on.\n3.5 Generalizing vs. over\ufb01tting the training set\nThe n-gram model, like many statistical models, is dependent on the training corpus.\nOne implication of this is that the probabilities often encode speci\ufb01c facts about a\ngiven training corpus. Another implication is that n-grams do a better and better job\nof modeling the training corpus as we increase the value of N.\nWe can use the sampling method from the prior section to visualize both of\nthese facts! To give an intuition for the increasing power of higher-order n-grams,\nFig. 3.4 shows random sentences generated from unigram, bigram, trigram, and 4-\ngram models trained on Shakespeare\u2019s works.\n1\u2013To him swallowed confess hear both. Which. Of save on trail for are ay device and\nrote life have\ngram \u2013Hill he late speaks; or! a more to leg less \ufb01rst you enter\n2\u2013Why dost stand forth thy canopy, forsooth; he is this palpable hit the King Henry. Live\nking. Follow.\ngram \u2013What means, sir. I confess she? then all sorts, he is trim, captain.\n3\u2013Fly, and will rid me these news of price. Therefore the sadness of parting, as they say,\n\u2019tis done.\ngram \u2013This shall forbid it should be branded, if renown made it empty.\n4\u2013King Henry. What! I will go seek the traitor Gloucester. Exeunt some of the watch. A\ngreat banquet serv\u2019d in;\ngram \u2013It cannot be but so.\nFigure 3.4 Eight sentences randomly generated from four n-grams computed from Shakespeare\u2019s works. All\ncharacters were mapped to lower-case and punctuation marks were treated as words. Output is hand-corrected\nfor capitalization to improve readability.\nThe longer the context, the more coherent the sentences. The unigram sen-\ntences show no coherent relation between words nor any sentence-\ufb01nal punctua-\ntion. The bigram sentences have some local word-to-word coherence (especially\nconsidering punctuation as words). The trigram sentences are beginning to look a\nlot like Shakespeare. Indeed, the 4-gram sentences look a little too much like Shake-\nspeare. The words It cannot be but so are directly from King John . This is because,\nnot to put the knock on Shakespeare, his oeuvre is not very large as corpora go 44 CHAPTER 3 \u2022 N- GRAM LANGUAGE MODELS\n(N=884;647;V=29;066), and our n-gram probability matrices are ridiculously\nsparse. There are V2=844;000;000 possible bigrams alone, and the number of\npossible 4-grams is V4=7\u00021017. Thus, once the generator has chosen the \ufb01rst\n3-gram ( It cannot be ), there are only seven possible next words for the 4th element\n(but,I,that,thus,this, and the period).\nTo get an idea of the dependence on the training set, let\u2019s look at LMs trained on a\ncompletely different corpus: the Wall Street Journal (WSJ) newspaper. Shakespeare\nand the WSJ are both English, so we might have expected some overlap between our\nn-grams for the two genres. Fig. 3.5 shows sentences generated by unigram, bigram,\nand trigram grammars trained on 40 million words from WSJ.\n1Months the my and issue of year foreign new exchange\u2019s september\nwere recession exchange new endorsed a acquire to six executivesgram\n2Last December through the way to preserve the Hudson corporation N.\nB. E. C. Taylor would seem to complete the major central planners one\ngram point \ufb01ve percent of U. S. E. has already old M. X. corporation of living\non information such as more frequently \ufb01shing to keep her\n3They also point to ninety nine point six billion dollars from two hundred\nfour oh six three percent of the rates of interest stores as Mexico and\ngram Brazil on market conditions\nFigure 3.5 Three sentences randomly generated from three n-gram models computed from\n40 million words of the Wall Street Journal , lower-casing all characters and treating punctua-\ntion as words. Output was then hand-corrected for capitalization to improve readability.\nCompare these examples to the pseudo-Shakespeare in Fig. 3.4. While they both\nmodel \u201cEnglish-like sentences\u201d, there is no overlap in the generated sentences, and\nlittle overlap even in small phrases. Statistical models are pretty useless as predictors\nif the training sets and the test sets are as different as Shakespeare and the WSJ.\nHow should we deal with this problem when we build n-gram models? One step\nis to be sure to use a training corpus that has a similar genre to whatever task we are\ntrying to accomplish. To build a language model for translating legal documents,\nwe need a training corpus of legal documents. To build a language model for a\nquestion-answering system, we need a training corpus of questions.\nIt is equally important to get training data in the appropriate dialect orvariety ,\nespecially when processing social media posts or spoken transcripts. For exam-\nple some tweets will use features of African American English (AAE)\u2014 the name\nfor the many variations of language used in African American communities (King,\n2020). Such features can include words like \ufb01nna \u2014an auxiliary verb that marks\nimmediate future tense \u2014that don\u2019t occur in other varieties, or spellings like denfor\nthen, in tweets like this one (Blodgett and O\u2019Connor, 2017):\n(3.22) Bored af den my phone \ufb01nna die!!!\nwhile tweets from English-based languages like Nigerian Pidgin have markedly dif-\nferent vocabulary and n-gram patterns from American English (Jurgens et al., 2017):\n(3.23) @username R u a wizard or wat gan sef: in d mornin - u tweet, afternoon - u\ntweet, nyt gan u dey tweet. beta get ur IT placement wiv twitter\nIs it possible for the testset nonetheless to have a word we have never seen be-\nfore? What happens if the word Jurafsky never occurs in our training set, but pops\nup in the test set? The answer is that although words might be unseen, we actu-\nally run our NLP algorithms not on words but on subword tokens . With subword 3.6 \u2022 S MOOTHING , INTERPOLATION ,AND BACKOFF 45\ntokenization (like the BPE algorithm of Chapter 2) any word can be modeled as a\nsequence of known smaller subwords, if necessary by a sequence of individual let-\nters. So although for convenience we\u2019ve been referring to words in this chapter, the\nlanguage model vocabulary is actually the set of tokens rather than words, and the\ntest set can never contain unseen tokens.\n3.6 Smoothing, Interpolation, and Backoff\nThere is a problem with using maximum likelihood estimates for probabilities: any\n\ufb01nite training corpus will be missing some perfectly acceptable English word se-\nquences. That is, cases where a particular n-gram never occurs in the training data\nbut appears in the test set. Perhaps our training corpus has the words ruby and\nslippers in it but just happens not to have the phrase ruby slippers .\nThese unseen sequences or zeros \u2014sequences that don\u2019t occur in the training set zeros\nbut do occur in the test set\u2014are a problem for two reasons. First, their presence\nmeans we are underestimating the probability of word sequences that might occur,\nwhich hurts the performance of any application we want to run on this data. Second,\nif the probability of any word in the test set is 0, the probability of the whole test\nset is 0. Perplexity is de\ufb01ned based on the inverse probability of the test set. Thus\nif some words in context have zero probability, we can\u2019t compute perplexity at all,\nsince we can\u2019t divide by 0!\nThe standard way to deal with putative \u201czero probability n-grams\u201d that should re-\nally have some non-zero probability is called smoothing ordiscounting . Smoothing smoothing\ndiscounting algorithms shave off a bit of probability mass from some more frequent events and\ngive it to unseen events. Here we\u2019ll introduce some simple smoothing algorithms:\nLaplace (add-one) smoothing ,stupid backoff , and n-gram interpolation .\n3.6.1 Laplace Smoothing\nThe simplest way to do smoothing is to add one to all the n-gram counts, before\nwe normalize them into probabilities. All the counts that used to be zero will now\nhave a count of 1, the counts of 1 will be 2, and so on. This algorithm is called\nLaplace smoothing . Laplace smoothing does not perform well enough to be usedLaplace\nsmoothing\nin modern n-gram models, but it usefully introduces many of the concepts that we\nsee in other smoothing algorithms, gives a useful baseline, and is also a practical\nsmoothing algorithm for other tasks like text classi\ufb01cation (Chapter 4).\nLet\u2019s start with the application of Laplace smoothing to unigram probabilities.\nRecall that the unsmoothed maximum likelihood estimate of the unigram probability\nof the word wiis its count cinormalized by the total number of word tokens N:\nP(wi) =ci\nN\nLaplace smoothing merely adds one to each count (hence its alternate name add-\nonesmoothing). Since there are Vwords in the vocabulary and each one was in- add-one\ncremented, we also need to adjust the denominator to take into account the extra V\nobservations. (What happens to our Pvalues if we don\u2019t increase the denominator?)\nPLaplace (wi) =ci+1\nN+V(3.24) 46 CHAPTER 3 \u2022 N- GRAM LANGUAGE MODELS\nInstead of changing both the numerator and denominator, it is convenient to describe\nhow a smoothing algorithm affects the numerator, by de\ufb01ning an adjusted count c\u0003.\nThis adjusted count is easier to compare directly with the MLE counts and can be\nturned into a probability like an MLE count by normalizing by N. To de\ufb01ne this\ncount, since we are only changing the numerator in addition to adding 1 we\u2019ll also\nneed to multiply by a normalization factorN\nN+V:\nc\u0003\ni= (ci+1)N\nN+V(3.25)\nWe can now turn c\u0003\niinto a probability P\u0003\niby normalizing by N.\nA related way to view smoothing is as discounting (lowering) some non-zero discounting\ncounts in order to get the probability mass that will be assigned to the zero counts.\nThus, instead of referring to the discounted counts c\u0003, we might describe a smooth-\ning algorithm in terms of a relative discount di, the ratio of the discounted counts to discount\nthe original counts:\ndi=c\u0003\ni\nci\nNow that we have the intuition for the unigram case, let\u2019s smooth our Berkeley\nRestaurant Project bigrams. Figure 3.6 shows the add-one smoothed counts for the\nbigrams in Fig. 3.1.\ni want to eat chinese food lunch spend\ni 6 828 1 10 1 1 1 3\nwant 3 1 609 2 7 7 6 2\nto 3 1 5 687 3 1 7 212\neat 1 1 3 1 17 3 43 1\nchinese 2 1 1 1 1 83 2 1\nfood 16 1 16 1 2 5 1 1\nlunch 3 1 1 1 1 2 1 1\nspend 2 1 2 1 1 1 1 1\nFigure 3.6 Add-one smoothed bigram counts for eight of the words (out of V=1446) in\nthe Berkeley Restaurant Project corpus of 9332 sentences. Previously-zero counts are in gray.\nFigure 3.7 shows the add-one smoothed probabilities for the bigrams in Fig. 3.2.\nRecall that normal bigram probabilities are computed by normalizing each row of\ncounts by the unigram count:\nPMLE(wnjwn\u00001) =C(wn\u00001wn)\nC(wn\u00001)(3.26)\nFor add-one smoothed bigram counts, we need to augment the unigram count by the\nnumber of total word types in the vocabulary V:\nPLaplace (wnjwn\u00001) =C(wn\u00001wn)+1P\nw(C(wn\u00001w)+1)=C(wn\u00001wn)+1\nC(wn\u00001)+V(3.27)\nThus, each of the unigram counts given in the previous section will need to be aug-\nmented by V=1446. The result is the smoothed bigram probabilities in Fig. 3.7.\nIt is often convenient to reconstruct the count matrix so we can see how much a\nsmoothing algorithm has changed the original counts. These adjusted counts can be 3.6 \u2022 S MOOTHING , INTERPOLATION ,AND BACKOFF 47\ni want to eat chinese food lunch spend\ni 0.0015 0.21 0.00025 0.0025 0.00025 0.00025 0.00025 0.00075\nwant 0.0013 0.00042 0.26 0.00084 0.0029 0.0029 0.0025 0.00084\nto 0.00078 0.00026 0.0013 0.18 0.00078 0.00026 0.0018 0.055\neat 0.00046 0.00046 0.0014 0.00046 0.0078 0.0014 0.02 0.00046\nchinese 0.0012 0.00062 0.00062 0.00062 0.00062 0.052 0.0012 0.00062\nfood 0.0063 0.00039 0.0063 0.00039 0.00079 0.002 0.00039 0.00039\nlunch 0.0017 0.00056 0.00056 0.00056 0.00056 0.0011 0.00056 0.00056\nspend 0.0012 0.00058 0.0012 0.00058 0.00058 0.00058 0.00058 0.00058\nFigure 3.7 Add-one smoothed bigram probabilities for eight of the words (out of V=1446) in the BeRP\ncorpus of 9332 sentences. Previously-zero probabilities are in gray.\ni want to eat chinese food lunch spend\ni 3.8 527 0.64 6.4 0.64 0.64 0.64 1.9\nwant 1.2 0.39 238 0.78 2.7 2.7 2.3 0.78\nto 1.9 0.63 3.1 430 1.9 0.63 4.4 133\neat 0.34 0.34 1 0.34 5.8 1 15 0.34\nchinese 0.2 0.098 0.098 0.098 0.098 8.2 0.2 0.098\nfood 6.9 0.43 6.9 0.43 0.86 2.2 0.43 0.43\nlunch 0.57 0.19 0.19 0.19 0.19 0.38 0.19 0.19\nspend 0.32 0.16 0.32 0.16 0.16 0.16 0.16 0.16\nFigure 3.8 Add-one reconstituted counts for eight words (of V=1446) in the BeRP corpus\nof 9332 sentences. Previously-zero counts are in gray.\ncomputed by Eq. 3.28. Figure 3.8 shows the reconstructed counts.\nc\u0003(wn\u00001wn) =[C(wn\u00001wn)+1]\u0002C(wn\u00001)\nC(wn\u00001)+V(3.28)\nNote that add-one smoothing has made a very big change to the counts. Com-\nparing Fig. 3.8 to the original counts in Fig. 3.1, we can see that C(want to )changed\nfrom 608 to 238! We can see this in probability space as well: P(tojwant)decreases\nfrom 0.66 in the unsmoothed case to 0.26 in the smoothed case. Looking at the dis-\ncount d(the ratio between new and old counts) shows us how strikingly the counts\nfor each pre\ufb01x word have been reduced; the discount for the bigram want to is 0.39,\nwhile the discount for Chinese food is 0.10, a factor of 10! The sharp change occurs\nbecause too much probability mass is moved to all the zeros.\n3.6.2 Add-k smoothing\nOne alternative to add-one smoothing is to move a bit less of the probability mass\nfrom the seen to the unseen events. Instead of adding 1 to each count, we add a\nfractional count k(0.5? 0.01?). This algorithm is therefore called add-k smoothing . add-k\nP\u0003\nAdd-k(wnjwn\u00001) =C(wn\u00001wn)+k\nC(wn\u00001)+kV(3.29)\nAdd-k smoothing requires that we have a method for choosing k; this can be\ndone, for example, by optimizing on a devset . Although add-k is useful for some\ntasks (including text classi\ufb01cation), it turns out that it still doesn\u2019t work well for\nlanguage modeling, generating counts with poor variances and often inappropriate\ndiscounts (Gale and Church, 1994). 48 CHAPTER 3 \u2022 N- GRAM LANGUAGE MODELS\n3.6.3 Language Model Interpolation\nThere is an alternative source of knowledge we can draw on to solve the problem\nof zero frequency n-grams. If we are trying to compute P(wnjwn\u00002wn\u00001)but we\nhave no examples of a particular trigram wn\u00002wn\u00001wn, we can instead estimate its\nprobability by using the bigram probability P(wnjwn\u00001). Similarly, if we don\u2019t have\ncounts to compute P(wnjwn\u00001), we can look to the unigram P(wn). In other words,\nsometimes using less context can help us generalize more for contexts that the model\nhasn\u2019t learned much about.\nThe most common way to use this n-gram hierarchy is called interpolation : interpolation\ncomputing a new probability by interpolating (weighting and combining) the tri-\ngram, bigram, and unigram probabilities.3In simple linear interpolation, we com-\nbine different order n-grams by linearly interpolating them. Thus, we estimate the\ntrigram probability P(wnjwn\u00002wn\u00001)by mixing together the unigram, bigram, and\ntrigram probabilities, each weighted by a l:\n\u02c6P(wnjwn\u00002wn\u00001) = l1P(wn)\n+l2P(wnjwn\u00001)\n+l3P(wnjwn\u00002wn\u00001) (3.30)\nThels must sum to 1, making Eq. 3.30 equivalent to a weighted average. In a\nslightly more sophisticated version of linear interpolation, each lweight is com-\nputed by conditioning on the context. This way, if we have particularly accurate\ncounts for a particular bigram, we assume that the counts of the trigrams based on\nthis bigram will be more trustworthy, so we can make the ls for those trigrams\nhigher and thus give that trigram more weight in the interpolation. Equation 3.31\nshows the equation for interpolation with context-conditioned weights, where each\nlambda takes an argument that is the two prior word context:\n\u02c6P(wnjwn\u00002wn\u00001) = l1(wn\u00002:n\u00001)P(wn)\n+l2(wn\u00002:n\u00001)P(wnjwn\u00001)\n+l3(wn\u00002:n\u00001)P(wnjwn\u00002wn\u00001) (3.31)\nHow are these lvalues set? Both the simple interpolation and conditional interpo-\nlation ls are learned from a held-out corpus. A held-out corpus is an additional held-out\ntraining corpus, so-called because we hold it out from the training data, that we use\nto set these lvalues.4We do so by choosing the lvalues that maximize the likeli-\nhood of the held-out corpus. That is, we \ufb01x the n-gram probabilities and then search\nfor the lvalues that\u2014when plugged into Eq. 3.30\u2014give us the highest probability\nof the held-out set. There are various ways to \ufb01nd this optimal set of ls. One way\nis to use the EMalgorithm, an iterative learning algorithm that converges on locally\noptimal ls (Jelinek and Mercer, 1980).\n3.6.4 Stupid Backoff\nAn alternative to interpolation is backoff . In a backoff model, if the n-gram we need backoff\n3We won\u2019t discuss the less-common alternative, called backoff , in which we use the trigram if the\nevidence is suf\ufb01cient for it, but if not we instead just use the bigram, otherwise the unigram. That is, we\nonly \u201cback off\u201d to a lower-order n-gram if we have zero evidence for a higher-order n-gram.\n4Held-out corpora are generally used to set hyperparameters , which are special parameters, unlike\nregular counts that are learned from the training data; we\u2019ll discuss hyperparameters in Chapter 7. 3.7 \u2022 A DVANCED : PERPLEXITY \u2019SRELATION TO ENTROPY 49\nhas zero counts, we approximate it by backing off to the (n-1)-gram. We continue\nbacking off until we reach a history that has some counts. For a backoff model to\ngive a correct probability distribution, we have to discount the higher-order n-grams discount\nto save some probability mass for the lower order n-grams. In practice, instead of\ndiscounting, it\u2019s common to use a much simpler non-discounted backoff algorithm\ncalled stupid backoff (Brants et al., 2007). stupid backoff\nStupid backoff gives up the idea of trying to make the language model a true\nprobability distribution. There is no discounting of the higher-order probabilities. If\na higher-order n-gram has a zero count, we simply backoff to a lower order n-gram,\nweighed by a \ufb01xed (context-independent) weight. This algorithm does not produce\na probability distribution, so we\u2019ll follow Brants et al. (2007) in referring to it as S:\nS(wijwi\u0000N+1:i\u00001) =8\n<\n:count (wi\u0000N+1:i)\ncount (wi\u0000N+1:i\u00001)if count (wi\u0000N+1:i)>0\nlS(wijwi\u0000N+2:i\u00001)otherwise(3.32)\nThe backoff terminates in the unigram, which has score S(w) =count (w)\nN. Brants et al.\n(2007) \ufb01nd that a value of 0.4 worked well for l.\n3.7 Advanced: Perplexity\u2019s Relation to Entropy\nWe introduced perplexity in Section 3.3 as a way to evaluate n-gram models on\na test set. A better n-gram model is one that assigns a higher probability to the\ntest data, and perplexity is a normalized version of the probability of the test set.\nThe perplexity measure actually arises from the information-theoretic concept of\ncross-entropy, which explains otherwise mysterious properties of perplexity (why\nthe inverse probability, for example?) and its relationship to entropy. Entropy is a Entropy\nmeasure of information. Given a random variable Xranging over whatever we are\npredicting (words, letters, parts of speech), the set of which we\u2019ll call c, and with a\nparticular probability function, call it p(x), the entropy of the random variable Xis:\nH(X) =\u0000X\nx2cp(x)log2p(x) (3.33)\nThe log can, in principle, be computed in any base. If we use log base 2, the\nresulting value of entropy will be measured in bits.\nOne intuitive way to think about entropy is as a lower bound on the number of\nbits it would take to encode a certain decision or piece of information in the optimal\ncoding scheme. Consider an example from the standard information theory textbook\nCover and Thomas (1991). Imagine that we want to place a bet on a horse race but\nit is too far to go all the way to Yonkers Racetrack, so we\u2019d like to send a short\nmessage to the bookie to tell him which of the eight horses to bet on. One way to\nencode this message is just to use the binary representation of the horse\u2019s number\nas the code; thus, horse 1 would be 001, horse 2010, horse 3011, and so on, with\nhorse 8 coded as 000. If we spend the whole day betting and each horse is coded\nwith 3 bits, on average we would be sending 3 bits per race.\nCan we do better? Suppose that the spread is the actual distribution of the bets\nplaced and that we represent it as the prior probability of each horse as follows: 50 CHAPTER 3 \u2022 N- GRAM LANGUAGE MODELS\nHorse 11\n2Horse 51\n64\nHorse 21\n4Horse 61\n64\nHorse 31\n8Horse 71\n64\nHorse 41\n16Horse 81\n64\nThe entropy of the random variable Xthat ranges over horses gives us a lower\nbound on the number of bits and is\nH(X) =\u0000i=8X\ni=1p(i)log2p(i)\n=\u00001\n2log21\n2\u00001\n4log21\n4\u00001\n8log21\n8\u00001\n16log21\n16\u00004(1\n64log21\n64)\n=2 bits (3.34)\nA code that averages 2 bits per race can be built with short encodings for more\nprobable horses, and longer encodings for less probable horses. For example, we\ncould encode the most likely horse with the code 0, and the remaining horses as 10,\nthen110,1110 ,111100 ,111101 ,111110 , and111111 .\nWhat if the horses are equally likely? We saw above that if we used an equal-\nlength binary code for the horse numbers, each horse took 3 bits to code, so the\naverage was 3. Is the entropy the same? In this case each horse would have a\nprobability of1\n8. The entropy of the choice of horses is then\nH(X) =\u0000i=8X\ni=11\n8log21\n8=\u0000log21\n8=3 bits (3.35)\nUntil now we have been computing the entropy of a single variable. But most of\nwhat we will use entropy for involves sequences . For a grammar, for example, we\nwill be computing the entropy of some sequence of words W=fw1;w2;:::; wng.\nOne way to do this is to have a variable that ranges over sequences of words. For\nexample we can compute the entropy of a random variable that ranges over all se-\nquences of words of length nin some language Las follows:\nH(w1;w2;:::; wn) =\u0000X\nw1:n2Lp(w1:n)logp(w1:n) (3.36)\nWe could de\ufb01ne the entropy rate (we could also think of this as the per-word entropy rate\nentropy ) as the entropy of this sequence divided by the number of words:\n1\nnH(w1:n) =\u00001\nnX\nw1:n2Lp(w1:n)logp(w1:n) (3.37)\nBut to measure the true entropy of a language, we need to consider sequences of\nin\ufb01nite length. If we think of a language as a stochastic process Lthat produces a\nsequence of words, and allow Wto represent the sequence of words w1;:::; wn, then\nL\u2019s entropy rate H(L)is de\ufb01ned as\nH(L) = lim\nn!\u00a51\nnH(w1:n)\n=\u0000lim\nn!\u00a51\nnX\nW2Lp(w1:n)logp(w1:n) (3.38) 3.7 \u2022 A DVANCED : PERPLEXITY \u2019SRELATION TO ENTROPY 51\nThe Shannon-McMillan-Breiman theorem (Algoet and Cover 1988, Cover and Thomas\n1991) states that if the language is regular in certain ways (to be exact, if it is both\nstationary and ergodic),\nH(L) =lim\nn!\u00a5\u00001\nnlogp(w1:n) (3.39)\nThat is, we can take a single sequence that is long enough instead of summing over\nall possible sequences. The intuition of the Shannon-McMillan-Breiman theorem\nis that a long-enough sequence of words will contain in it many other shorter se-\nquences and that each of these shorter sequences will reoccur in the longer sequence\naccording to their probabilities.\nA stochastic process is said to be stationary if the probabilities it assigns to a Stationary\nsequence are invariant with respect to shifts in the time index. In other words, the\nprobability distribution for words at time tis the same as the probability distribution\nat time t+1. Markov models, and hence n-grams, are stationary. For example, in\na bigram, Piis dependent only on Pi\u00001. So if we shift our time index by x,Pi+xis\nstill dependent on Pi+x\u00001. But natural language is not stationary, since as we show\nin Appendix D, the probability of upcoming words can be dependent on events that\nwere arbitrarily distant and time dependent. Thus, our statistical models only give\nan approximation to the correct distributions and entropies of natural language.\nTo summarize, by making some incorrect but convenient simplifying assump-\ntions, we can compute the entropy of some stochastic process by taking a very long\nsample of the output and computing its average log probability.\nNow we are ready to introduce cross-entropy . The cross-entropy is useful when cross-entropy\nwe don\u2019t know the actual probability distribution pthat generated some data. It\nallows us to use some m, which is a model of p(i.e., an approximation to p). The\ncross-entropy of monpis de\ufb01ned by\nH(p;m) =lim\nn!\u00a5\u00001\nnX\nW2Lp(w1;:::; wn)logm(w1;:::; wn) (3.40)\nThat is, we draw sequences according to the probability distribution p, but sum the\nlog of their probabilities according to m.\nAgain, following the Shannon-McMillan-Breiman theorem, for a stationary er-\ngodic process:\nH(p;m) =lim\nn!\u00a5\u00001\nnlogm(w1w2:::wn) (3.41)\nThis means that, as for entropy, we can estimate the cross-entropy of a model m\non some distribution pby taking a single sequence that is long enough instead of\nsumming over all possible sequences.\nWhat makes the cross-entropy useful is that the cross-entropy H(p;m)is an up-\nper bound on the entropy H(p). For any model m:\nH(p)\u0014H(p;m) (3.42)\nThis means that we can use some simpli\ufb01ed model mto help estimate the true en-\ntropy of a sequence of symbols drawn according to probability p. The more accurate\nmis, the closer the cross-entropy H(p;m)will be to the true entropy H(p). Thus,\nthe difference between H(p;m)andH(p)is a measure of how accurate a model is.\nBetween two models m1andm2, the more accurate model will be the one with the 52 CHAPTER 3 \u2022 N- GRAM LANGUAGE MODELS\nlower cross-entropy. (The cross-entropy can never be lower than the true entropy, so\na model cannot err by underestimating the true entropy.)\nWe are \ufb01nally ready to see the relation between perplexity and cross-entropy\nas we saw it in Eq. 3.41. Cross-entropy is de\ufb01ned in the limit as the length of the\nobserved word sequence goes to in\ufb01nity. We approximate this cross-entropy by\nrelying on a (suf\ufb01ciently long) sequence of \ufb01xed length. This approximation to the\ncross-entropy of a model M=P(wijwi\u0000N+1:i\u00001)on a sequence of words Wis\nH(W) =\u00001\nNlogP(w1w2:::wN) (3.43)\nTheperplexity of a model Pon a sequence of words Wis now formally de\ufb01ned as perplexity\n2 raised to the power of this cross-entropy:\nPerplexity (W) = 2H(W)\n=P(w1w2:::wN)\u00001\nN\n=Ns\n1\nP(w1w2:::wN)\n3.8 Summary\nThis chapter introduced language modeling via the n-gram model, a classic model\nthat allows us to introduce many of the basic concepts in language modeling.\n\u2022 Language models offer a way to assign a probability to a sentence or other\nsequence of words or tokens, and to predict a word or token from preceding\nwords or tokens.\n\u2022N-grams are perhaps the simplest kind of language model. They are Markov\nmodels that estimate words from a \ufb01xed window of previous words. N-gram\nmodels can be trained by counting in a training corpus and normalizing the\ncounts (the maximum likelihood estimate ).\n\u2022 N-gram language models can be evaluated on a test set using perplexity.\n\u2022 The perplexity of a test set according to a language model is a function of\nthe probability of the test set: the inverse test set probability according to the\nmodel, normalized by the length.\n\u2022Sampling from a language model means to generate some sentences, choos-\ning each sentence according to its likelihood as de\ufb01ned by the model.\n\u2022Smoothing algorithms provide a way to estimate probabilities for events that\nwere unseen in training. Commonly used smoothing algorithms for n-grams\ninclude add-1 smoothing, or rely on lower-order n-gram counts through inter-\npolation .\nBibliographical and Historical Notes\nThe underlying mathematics of the n-gram was \ufb01rst proposed by Markov (1913),\nwho used what are now called Markov chains (bigrams and trigrams) to predict\nwhether an upcoming letter in Pushkin\u2019s Eugene Onegin would be a vowel or a con-\nsonant. Markov classi\ufb01ed 20,000 letters as V or C and computed the bigram and BIBLIOGRAPHICAL AND HISTORICAL NOTES 53\ntrigram probability that a given letter would be a vowel given the previous one or\ntwo letters. Shannon (1948) applied n-grams to compute approximations to English\nword sequences. Based on Shannon\u2019s work, Markov models were commonly used in\nengineering, linguistic, and psychological work on modeling word sequences by the\n1950s. In a series of extremely in\ufb02uential papers starting with Chomsky (1956) and\nincluding Chomsky (1957) and Miller and Chomsky (1963), Noam Chomsky argued\nthat \u201c\ufb01nite-state Markov processes\u201d, while a possibly useful engineering heuristic,\nwere incapable of being a complete cognitive model of human grammatical knowl-\nedge. These arguments led many linguists and computational linguists to ignore\nwork in statistical modeling for decades.\nThe resurgence of n-gram language models came from Fred Jelinek and col-\nleagues at the IBM Thomas J. Watson Research Center, who were in\ufb02uenced by\nShannon, and James Baker at CMU, who was in\ufb02uenced by the prior, classi\ufb01ed\nwork of Leonard Baum and colleagues on these topics at labs like the US Institute\nfor Defense SAnalyses (IDA) after they were declassi\ufb01ed. Independently these two\nlabs successfully used n-grams in their speech recognition systems at the same time\n(Baker 1975b, Jelinek et al. 1975, Baker 1975a, Bahl et al. 1983, Jelinek 1990). The\nterms \u201clanguage model\u201d and \u201cperplexity\u201d were \ufb01rst used for this technology by the\nIBM group. Jelinek and his colleagues used the term language model in a pretty\nmodern way, to mean the entire set of linguistic in\ufb02uences on word sequence prob-\nabilities, including grammar, semantics, discourse, and even speaker characteristics,\nrather than just the particular n-gram model itself.\nAdd-one smoothing derives from Laplace\u2019s 1812 law of succession and was \ufb01rst\napplied as an engineering solution to the zero frequency problem by Jeffreys (1948)\nbased on an earlier Add-K suggestion by Johnson (1932). Problems with the add-\none algorithm are summarized in Gale and Church (1994).\nA wide variety of different language modeling and smoothing techniques were\nproposed in the 80s and 90s, including Good-Turing discounting\u2014\ufb01rst applied to the\nn-gram smoothing at IBM by Katz (N \u00b4adas 1984, Church and Gale 1991)\u2014 Witten-\nBell discounting (Witten and Bell, 1991), and varieties of class-based n-gram mod-class-based\nn-gram\nels that used information about word classes. Starting in the late 1990s, Chen and\nGoodman performed a number of carefully controlled experiments comparing dif-\nferent algorithms and parameters (Chen and Goodman 1999, Goodman 2006, inter\nalia). They showed the advantages of Modi\ufb01ed Interpolated Kneser-Ney , which\nbecame the standard baseline for n-gram language modeling around the turn of the\ncentury, especially because they showed that caches and class-based models pro-\nvided only minor additional improvement. SRILM (Stolcke, 2002) and KenLM\n(Hea\ufb01eld 2011, Hea\ufb01eld et al. 2013) are publicly available toolkits for building n-\ngram language models.\nLarge language models are based on neural networks rather than n-grams, en-\nabling them to solve the two major problems with n-grams: (1) the number of param-\neters increases exponentially as the n-gram order increases, and (2) n-grams have no\nway to generalize from training examples to test set examples unless they use iden-\ntical words. Neural language models instead project words into a continuous space\nin which words with similar contexts have similar representations. We\u2019ll introduce\ntransformer-based large language models in Chapter 9, along the way introducing\nfeedforward language models (Bengio et al. 2006, Schwenk 2007) in Chapter 7 and\nrecurrent language models (Mikolov, 2012) in Chapter 8. 54 CHAPTER 3 \u2022 N- GRAM LANGUAGE MODELS\nExercises\n3.1 Write out the equation for trigram probability estimation (modifying Eq. 3.11).\nNow write out all the non-zero trigram probabilities for the I am Sam corpus\non page 35.\n3.2 Calculate the probability of the sentence i want chinese food . Give two\nprobabilities, one using Fig. 3.2 and the \u2018useful probabilities\u2019 just below it on\npage 37, and another using the add-1 smoothed table in Fig. 3.7. Assume the\nadditional add-1 smoothed probabilities P(i| ) =0:19 and P(|food ) =\n0:40.\n3.3 Which of the two probabilities you computed in the previous exercise is higher,\nunsmoothed or smoothed? Explain why.\n3.4 We are given the following corpus, modi\ufb01ed from the one in the chapter:\n I am Sam \n Sam I am \n I am Sam \n I do not like green eggs and Sam \nUsing a bigram language model with add-one smoothing, what is P(Sam j\nam)? Include and in your counts just like any other token.\n3.5 Suppose we didn\u2019t use the end-symbol . Train an unsmoothed bigram\ngrammar on the following training corpus without using the end-symbol :\n a b\n b b\n b a\n a a\nDemonstrate that your bigram model does not assign a single probability dis-\ntribution across all sentence lengths by showing that the sum of the probability\nof the four possible 2 word sentences over the alphabet fa,bgis 1.0, and the\nsum of the probability of all possible 3 word sentences over the alphabet fa,bg\nis also 1.0.\n3.6 Suppose we train a trigram language model with add-one smoothing on a\ngiven corpus. The corpus contains V word types. Express a formula for esti-\nmating P(w3jw1,w2), where w3 is a word which follows the bigram (w1,w2),\nin terms of various n-gram counts and V . Use the notation c(w1,w2,w3) to\ndenote the number of times that trigram (w1,w2,w3) occurs in the corpus, and\nso on for bigrams and unigrams.\n3.7 We are given the following corpus, modi\ufb01ed from the one in the chapter:\n I am Sam \n Sam I am \n I am Sam \n I do not like green eggs and Sam \nIf we use linear interpolation smoothing between a maximum-likelihood bi-\ngram model and a maximum-likelihood unigram model with l1=1\n2andl2=\n1\n2, what is P(Samjam)? Include and in your counts just like any\nother token.\n3.8 Write a program to compute unsmoothed unigrams and bigrams. EXERCISES 55\n3.9 Run your n-gram program on two different small corpora of your choice (you\nmight use email text or newsgroups). Now compare the statistics of the two\ncorpora. What are the differences in the most common unigrams between the\ntwo? How about interesting differences in bigrams?\n3.10 Add an option to your program to generate random sentences.\n3.11 Add an option to your program to compute the perplexity of a test set.\n3.12 You are given a training set of 100 numbers that consists of 91 zeros and 1\neach of the other digits 1-9. Now we see the following test set: 0 0 0 0 0 3 0 0\n0 0. What is the unigram perplexity? 56 CHAPTER 4 \u2022 N AIVE BAYES , TEXT CLASSIFICATION ,AND SENTIMENT\nCHAPTER\n4Naive Bayes, Text Classi\ufb01ca-\ntion, and Sentiment\nClassi\ufb01cation lies at the heart of both human and machine intelligence. Deciding\nwhat letter, word, or image has been presented to our senses, recognizing faces\nor voices, sorting mail, assigning grades to homeworks; these are all examples of\nassigning a category to an input. The potential challenges of this task are highlighted\nby the fabulist Jorge Luis Borges (1964), who imagined classifying animals into:\n(a) those that belong to the Emperor, (b) embalmed ones, (c) those that\nare trained, (d) suckling pigs, (e) mermaids, (f) fabulous ones, (g) stray\ndogs, (h) those that are included in this classi\ufb01cation, (i) those that\ntremble as if they were mad, (j) innumerable ones, (k) those drawn with\na very \ufb01ne camel\u2019s hair brush, (l) others, (m) those that have just broken\na \ufb02ower vase, (n) those that resemble \ufb02ies from a distance.\nMany language processing tasks involve classi\ufb01cation, although luckily our classes\nare much easier to de\ufb01ne than those of Borges. In this chapter we introduce the naive\nBayes algorithm and apply it to text categorization , the task of assigning a label ortext\ncategorization\ncategory to an entire text or document.\nWe focus on one common text categorization task, sentiment analysis , the ex-sentiment\nanalysis\ntraction of sentiment , the positive or negative orientation that a writer expresses\ntoward some object. A review of a movie, book, or product on the web expresses the\nauthor\u2019s sentiment toward the product, while an editorial or political text expresses\nsentiment toward a candidate or political action. Extracting consumer or public sen-\ntiment is thus relevant for \ufb01elds from marketing to politics.\nThe simplest version of sentiment analysis is a binary classi\ufb01cation task, and\nthe words of the review provide excellent cues. Consider, for example, the follow-\ning phrases extracted from positive and negative reviews of movies and restaurants.\nWords like great ,richly ,awesome , and pathetic , and awful andridiculously are very\ninformative cues:\n+...zany characters and richly applied satire, and some great plot twists\n\u0000It was pathetic. The worst part about it was the boxing scenes...\n+...awesome caramel sauce and sweet toasty almonds. I love this place!\n\u0000...awful pizza and ridiculously overpriced...\nSpam detection is another important commercial application, the binary clas- spam detection\nsi\ufb01cation task of assigning an email to one of the two classes spam ornot-spam .\nMany lexical and other features can be used to perform this classi\ufb01cation. For ex-\nample you might quite reasonably be suspicious of an email containing phrases like\n\u201conline pharmaceutical\u201d or \u201cWITHOUT ANY COST\u201d or \u201cDear Winner\u201d.\nAnother thing we might want to know about a text is the language it\u2019s written\nin. Texts on social media, for example, can be in any number of languages and\nwe\u2019ll need to apply different processing. The task of language id is thus the \ufb01rst language id\nstep in most language processing pipelines. Related text classi\ufb01cation tasks like au-\nthorship attribution \u2014 determining a text\u2019s author\u2014 are also relevant to the digitalauthorship\nattribution\nhumanities, social sciences, and forensic linguistics. 4.1 \u2022 N AIVE BAYES CLASSIFIERS 57\nFinally, one of the oldest tasks in text classi\ufb01cation is assigning a library sub-\nject category or topic label to a text. Deciding whether a research paper concerns\nepidemiology or instead, perhaps, embryology, is an important component of infor-\nmation retrieval. Various sets of subject categories exist, such as the MeSH (Medical\nSubject Headings) thesaurus. In fact, as we will see, subject category classi\ufb01cation\nis the task for which the naive Bayes algorithm was invented in 1961 Maron (1961).\nClassi\ufb01cation is essential for tasks below the level of the document as well.\nWe\u2019ve already seen period disambiguation (deciding if a period is the end of a sen-\ntence or part of a word), and word tokenization (deciding if a character should be\na word boundary). Even language modeling can be viewed as classi\ufb01cation: each\nword can be thought of as a class, and so predicting the next word is classifying the\ncontext-so-far into a class for each next word. A part-of-speech tagger (Chapter 17)\nclassi\ufb01es each occurrence of a word in a sentence as, e.g., a noun or a verb.\nThe goal of classi\ufb01cation is to take a single observation, extract some useful\nfeatures, and thereby classify the observation into one of a set of discrete classes.\nOne method for classifying text is to use rules handwritten by humans. Handwrit-\nten rule-based classi\ufb01ers can be components of state-of-the-art systems in language\nprocessing. But rules can be fragile, as situations or data change over time, and for\nsome tasks humans aren\u2019t necessarily good at coming up with the rules.\nThe most common way of doing text classi\ufb01cation in language processing is\ninstead via supervised machine learning , the subject of this chapter. In supervisedsupervised\nmachine\nlearninglearning, we have a data set of input observations, each associated with some correct\noutput (a \u2018supervision signal\u2019). The goal of the algorithm is to learn how to map\nfrom a new observation to a correct output.\nFormally, the task of supervised classi\ufb01cation is to take an input xand a \ufb01xed\nset of output classes Y=fy1;y2;:::;yMgand return a predicted class y2Y. For\ntext classi\ufb01cation, we\u2019ll sometimes talk about c(for \u201cclass\u201d) instead of yas our\noutput variable, and d(for \u201cdocument\u201d) instead of xas our input variable. In the\nsupervised situation we have a training set of Ndocuments that have each been hand-\nlabeled with a class: f(d1;c1);::::;(dN;cN)g. Our goal is to learn a classi\ufb01er that is\ncapable of mapping from a new document dto its correct class c2C, where Cis\nsome set of useful document classes. A probabilistic classi\ufb01er additionally will tell\nus the probability of the observation being in the class. This full distribution over\nthe classes can be useful information for downstream decisions; avoiding making\ndiscrete decisions early on can be useful when combining systems.\nMany kinds of machine learning algorithms are used to build classi\ufb01ers. This\nchapter introduces naive Bayes; the following one introduces logistic regression.\nThese exemplify two ways of doing classi\ufb01cation. Generative classi\ufb01ers like naive\nBayes build a model of how a class could generate some input data. Given an ob-\nservation, they return the class most likely to have generated the observation. Dis-\ncriminative classi\ufb01ers like logistic regression instead learn what features from the\ninput are most useful to discriminate between the different possible classes. While\ndiscriminative systems are often more accurate and hence more commonly used,\ngenerative classi\ufb01ers still have a role.\n4.1 Naive Bayes Classi\ufb01ers\nIn this section we introduce the multinomial naive Bayes classi\ufb01er , so called be-naive Bayes\nclassi\ufb01er\ncause it is a Bayesian classi\ufb01er that makes a simplifying (naive) assumption about 58 CHAPTER 4 \u2022 N AIVE BAYES , TEXT CLASSIFICATION ,AND SENTIMENT\nhow the features interact.\nThe intuition of the classi\ufb01er is shown in Fig. 4.1. We represent a text document\nas if it were a bag of words , that is, an unordered set of words with their position bag of words\nignored, keeping only their frequency in the document. In the example in the \ufb01gure,\ninstead of representing the word order in all the phrases like \u201cI love this movie\u201d and\n\u201cI would recommend it\u201d, we simply note that the word Ioccurred 5 times in the\nentire excerpt, the word it6 times, the words love,recommend , and movie once, and\nso on.\nititititititIIII\nIloverecommendmoviethethethetheto\ntotoand\nandandseenseenyetwouldwithwhowhimsical\nwhilewhenevertimessweetseveralscenessatiricalromanticofmanageshumorhavehappyfunfriendfairydialoguebutconventionsareanyoneadventurealwaysagainaboutI love this movie! It's sweet, but with satirical humor. The dialogue is great and the adventure scenes are fun... It manages to be whimsical and romantic while laughing at the conventions of the fairy tale genre. I would recommend it to just about anyone. I've seen it several times, and I'm always happy to see it again whenever I have a friend who hasn't seen it yet!it Ithetoandseenyetwouldwhimsicaltimessweetsatiricaladventuregenrefairyhumorhavegreat\u20266 54332111111111111\u2026\nFigure 4.1 Intuition of the multinomial naive Bayes classi\ufb01er applied to a movie review. The position of the\nwords is ignored (the bag-of-words assumption) and we make use of the frequency of each word.\nNaive Bayes is a probabilistic classi\ufb01er, meaning that for a document d, out of\nall classes c2Cthe classi\ufb01er returns the class \u02c6 cwhich has the maximum posterior\nprobability given the document. In Eq. 4.1 we use the hat notation \u02c6to mean \u201cour \u02c6\nestimate of the correct class\u201d, and we use argmax to mean an operation that selects argmax\nthe argument (in this case the class c) that maximizes a function (in this case the\nprobability P(cjd).\n\u02c6c=argmax\nc2CP(cjd) (4.1)\nThis idea of Bayesian inference has been known since the work of Bayes (1763),Bayesian\ninference\nand was \ufb01rst applied to text classi\ufb01cation by Mosteller and Wallace (1964). The\nintuition of Bayesian classi\ufb01cation is to use Bayes\u2019 rule to transform Eq. 4.1 into\nother probabilities that have some useful properties. Bayes\u2019 rule is presented in\nEq. 4.2; it gives us a way to break down any conditional probability P(xjy)into\nthree other probabilities:\nP(xjy) =P(yjx)P(x)\nP(y)(4.2) 4.1 \u2022 N AIVE BAYES CLASSIFIERS 59\nWe can then substitute Eq. 4.2 into Eq. 4.1 to get Eq. 4.3:\n\u02c6c=argmax\nc2CP(cjd) =argmax\nc2CP(djc)P(c)\nP(d)(4.3)\nWe can conveniently simplify Eq. 4.3 by dropping the denominator P(d). This\nis possible because we will be computingP(djc)P(c)\nP(d)for each possible class. But P(d)\ndoesn\u2019t change for each class; we are always asking about the most likely class for\nthe same document d, which must have the same probability P(d). Thus, we can\nchoose the class that maximizes this simpler formula:\n\u02c6c=argmax\nc2CP(cjd) =argmax\nc2CP(djc)P(c) (4.4)\nWe call Naive Bayes a generative model because we can read Eq. 4.4 as stating\na kind of implicit assumption about how a document is generated: \ufb01rst a class is\nsampled from P(c), and then the words are generated by sampling from P(djc). (In\nfact we could imagine generating arti\ufb01cial documents, or at least their word counts,\nby following this process). We\u2019ll say more about this intuition of generative models\nin Chapter 5.\nTo return to classi\ufb01cation: we compute the most probable class \u02c6 cgiven some\ndocument dby choosing the class which has the highest product of two probabilities:\ntheprior probability of the class P(c)and the likelihood of the document P(djc):prior\nprobability\nlikelihood\n\u02c6c=argmax\nc2Clikelihoodz}|{\nP(djc)priorz}|{\nP(c) (4.5)\nWithout loss of generality, we can represent a document das a set of features\nf1;f2;:::;fn:\n\u02c6c=argmax\nc2Clikelihoodz}|{\nP(f1;f2;::::; fnjc)priorz}|{\nP(c) (4.6)\nUnfortunately, Eq. 4.6 is still too hard to compute directly: without some sim-\nplifying assumptions, estimating the probability of every possible combination of\nfeatures (for example, every possible set of words and positions) would require huge\nnumbers of parameters and impossibly large training sets. Naive Bayes classi\ufb01ers\ntherefore make two simplifying assumptions.\nThe \ufb01rst is the bag-of-words assumption discussed intuitively above: we assume\nposition doesn\u2019t matter, and that the word \u201clove\u201d has the same effect on classi\ufb01cation\nwhether it occurs as the 1st, 20th, or last word in the document. Thus we assume\nthat the features f1;f2;:::;fnonly encode word identity and not position.\nThe second is commonly called the naive Bayes assumption : this is the condi-naive Bayes\nassumption\ntional independence assumption that the probabilities P(fijc)are independent given\nthe class cand hence can be \u2018naively\u2019 multiplied as follows:\nP(f1;f2;::::; fnjc) = P(f1jc)\u0001P(f2jc)\u0001:::\u0001P(fnjc) (4.7)\nThe \ufb01nal equation for the class chosen by a naive Bayes classi\ufb01er is thus:\ncNB=argmax\nc2CP(c)Y\nf2FP(fjc) (4.8) 60 CHAPTER 4 \u2022 N AIVE BAYES , TEXT CLASSIFICATION ,AND SENTIMENT\nTo apply the naive Bayes classi\ufb01er to text, we will use each word in the documents\nas a feature, as suggested above, and we consider each of the words in the document\nby walking an index through every word position in the document:\npositions all word positions in test document\ncNB=argmax\nc2CP(c)Y\ni2positionsP(wijc) (4.9)\nNaive Bayes calculations, like calculations for language modeling, are done in log\nspace, to avoid under\ufb02ow and increase speed. Thus Eq. 4.9 is generally instead\nexpressed1as\ncNB=argmax\nc2ClogP(c)+X\ni2positionslogP(wijc) (4.10)\nBy considering features in log space, Eq. 4.10 computes the predicted class as a lin-\near function of input features. Classi\ufb01ers that use a linear combination of the inputs\nto make a classi\ufb01cation decision \u2014like naive Bayes and also logistic regression\u2014\nare called linear classi\ufb01ers .linear\nclassi\ufb01ers\n4.2 Training the Naive Bayes Classi\ufb01er\nHow can we learn the probabilities P(c)andP(fijc)? Let\u2019s \ufb01rst consider the maxi-\nmum likelihood estimate. We\u2019ll simply use the frequencies in the data. For the class\nprior P(c)we ask what percentage of the documents in our training set are in each\nclass c. Let Ncbe the number of documents in our training data with class cand\nNdocbe the total number of documents. Then:\n\u02c6P(c) =Nc\nNdoc(4.11)\nTo learn the probability P(fijc), we\u2019ll assume a feature is just the existence of a word\nin the document\u2019s bag of words, and so we\u2019ll want P(wijc), which we compute as\nthe fraction of times the word wiappears among all words in all documents of topic\nc. We \ufb01rst concatenate all documents with category cinto one big \u201ccategory c\u201d text.\nThen we use the frequency of wiin this concatenated document to give a maximum\nlikelihood estimate of the probability:\n\u02c6P(wijc) =count (wi;c)P\nw2Vcount (w;c)(4.12)\nHere the vocabulary V consists of the union of all the word types in all classes, not\njust the words in one class c.\nThere is a problem, however, with maximum likelihood training. Imagine we\nare trying to estimate the likelihood of the word \u201cfantastic\u201d given class positive , but\nsuppose there are no training documents that both contain the word \u201cfantastic\u201d and\nare classi\ufb01ed as positive . Perhaps the word \u201cfantastic\u201d happens to occur (sarcasti-\ncally?) in the class negative . In such a case the probability for this feature will be\nzero:\n\u02c6P(\u201cfantastic\u201djpositive ) =count (\u201cfantastic\u201d;positive )P\nw2Vcount (w;positive )=0 (4.13)\n1In practice throughout this book, we\u2019ll use log to mean natural log (ln) when the base is not speci\ufb01ed. 4.3 \u2022 W ORKED EXAMPLE 61\nBut since naive Bayes naively multiplies all the feature likelihoods together, zero\nprobabilities in the likelihood term for any class will cause the probability of the\nclass to be zero, no matter the other evidence!\nThe simplest solution is the add-one (Laplace) smoothing introduced in Chap-\nter 3. While Laplace smoothing is usually replaced by more sophisticated smoothing\nalgorithms in language modeling, it is commonly used in naive Bayes text catego-\nrization:\n\u02c6P(wijc) =count (wi;c)+1P\nw2V(count (w;c)+1)=count (wi;c)+1\u0000P\nw2Vcount (w;c)\u0001\n+jVj(4.14)\nNote once again that it is crucial that the vocabulary V consists of the union of all the\nword types in all classes, not just the words in one class c(try to convince yourself\nwhy this must be true; see the exercise at the end of the chapter).\nWhat do we do about words that occur in our test data but are not in our vocab-\nulary at all because they did not occur in any training document in any class? The\nsolution for such unknown words is to ignore them\u2014remove them from the test unknown word\ndocument and not include any probability for them at all.\nFinally, some systems choose to completely ignore another class of words: stop\nwords , very frequent words like theanda. This can be done by sorting the vocabu- stop words\nlary by frequency in the training set, and de\ufb01ning the top 10\u2013100 vocabulary entries\nas stop words, or alternatively by using one of the many prede\ufb01ned stop word lists\navailable online. Then each instance of these stop words is simply removed from\nboth training and test documents as if it had never occurred. In most text classi\ufb01ca-\ntion applications, however, using a stop word list doesn\u2019t improve performance, and\nso it is more common to make use of the entire vocabulary and not use a stop word\nlist.\nFig. 4.2 shows the \ufb01nal algorithm.\n4.3 Worked example\nLet\u2019s walk through an example of training and testing naive Bayes with add-one\nsmoothing. We\u2019ll use a sentiment analysis domain with the two classes positive\n(+) and negative (-), and take the following miniature training and test documents\nsimpli\ufb01ed from actual movie reviews.\nCat Documents\nTraining - just plain boring\n- entirely predictable and lacks energy\n- no surprises and very few laughs\n+ very powerful\n+ the most fun \ufb01lm of the summer\nTest ? predictable with no fun\nThe prior P(c)for the two classes is computed via Eq. 4.11 asNc\nNdoc:\nP(\u0000) =3\n5P(+) =2\n5\nThe word with doesn\u2019t occur in the training set, so we drop it completely (as\nmentioned above, we don\u2019t use unknown word models for naive Bayes). The like-\nlihoods from the training set for the remaining three words \u201cpredictable\u201d, \u201cno\u201d, and 62 CHAPTER 4 \u2022 N AIVE BAYES , TEXT CLASSIFICATION ,AND SENTIMENT\nfunction TRAIN NAIVE BAYES (D, C) returns V;logP(c), log P(wjc)\nfor each class c2C # Calculate P(c)terms\nNdoc= number of documents in D\nNc= number of documents from D in class c\nlogprior [c] logNc\nNdoc\nV vocabulary of D\nbigdoc [c] append (d)ford2Dwith class c\nfor each word win V # Calculate P(wjc)terms\ncount(w,c) # of occurrences of winbigdoc [c]\nloglikelihood [w,c] logcount (w;c) + 1P\nw0in V(count (w0;c) + 1)\nreturn logprior ,loglikelihood ,V\nfunction TESTNAIVE BAYES (testdoc ,logprior ,loglikelihood , C, V) returns bestc\nfor each class c2C\nsum[c] logprior [c]\nfor each position iintestdoc\nword testdoc[i]\nifword2V\nsum[c] sum[c]+loglikelihood [word ,c]\nreturn argmaxcsum[c]\nFigure 4.2 The naive Bayes algorithm, using add-1 smoothing. To use add- asmoothing\ninstead, change the +1 to+afor loglikelihood counts in training.\n\u201cfun\u201d, are as follows, from Eq. 4.14 (computing the probabilities for the remainder\nof the words in the training set is left as an exercise for the reader):\nP(\u201cpredictable\u201dj\u0000) =1+1\n14+20P(\u201cpredictable\u201dj+) =0+1\n9+20\nP(\u201cno\u201dj\u0000) =1+1\n14+20P(\u201cno\u201dj+) =0+1\n9+20\nP(\u201cfun\u201dj\u0000) =0+1\n14+20P(\u201cfun\u201dj+) =1+1\n9+20\nFor the test sentence S = \u201cpredictable with no fun\u201d, after removing the word \u2018with\u2019,\nthe chosen class, via Eq. 4.9, is therefore computed as follows:\nP(\u0000)P(Sj\u0000) =3\n5\u00022\u00022\u00021\n343=6:1\u000210\u00005\nP(+)P(Sj+) =2\n5\u00021\u00021\u00022\n293=3:2\u000210\u00005\nThe model thus predicts the class negative for the test sentence.\n4.4 Optimizing for Sentiment Analysis\nWhile standard naive Bayes text classi\ufb01cation can work well for sentiment analysis,\nsome small changes are generally employed that improve performance. 4.4 \u2022 O PTIMIZING FOR SENTIMENT ANALYSIS 63\nFirst, for sentiment classi\ufb01cation and a number of other text classi\ufb01cation tasks,\nwhether a word occurs or not seems to matter more than its frequency. Thus it often\nimproves performance to clip the word counts in each document at 1 (see the end\nof the chapter for pointers to these results). This variant is called binary multino-\nmial naive Bayes orbinary naive Bayes . The variant uses the same algorithm asbinary naive\nBayes\nin Fig. 4.2 except that for each document we remove all duplicate words before con-\ncatenating them into the single big document during training and we also remove\nduplicate words from test documents. Fig. 4.3 shows an example in which a set\nof four documents (shortened and text-normalized for this example) are remapped\nto binary, with the modi\ufb01ed counts shown in the table on the right. The example\nis worked without add-1 smoothing to make the differences clearer. Note that the\nresults counts need not be 1; the word great has a count of 2 even for binary naive\nBayes, because it appears in multiple documents.\nFour original documents:\n\u0000it was pathetic the worst part was the\nboxing scenes\n\u0000no plot twists or great scenes\n+and satire and great plot twists\n+great scenes great \ufb01lm\nAfter per-document binarization:\n\u0000it was pathetic the worst part boxing\nscenes\n\u0000no plot twists or great scenes\n+and satire great plot twists\n+great scenes \ufb01lmNB Binary\nCounts Counts\n+\u0000+\u0000\nand 2 0 1 0\nboxing 0 1 0 1\n\ufb01lm 1 0 1 0\ngreat 3 1 2 1\nit 0 1 0 1\nno 0 1 0 1\nor 0 1 0 1\npart 0 1 0 1\npathetic 0 1 0 1\nplot 1 1 1 1\nsatire 1 0 1 0\nscenes 1 2 1 2\nthe 0 2 0 1\ntwists 1 1 1 1\nwas 0 2 0 1\nworst 0 1 0 1\nFigure 4.3 An example of binarization for the binary naive Bayes algorithm.\nA second important addition commonly made when doing text classi\ufb01cation for\nsentiment is to deal with negation. Consider the difference between I really like this\nmovie (positive) and I didn\u2019t like this movie (negative). The negation expressed by\ndidn\u2019t completely alters the inferences we draw from the predicate like. Similarly,\nnegation can modify a negative word to produce a positive review ( don\u2019t dismiss this\n\ufb01lm,doesn\u2019t let us get bored ).\nA very simple baseline that is commonly used in sentiment analysis to deal with\nnegation is the following: during text normalization, prepend the pre\ufb01x NOT to\nevery word after a token of logical negation ( n\u2019t, not, no, never ) until the next punc-\ntuation mark. Thus the phrase\ndidn't like this movie , but I\nbecomes\ndidn't NOT_like NOT_this NOT_movie , but I\nNewly formed \u2018words\u2019 like NOT like,NOT recommend will thus occur more\noften in negative document and act as cues for negative sentiment, while words\nlikeNOT bored ,NOT dismiss will acquire positive associations. Syntactic parsing\n(Chapter 18) can be used deal more accurately with the scope relationship between 64 CHAPTER 4 \u2022 N AIVE BAYES , TEXT CLASSIFICATION ,AND SENTIMENT\nthese negation words and the predicates they modify, but this simple baseline works\nquite well in practice.\nFinally, in some situations we might have insuf\ufb01cient labeled training data to\ntrain accurate naive Bayes classi\ufb01ers using all words in the training set to estimate\npositive and negative sentiment. In such cases we can instead derive the positive\nand negative word features from sentiment lexicons , lists of words that are pre-sentiment\nlexicons\nannotated with positive or negative sentiment. Four popular lexicons are the General\nInquirer (Stone et al., 1966), LIWC (Pennebaker et al., 2007), the opinion lexiconGeneral\nInquirer\nLIWC of Hu and Liu (2004a) and the MPQA Subjectivity Lexicon (Wilson et al., 2005).\nFor example the MPQA subjectivity lexicon has 6885 words each marked for\nwhether it is strongly or weakly biased positive or negative. Some examples:\n+:admirable, beautiful, con\ufb01dent, dazzling, ecstatic, favor, glee, great\n\u0000:awful, bad, bias, catastrophe, cheat, deny, envious, foul, harsh, hate\nA common way to use lexicons in a naive Bayes classi\ufb01er is to add a feature\nthat is counted whenever a word from that lexicon occurs. Thus we might add a\nfeature called \u2018this word occurs in the positive lexicon\u2019, and treat all instances of\nwords in the lexicon as counts for that one feature, instead of counting each word\nseparately. Similarly, we might add as a second feature \u2018this word occurs in the\nnegative lexicon\u2019 of words in the negative lexicon. If we have lots of training data,\nand if the test data matches the training data, using just two features won\u2019t work as\nwell as using all the words. But when training data is sparse or not representative of\nthe test set, using dense lexicon features instead of sparse individual-word features\nmay generalize better.\nWe\u2019ll return to this use of lexicons in Chapter 22, showing how these lexicons\ncan be learned automatically, and how they can be applied to many other tasks be-\nyond sentiment classi\ufb01cation.\n4.5 Naive Bayes for other text classi\ufb01cation tasks\nIn the previous section we pointed out that naive Bayes doesn\u2019t require that our\nclassi\ufb01er use all the words in the training data as features. In fact features in naive\nBayes can express any property of the input text we want.\nConsider the task of spam detection , deciding if a particular piece of email is spam detection\nan example of spam (unsolicited bulk email)\u2014one of the \ufb01rst applications of naive\nBayes to text classi\ufb01cation (Sahami et al., 1998).\nA common solution here, rather than using all the words as individual features,\nis to prede\ufb01ne likely sets of words or phrases as features, combined with features\nthat are not purely linguistic. For example the open-source SpamAssassin tool2\nprede\ufb01nes features like the phrase \u201cone hundred percent guaranteed\u201d, or the feature\nmentions millions of dollars , which is a regular expression that matches suspiciously\nlarge sums of money. But it also includes features like HTML has a low ratio of text\nto image area , that aren\u2019t purely linguistic and might require some sophisticated\ncomputation, or totally non-linguistic features about, say, the path that the email\ntook to arrive. More sample SpamAssassin features:\n\u2022 Email subject line is all capital letters\n\u2022 Contains phrases of urgency like \u201curgent reply\u201d\n2https://spamassassin.apache.org 4.6 \u2022 N AIVE BAYES AS A LANGUAGE MODEL 65\n\u2022 Email subject line contains \u201conline pharmaceutical\u201d\n\u2022 HTML has unbalanced \u201chead\u201d tags\n\u2022 Claims you can be removed from the list\nFor other tasks, like language id \u2014determining what language a given piece language id\nof text is written in\u2014the most effective naive Bayes features are not words at all,\nbutcharacter n-grams , 2-grams (\u2018zw\u2019) 3-grams (\u2018nya\u2019, \u2018 V o\u2019), or 4-grams (\u2018ie z\u2019,\n\u2018thei\u2019), or, even simpler byte n-grams , where instead of using the multibyte Unicode\ncharacter representations called codepoints, we just pretend everything is a string of\nraw bytes. Because spaces count as a byte, byte n-grams can model statistics about\nthe beginning or ending of words. A widely used naive Bayes system, langid.py\n(Lui and Baldwin, 2012) begins with all possible n-grams of lengths 1-4, using fea-\nture selection to winnow down to the most informative 7000 \ufb01nal features.\nLanguage ID systems are trained on multilingual text, such as Wikipedia (Wiki-\npedia text in 68 different languages was used in (Lui and Baldwin, 2011)), or newswire.\nTo make sure that this multilingual text correctly re\ufb02ects different regions, dialects,\nand socioeconomic classes, systems also add Twitter text in many languages geo-\ntagged to many regions (important for getting world English dialects from countries\nwith large Anglophone populations like Nigeria or India), Bible and Quran transla-\ntions, slang websites like Urban Dictionary, corpora of African American Vernacular\nEnglish (Blodgett et al., 2016), and so on (Jurgens et al., 2017).\n4.6 Naive Bayes as a Language Model\nAs we saw in the previous section, naive Bayes classi\ufb01ers can use any sort of feature:\ndictionaries, URLs, email addresses, network features, phrases, and so on. But if,\nas in Section 4.3, we use only individual word features, and we use all of the words\nin the text (not a subset), then naive Bayes has an important similarity to language\nmodeling. Speci\ufb01cally, a naive Bayes model can be viewed as a set of class-speci\ufb01c\nunigram language models, in which the model for each class instantiates a unigram\nlanguage model.\nSince the likelihood features from the naive Bayes model assign a probability to\neach word P(wordjc), the model also assigns a probability to each sentence:\nP(sjc) =Y\ni2positionsP(wijc) (4.15)\nThus consider a naive Bayes model with the classes positive (+) and negative (-)\nand the following model parameters:\nw P(wj+)P(wj-)\nI 0.1 0.2\nlove 0.1 0.001\nthis 0.01 0.01\nfun 0.05 0.005\n\ufb01lm 0.1 0.1\n... ... ...\nEach of the two columns above instantiates a language model that can assign a\nprobability to the sentence \u201cI love this fun \ufb01lm\u201d: 66 CHAPTER 4 \u2022 N AIVE BAYES , TEXT CLASSIFICATION ,AND SENTIMENT\nP(\u201cI love this fun \ufb01lm\u201d j+) = 0:1\u00020:1\u00020:01\u00020:05\u00020:1=5\u000210\u00007\nP(\u201cI love this fun \ufb01lm\u201d j\u0000) = 0:2\u00020:001\u00020:01\u00020:005\u00020:1=1:0\u000210\u00009\nAs it happens, the positive model assigns a higher probability to the sentence:\nP(sjpos)>P(sjneg). Note that this is just the likelihood part of the naive Bayes\nmodel; once we multiply in the prior a full naive Bayes model might well make a\ndifferent classi\ufb01cation decision.\n4.7 Evaluation: Precision, Recall, F-measure\nTo introduce the methods for evaluating text classi\ufb01cation, let\u2019s \ufb01rst consider some\nsimple binary detection tasks. For example, in spam detection, our goal is to label\nevery text as being in the spam category (\u201cpositive\u201d) or not in the spam category\n(\u201cnegative\u201d). For each item (email document) we therefore need to know whether\nour system called it spam or not. We also need to know whether the email is actually\nspam or not, i.e. the human-de\ufb01ned labels for each document that we are trying to\nmatch. We will refer to these human labels as the gold labels . gold labels\nOr imagine you\u2019re the CEO of the Delicious Pie Company and you need to know\nwhat people are saying about your pies on social media, so you build a system that\ndetects tweets concerning Delicious Pie. Here the positive class is tweets about\nDelicious Pie and the negative class is all other tweets.\nIn both cases, we need a metric for knowing how well our spam detector (or\npie-tweet-detector) is doing. To evaluate any system for detecting things, we start\nby building a confusion matrix like the one shown in Fig. 4.4. A confusion matrixconfusion\nmatrix\nis a table for visualizing how an algorithm performs with respect to the human gold\nlabels, using two dimensions (system output and gold labels), and each cell labeling\na set of possible outcomes. In the spam detection case, for example, true positives\nare documents that are indeed spam (indicated by human-created gold labels) that\nour system correctly said were spam. False negatives are documents that are indeed\nspam but our system incorrectly labeled as non-spam.\nTo the bottom right of the table is the equation for accuracy , which asks what\npercentage of all the observations (for the spam or pie examples that means all emails\nor tweets) our system labeled correctly. Although accuracy might seem a natural\nmetric, we generally don\u2019t use it for text classi\ufb01cation tasks. That\u2019s because accuracy\ndoesn\u2019t work well when the classes are unbalanced (as indeed they are with spam,\nwhich is a large majority of email, or with tweets, which are mainly not about pie).\nTo make this more explicit, imagine that we looked at a million tweets, and\nlet\u2019s say that only 100 of them are discussing their love (or hatred) for our pie,\nwhile the other 999,900 are tweets about something completely unrelated. Imagine a\nsimple classi\ufb01er that stupidly classi\ufb01ed every tweet as \u201cnot about pie\u201d. This classi\ufb01er\nwould have 999,900 true negatives and only 100 false negatives for an accuracy of\n999,900/1,000,000 or 99.99%! What an amazing accuracy level! Surely we should\nbe happy with this classi\ufb01er? But of course this fabulous \u2018no pie\u2019 classi\ufb01er would\nbe completely useless, since it wouldn\u2019t \ufb01nd a single one of the customer comments\nwe are looking for. In other words, accuracy is not a good metric when the goal is\nto discover something that is rare, or at least not completely balanced in frequency,\nwhich is a very common situation in the world. 4.7 \u2022 E VALUATION : PRECISION , RECALL , F- MEASURE 67\ntrue positivefalse negativefalse positivetrue negativegold positivegold negativesystempositivesystemnegativegold standard labelssystemoutputlabelsrecall = tptp+fnprecision = tptp+fpaccuracy = tp+tntp+fp+tn+fn\nFigure 4.4 A confusion matrix for visualizing how well a binary classi\ufb01cation system per-\nforms against gold standard labels.\nThat\u2019s why instead of accuracy we generally turn to two other metrics shown in\nFig. 4.4: precision andrecall .Precision measures the percentage of the items that precision\nthe system detected (i.e., the system labeled as positive) that are in fact positive (i.e.,\nare positive according to the human gold labels). Precision is de\ufb01ned as\nPrecision =true positives\ntrue positives + false positives\nRecall measures the percentage of items actually present in the input that were recall\ncorrectly identi\ufb01ed by the system. Recall is de\ufb01ned as\nRecall =true positives\ntrue positives + false negatives\nPrecision and recall will help solve the problem with the useless \u201cnothing is\npie\u201d classi\ufb01er. This classi\ufb01er, despite having a fabulous accuracy of 99.99%, has\na terrible recall of 0 (since there are no true positives, and 100 false negatives, the\nrecall is 0/100). You should convince yourself that the precision at \ufb01nding relevant\ntweets is equally problematic. Thus precision and recall, unlike accuracy, emphasize\ntrue positives: \ufb01nding the things that we are supposed to be looking for.\nThere are many ways to de\ufb01ne a single metric that incorporates aspects of both\nprecision and recall. The simplest of these combinations is the F-measure (van F-measure\nRijsbergen, 1975) , de\ufb01ned as:\nFb=(b2+1)PR\nb2P+R\nThebparameter differentially weights the importance of recall and precision,\nbased perhaps on the needs of an application. Values of b>1 favor recall, while\nvalues of b<1 favor precision. When b=1, precision and recall are equally bal-\nanced; this is the most frequently used metric, and is called F b=1or just F 1: F1\nF1=2PR\nP+R(4.16)\nF-measure comes from a weighted harmonic mean of precision and recall. The\nharmonic mean of a set of numbers is the reciprocal of the arithmetic mean of recip-\nrocals:\nHarmonicMean (a1;a2;a3;a4;:::;an) =n\n1\na1+1\na2+1\na3+:::+1\nan(4.17) 68 CHAPTER 4 \u2022 N AIVE BAYES , TEXT CLASSIFICATION ,AND SENTIMENT\nand hence F-measure is\nF=1\na1\nP+(1\u0000a)1\nRor\u0012\nwithb2=1\u0000a\na\u0013\nF=(b2+1)PR\nb2P+R(4.18)\nHarmonic mean is used because the harmonic mean of two values is closer to the\nminimum of the two values than the arithmetic mean is. Thus it weighs the lower of\nthe two numbers more heavily, which is more conservative in this situation.\n4.7.1 Evaluating with more than two classes\nUp to now we have been describing text classi\ufb01cation tasks with only two classes.\nBut lots of classi\ufb01cation tasks in language processing have more than two classes.\nFor sentiment analysis we generally have 3 classes (positive, negative, neutral) and\neven more classes are common for tasks like part-of-speech tagging, word sense\ndisambiguation, semantic role labeling, emotion detection, and so on. Luckily the\nnaive Bayes algorithm is already a multi-class classi\ufb01cation algorithm.\n851060urgentnormalgold labelssystemoutputrecallu = 88+5+3precisionu= 88+10+115030200spamurgentnormalspam3recalln = recalls = precisionn= 605+60+50precisions= 2003+30+2006010+60+302001+50+200\nFigure 4.5 Confusion matrix for a three-class categorization task, showing for each pair of\nclasses (c1;c2), how many documents from c1were (in)correctly assigned to c2.\nBut we\u2019ll need to slightly modify our de\ufb01nitions of precision and recall. Con-\nsider the sample confusion matrix for a hypothetical 3-way one-of email catego-\nrization decision (urgent, normal, spam) shown in Fig. 4.5. The matrix shows, for\nexample, that the system mistakenly labeled one spam document as urgent, and we\nhave shown how to compute a distinct precision and recall value for each class. In\norder to derive a single metric that tells us how well the system is doing, we can com-\nbine these values in two ways. In macroaveraging , we compute the performance macroaveraging\nfor each class, and then average over classes. In microaveraging , we collect the de- microaveraging\ncisions for all classes into a single confusion matrix, and then compute precision and\nrecall from that table. Fig. 4.6 shows the confusion matrix for each class separately,\nand shows the computation of microaveraged and macroaveraged precision.\nAs the \ufb01gure shows, a microaverage is dominated by the more frequent class (in\nthis case spam), since the counts are pooled. The macroaverage better re\ufb02ects the\nstatistics of the smaller classes, and so is more appropriate when performance on all\nthe classes is equally important. 4.8 \u2022 T EST SETS AND CROSS -VALIDATION 69\n8811340trueurgenttruenotsystemurgentsystemnot604055212truenormaltruenotsystemnormalsystemnot200513383truespamtruenotsystemspamsystemnot2689999635trueyestruenosystemyessystemnoprecision =8+118= .42precision =200+33200= .86precision =60+5560= .52microaverageprecision268+99268= .73=macroaverageprecision3.42+.52+.86= .60=PooledClass 3: SpamClass 2: NormalClass 1: Urgent\nFigure 4.6 Separate confusion matrices for the 3 classes from the previous \ufb01gure, showing the pooled confu-\nsion matrix and the microaveraged and macroaveraged precision.\n4.8 Test sets and Cross-validation\nThe training and testing procedure for text classi\ufb01cation follows what we saw with\nlanguage modeling (Section 3.2): we use the training set to train the model, then use\nthedevelopment test set (also called a devset ) to perhaps tune some parameters,development\ntest set\ndevset and in general decide what the best model is. Once we come up with what we think\nis the best model, we run it on the (hitherto unseen) test set to report its performance.\nWhile the use of a devset avoids over\ufb01tting the test set, having a \ufb01xed train-\ning set, devset, and test set creates another problem: in order to save lots of data\nfor training, the test set (or devset) might not be large enough to be representative.\nWouldn\u2019t it be better if we could somehow use all our data for training and still use\nall our data for test? We can do this by cross-validation . cross-validation\nIn cross-validation, we choose a number k, and partition our data into kdisjoint\nsubsets called folds . Now we choose one of those kfolds as a test set, train our folds\nclassi\ufb01er on the remaining k\u00001 folds, and then compute the error rate on the test\nset. Then we repeat with another fold as the test set, again training on the other k\u00001\nfolds. We do this sampling process ktimes and average the test set error rate from\nthese kruns to get an average error rate. If we choose k=10, we would train 10\ndifferent models (each on 90% of our data), test the model 10 times, and average\nthese 10 values. This is called 10-fold cross-validation .10-fold\ncross-validation\nThe only problem with cross-validation is that because all the data is used for\ntesting, we need the whole corpus to be blind; we can\u2019t examine any of the data\nto suggest possible features and in general see what\u2019s going on, because we\u2019d be\npeeking at the test set, and such cheating would cause us to overestimate the perfor-\nmance of our system. However, looking at the corpus to understand what\u2019s going\non is important in designing NLP systems! What to do? For this reason, it is com-\nmon to create a \ufb01xed training set and test set, then do 10-fold cross-validation inside\nthe training set, but compute error rate the normal way in the test set, as shown in\nFig. 4.7. 70 CHAPTER 4 \u2022 N AIVE BAYES , TEXT CLASSIFICATION ,AND SENTIMENT\nTraining Iterations13452678910DevDevDevDevDevDevDevDevDevDevTrainingTrainingTrainingTrainingTrainingTrainingTrainingTrainingTrainingTrainingTrainingTest SetTesting\nFigure 4.7 10-fold cross-validation\n4.9 Statistical Signi\ufb01cance Testing\nIn building systems we often need to compare the performance of two systems. How\ncan we know if the new system we just built is better than our old one? Or better\nthan some other system described in the literature? This is the domain of statistical\nhypothesis testing, and in this section we introduce tests for statistical signi\ufb01cance\nfor NLP classi\ufb01ers, drawing especially on the work of Dror et al. (2020) and Berg-\nKirkpatrick et al. (2012).\nSuppose we\u2019re comparing the performance of classi\ufb01ers AandBon a metric M\nsuch as F 1, or accuracy. Perhaps we want to know if our logistic regression senti-\nment classi\ufb01er A(Chapter 5) gets a higher F 1score than our naive Bayes sentiment\nclassi\ufb01er Bon a particular test set x. Let\u2019s call M(A;x)the score that system Agets\non test set x, and d(x)the performance difference between AandBonx:\nd(x) =M(A;x)\u0000M(B;x) (4.19)\nWe would like to know if d(x)>0, meaning that our logistic regression classi\ufb01er\nhas a higher F 1than our naive Bayes classi\ufb01er on x.d(x)is called the effect size ; a effect size\nbigger dmeans that Aseems to be way better than B; a small dmeans Aseems to\nbe only a little better.\nWhy don\u2019t we just check if d(x)is positive? Suppose we do, and we \ufb01nd that\nthe F 1score of Ais higher than B\u2019s by .04. Can we be certain that Ais better? We\ncannot! That\u2019s because Amight just be accidentally better than Bon this particular x.\nWe need something more: we want to know if A\u2019s superiority over Bis likely to hold\nagain if we checked another test set x0, or under some other set of circumstances.\nIn the paradigm of statistical hypothesis testing, we test this by formalizing two\nhypotheses.\nH0:d(x)\u00140\nH1:d(x)>0 (4.20)\nThe hypothesis H0, called the null hypothesis , supposes that d(x)is actually nega- null hypothesis\ntive or zero, meaning that Ais not better than B. We would like to know if we can\ncon\ufb01dently rule out this hypothesis, and instead support H1, that Ais better.\nWe do this by creating a random variable Xranging over all test sets. Now we\nask how likely is it, if the null hypothesis H0was correct, that among these test sets 4.9 \u2022 S TATISTICAL SIGNIFICANCE TESTING 71\nwe would encounter the value of d(x)that we found, if we repeated the experiment\na great many times. We formalize this likelihood as the p-value : the probability, p-value\nassuming the null hypothesis H0is true, of seeing the d(x)that we saw or one even\ngreater\nP(d(X)\u0015d(x)jH0is true ) (4.21)\nSo in our example, this p-value is the probability that we would see d(x)assuming\nAisnotbetter than B. Ifd(x)is huge (let\u2019s say Ahas a very respectable F 1of .9\nandBhas a terrible F 1of only .2 on x), we might be surprised, since that would be\nextremely unlikely to occur if H0were in fact true, and so the p-value would be low\n(unlikely to have such a large difAis in fact not better than B). But if d(x)is very\nsmall, it might be less surprising to us even if H0were true and Ais not really better\nthan B, and so the p-value would be higher.\nA very small p-value means that the difference we observed is very unlikely\nunder the null hypothesis, and we can reject the null hypothesis. What counts as very\nsmall? It is common to use values like .05 or .01 as the thresholds. A value of .01\nmeans that if the p-value (the probability of observing the dwe saw assuming H0is\ntrue) is less than .01, we reject the null hypothesis and assume that Ais indeed better\nthan B. We say that a result (e.g., \u201c Ais better than B\u201d) is statistically signi\ufb01cant ifstatistically\nsigni\ufb01cant\nthedwe saw has a probability that is below the threshold and we therefore reject\nthis null hypothesis.\nHow do we compute this probability we need for the p-value? In NLP we gen-\nerally don\u2019t use simple parametric tests like t-tests or ANOV As that you might be\nfamiliar with. Parametric tests make assumptions about the distributions of the test\nstatistic (such as normality) that don\u2019t generally hold in our cases. So in NLP we\nusually use non-parametric tests based on sampling: we arti\ufb01cially create many ver-\nsions of the experimental setup. For example, if we had lots of different test sets x0\nwe could just measure all the d(x0)for all the x0. That gives us a distribution. Now\nwe set a threshold (like .01) and if we see in this distribution that 99% or more of\nthose deltas are smaller than the delta we observed, i.e., that p-value( x)\u2014the proba-\nbility of seeing a d(x)as big as the one we saw\u2014is less than .01, then we can reject\nthe null hypothesis and agree that d(x)was a suf\ufb01ciently surprising difference and\nAis really a better algorithm than B.\nThere are two common non-parametric tests used in NLP: approximate ran-\ndomization (Noreen, 1989) and the bootstrap test . We will describe bootstrapapproximate\nrandomization\nbelow, showing the paired version of the test, which again is most common in NLP.\nPaired tests are those in which we compare two sets of observations that are aligned: paired\neach observation in one set can be paired with an observation in another. This hap-\npens naturally when we are comparing the performance of two systems on the same\ntest set; we can pair the performance of system Aon an individual observation xi\nwith the performance of system Bon the same xi.\n4.9.1 The Paired Bootstrap Test\nThebootstrap test (Efron and Tibshirani, 1993) can apply to any metric; from pre- bootstrap test\ncision, recall, or F1 to the BLEU metric used in machine translation. The word\nbootstrapping refers to repeatedly drawing large numbers of samples with replace- bootstrapping\nment (called bootstrap samples ) from an original set. The intuition of the bootstrap\ntest is that we can create many virtual test sets from an observed test set by repeat-\nedly sampling from it. The method only makes the assumption that the sample is\nrepresentative of the population. 72 CHAPTER 4 \u2022 N AIVE BAYES , TEXT CLASSIFICATION ,AND SENTIMENT\nConsider a tiny text classi\ufb01cation example with a test set xof 10 documents. The\n\ufb01rst row of Fig. 4.8 shows the results of two classi\ufb01ers (A and B) on this test set.\nEach document is labeled by one of the four possibilities (A and B both right, both\nwrong, A right and B wrong, A wrong and B right). A slash through a letter ( \u0013B)\nmeans that that classi\ufb01er got the answer wrong. On the \ufb01rst document both A and\nB get the correct class (AB), while on the second document A got it right but B got\nit wrong (A \u0013B). If we assume for simplicity that our metric is accuracy, A has an\naccuracy of .70 and B of .50, so d(x)is .20.\nNow we create a large number b(perhaps 105) of virtual test sets x(i), each of size\nn=10. Fig. 4.8 shows a couple of examples. To create each virtual test set x(i), we\nrepeatedly ( n=10 times) select a cell from row xwith replacement. For example, to\ncreate the \ufb01rst cell of the \ufb01rst virtual test set x(1), if we happened to randomly select\nthe second cell of the xrow; we would copy the value A \u0013B into our new cell, and\nmove on to create the second cell of x(1), each time sampling (randomly choosing)\nfrom the original xwith replacement.\n1 2 3 4 5 6 7 8 910A% B% d()\nx AB A\u0013\u0013BAB\u0000\u0000AB A\u0013\u0013B\u0000\u0000AB A\u0013\u0013BAB\u0000\u0000A\u0013\u0013BA\u0013\u0013B.70 .50 .20\nx(1)A\u0013\u0013BAB A\u0013\u0013B\u0000\u0000AB\u0000\u0000AB A\u0013\u0013B\u0000\u0000AB AB\u0000\u0000A\u0013\u0013BAB .60 .60 .00\nx(2)A\u0013\u0013BAB\u0000\u0000A\u0013\u0013B\u0000\u0000AB\u0000\u0000AB AB\u0000\u0000AB A\u0013\u0013BAB AB .60 .70-.10\n...\nx(b)\nFigure 4.8 The paired bootstrap test: Examples of bpseudo test sets x(i)being created\nfrom an initial true test set x. Each pseudo test set is created by sampling n=10 times with\nreplacement; thus an individual sample is a single cell, a document with its gold label and\nthe correct or incorrect performance of classi\ufb01ers A and B. Of course real test sets don\u2019t have\nonly 10 examples, and bneeds to be large as well.\nNow that we have the btest sets, providing a sampling distribution, we can do\nstatistics on how often Ahas an accidental advantage. There are various ways to\ncompute this advantage; here we follow the version laid out in Berg-Kirkpatrick\net al. (2012). Assuming H0(Aisn\u2019t better than B), we would expect that d(X),\nestimated over many test sets, would be zero or negative; a much higher value would\nbe surprising, since H0speci\ufb01cally assumes Aisn\u2019t better than B. To measure exactly\nhow surprising our observed d(x)is, we would in other circumstances compute the\np-value by counting over many test sets how often d(x(i))exceeds the expected zero\nvalue by d(x)or more:\np-value (x) =1\nbbX\ni=11\u0010\nd(x(i))\u0000d(x)\u00150\u0011\n(We use the notation 1(x)to mean \u201c1 if xis true, and 0 otherwise\u201d.) However,\nalthough it\u2019s generally true that the expected value of d(X)over many test sets,\n(again assuming Aisn\u2019t better than B) is 0, this isn\u2019t true for the bootstrapped test\nsets we created. That\u2019s because we didn\u2019t draw these samples from a distribution\nwith 0 mean; we happened to create them from the original test set x, which happens\nto be biased (by .20) in favor of A. So to measure how surprising is our observed\nd(x), we actually compute the p-value by counting over many test sets how often 4.10 \u2022 A VOIDING HARMS IN CLASSIFICATION 73\nd(x(i))exceeds the expected value of d(x)byd(x)or more:\np-value (x) =1\nbbX\ni=11\u0010\nd(x(i))\u0000d(x)\u0015d(x)\u0011\n=1\nbbX\ni=11\u0010\nd(x(i))\u00152d(x)\u0011\n(4.22)\nSo if for example we have 10,000 test sets x(i)and a threshold of .01, and in only 47\nof the test sets do we \ufb01nd that A is accidentally better d(x(i))\u00152d(x), the resulting\np-value of .0047 is smaller than .01, indicating that the delta we found, d(x)is indeed\nsuf\ufb01ciently surprising and unlikely to have happened by accident, and we can reject\nthe null hypothesis and conclude Ais better than B.\nfunction BOOTSTRAP (test set x,num of samples b)returns p-value (x)\nCalculate d(x)# how much better does algorithm A do than B on x\ns= 0\nfori= 1tobdo\nforj= 1tondo # Draw a bootstrap sample x(i)of size n\nSelect a member of xat random and add it to x(i)\nCalculate d(x(i))# how much better does algorithm A do than B on x(i)\ns s+ 1ifd(x(i))\u00152d(x)\np-value( x)\u0019s\nb# on what % of the b samples did algorithm A beat expectations?\nreturn p-value( x) # if very few did, our observed dis probably not accidental\nFigure 4.9 A version of the paired bootstrap algorithm after Berg-Kirkpatrick et al. (2012).\nThe full algorithm for the bootstrap is shown in Fig. 4.9. It is given a test set x, a\nnumber of samples b, and counts the percentage of the bbootstrap test sets in which\nd(x\u0003(i))>2d(x). This percentage then acts as a one-sided empirical p-value.\n4.10 Avoiding Harms in Classi\ufb01cation\nIt is important to avoid harms that may result from classi\ufb01ers, harms that exist both\nfor naive Bayes classi\ufb01ers and for the other classi\ufb01cation algorithms we introduce\nin later chapters.\nOne class of harms is representational harms (Crawford 2017, Blodgett et al.representational\nharms\n2020), harms caused by a system that demeans a social group, for example by per-\npetuating negative stereotypes about them. For example Kiritchenko and Moham-\nmad (2018) examined the performance of 200 sentiment analysis systems on pairs of\nsentences that were identical except for containing either a common African Amer-\nican \ufb01rst name (like Shaniqua ) or a common European American \ufb01rst name (like\nStephanie ), chosen from the Caliskan et al. (2017) study discussed in Chapter 6.\nThey found that most systems assigned lower sentiment and more negative emotion\nto sentences with African American names, re\ufb02ecting and perpetuating stereotypes\nthat associate African Americans with negative emotions (Popp et al., 2003).\nIn other tasks classi\ufb01ers may lead to both representational harms and other\nharms, such as silencing. For example the important text classi\ufb01cation task of tox- 74 CHAPTER 4 \u2022 N AIVE BAYES , TEXT CLASSIFICATION ,AND SENTIMENT\nicity detection is the task of detecting hate speech, abuse, harassment, or othertoxicity\ndetection\nkinds of toxic language. While the goal of such classi\ufb01ers is to help reduce soci-\netal harm, toxicity classi\ufb01ers can themselves cause harms. For example, researchers\nhave shown that some widely used toxicity classi\ufb01ers incorrectly \ufb02ag as being toxic\nsentences that are non-toxic but simply mention identities like women (Park et al.,\n2018), blind people (Hutchinson et al., 2020) or gay people (Dixon et al., 2018;\nDias Oliva et al., 2021), or simply use linguistic features characteristic of varieties\nlike African-American Vernacular English (Sap et al. 2019, Davidson et al. 2019).\nSuch false positive errors could lead to the silencing of discourse by or about these\ngroups.\nThese model problems can be caused by biases or other problems in the training\ndata; in general, machine learning systems replicate and even amplify the biases\nin their training data. But these problems can also be caused by the labels (for\nexample due to biases in the human labelers), by the resources used (like lexicons,\nor model components like pretrained embeddings), or even by model architecture\n(like what the model is trained to optimize). While the mitigation of these biases\n(for example by carefully considering the training data sources) is an important area\nof research, we currently don\u2019t have general solutions. For this reason it\u2019s important,\nwhen introducing any NLP model, to study these kinds of factors and make them\nclear. One way to do this is by releasing a model card (Mitchell et al., 2019) for model card\neach version of a model. A model card documents a machine learning model with\ninformation like:\n\u2022 training algorithms and parameters\n\u2022 training data sources, motivation, and preprocessing\n\u2022 evaluation data sources, motivation, and preprocessing\n\u2022 intended use and users\n\u2022 model performance across different demographic or other groups and envi-\nronmental situations\n4.11 Summary\nThis chapter introduced the naive Bayes model for classi\ufb01cation and applied it to\nthetext categorization task of sentiment analysis .\n\u2022 Many language processing tasks can be viewed as tasks of classi\ufb01cation .\n\u2022 Text categorization, in which an entire text is assigned a class from a \ufb01nite set,\nincludes such tasks as sentiment analysis ,spam detection , language identi-\n\ufb01cation, and authorship attribution.\n\u2022 Sentiment analysis classi\ufb01es a text as re\ufb02ecting the positive or negative orien-\ntation ( sentiment ) that a writer expresses toward some object.\n\u2022 Naive Bayes is a generative model that makes the bag-of-words assumption\n(position doesn\u2019t matter) and the conditional independence assumption (words\nare conditionally independent of each other given the class)\n\u2022 Naive Bayes with binarized features seems to work better for many text clas-\nsi\ufb01cation tasks.\n\u2022 Classi\ufb01ers are evaluated based on precision andrecall .\n\u2022 Classi\ufb01ers are trained using distinct training, dev, and test sets, including the\nuse of cross-validation in the training set. BIBLIOGRAPHICAL AND HISTORICAL NOTES 75\n\u2022 Statistical signi\ufb01cance tests should be used to determine whether we can be\ncon\ufb01dent that one version of a classi\ufb01er is better than another.\n\u2022 Designers of classi\ufb01ers should carefully consider harms that may be caused\nby the model, including its training data and other components, and report\nmodel characteristics in a model card .\nBibliographical and Historical Notes\nMultinomial naive Bayes text classi\ufb01cation was proposed by Maron (1961) at the\nRAND Corporation for the task of assigning subject categories to journal abstracts.\nHis model introduced most of the features of the modern form presented here, ap-\nproximating the classi\ufb01cation task with one-of categorization, and implementing\nadd-dsmoothing and information-based feature selection.\nThe conditional independence assumptions of naive Bayes and the idea of Bayes-\nian analysis of text seems to have arisen multiple times. The same year as Maron\u2019s\npaper, Minsky (1961) proposed a naive Bayes classi\ufb01er for vision and other arti-\n\ufb01cial intelligence problems, and Bayesian techniques were also applied to the text\nclassi\ufb01cation task of authorship attribution by Mosteller and Wallace (1963). It had\nlong been known that Alexander Hamilton, John Jay, and James Madison wrote\nthe anonymously-published Federalist papers in 1787\u20131788 to persuade New York\nto ratify the United States Constitution. Yet although some of the 85 essays were\nclearly attributable to one author or another, the authorship of 12 were in dispute\nbetween Hamilton and Madison. Mosteller and Wallace (1963) trained a Bayesian\nprobabilistic model of the writing of Hamilton and another model on the writings\nof Madison, then computed the maximum-likelihood author for each of the disputed\nessays. Naive Bayes was \ufb01rst applied to spam detection in Heckerman et al. (1998).\nMetsis et al. (2006), Pang et al. (2002), and Wang and Manning (2012) show\nthat using boolean attributes with multinomial naive Bayes works better than full\ncounts. Binary multinomial naive Bayes is sometimes confused with another variant\nof naive Bayes that also uses a binary representation of whether a term occurs in\na document: Multivariate Bernoulli naive Bayes . The Bernoulli variant instead\nestimates P(wjc)as the fraction of documents that contain a term, and includes a\nprobability for whether a term is notin a document. McCallum and Nigam (1998)\nand Wang and Manning (2012) show that the multivariate Bernoulli variant of naive\nBayes doesn\u2019t work as well as the multinomial algorithm for sentiment or other text\ntasks.\nThere are a variety of sources covering the many kinds of text classi\ufb01cation\ntasks. For sentiment analysis see Pang and Lee (2008), and Liu and Zhang (2012).\nStamatatos (2009) surveys authorship attribute algorithms. On language identi\ufb01ca-\ntion see Jauhiainen et al. (2019); Jaech et al. (2016) is an important early neural\nsystem. The task of newswire indexing was often used as a test case for text classi-\n\ufb01cation algorithms, based on the Reuters-21578 collection of newswire articles.\nSee Manning et al. (2008) and Aggarwal and Zhai (2012) on text classi\ufb01cation;\nclassi\ufb01cation in general is covered in machine learning textbooks (Hastie et al. 2001,\nWitten and Frank 2005, Bishop 2006, Murphy 2012).\nNon-parametric methods for computing statistical signi\ufb01cance were used \ufb01rst in\nNLP in the MUC competition (Chinchor et al., 1993), and even earlier in speech\nrecognition (Gillick and Cox 1989, Bisani and Ney 2004). Our description of the\nbootstrap draws on the description in Berg-Kirkpatrick et al. (2012). Recent work\nhas focused on issues including multiple test sets and multiple metrics (S\u00f8gaard et al. 76 CHAPTER 4 \u2022 N AIVE BAYES , TEXT CLASSIFICATION ,AND SENTIMENT\n2014, Dror et al. 2017).\nFeature selection is a method of removing features that are unlikely to generalize\nwell. Features are generally ranked by how informative they are about the classi\ufb01ca-\ntion decision. A very common metric, information gain , tells us how many bits ofinformation\ngain\ninformation the presence of the word gives us for guessing the class. Other feature\nselection metrics include c2, pointwise mutual information, and GINI index; see\nYang and Pedersen (1997) for a comparison and Guyon and Elisseeff (2003) for an\nintroduction to feature selection.\nExercises\n4.1 Assume the following likelihoods for each word being part of a positive or\nnegative movie review, and equal prior probabilities for each class.\npos neg\nI 0.09 0.16\nalways 0.07 0.06\nlike 0.29 0.06\nforeign 0.04 0.15\n\ufb01lms 0.08 0.11\nWhat class will Naive bayes assign to the sentence \u201cI always like foreign\n\ufb01lms.\u201d?\n4.2 Given the following short movie reviews, each labeled with a genre, either\ncomedy or action:\n1. fun, couple, love, love comedy\n2. fast, furious, shoot action\n3. couple, \ufb02y, fast, fun, fun comedy\n4. furious, shoot, shoot, fun action\n5. \ufb02y, fast, shoot, love action\nand a new document D:\nfast, couple, shoot, \ufb02y\ncompute the most likely class for D. Assume a naive Bayes classi\ufb01er and use\nadd-1 smoothing for the likelihoods.\n4.3 Train two models, multinomial naive Bayes and binarized naive Bayes, both\nwith add-1 smoothing, on the following document counts for key sentiment\nwords, with positive or negative class assigned as noted.\ndoc \u201cgood\u201d \u201cpoor\u201d \u201cgreat\u201d (class)\nd1. 3 0 3 pos\nd2. 0 1 2 pos\nd3. 1 3 0 neg\nd4. 1 5 2 neg\nd5. 0 2 0 neg\nUse both naive Bayes models to assign a class (pos or neg) to this sentence:\nA good, good plot and great characters, but poor acting.\nRecall from page 61 that with naive Bayes text classi\ufb01cation, we simply ig-\nnore (throw out) any word that never occurred in the training document. (We\ndon\u2019t throw out words that appear in some classes but not others; that\u2019s what\nadd-one smoothing is for.) Do the two models agree or disagree? CHAPTER\n5Logistic Regression\n\u201cAnd how do you know that these \ufb01ne begonias are not of equal importance?\u201d\nHercule Poirot, in Agatha Christie\u2019s The Mysterious Affair at Styles\nDetective stories are as littered with clues as texts are with words. Yet for the\npoor reader it can be challenging to know how to weigh the author\u2019s clues in order\nto make the crucial classi\ufb01cation task: deciding whodunnit.\nIn this chapter we introduce an algorithm that is admirably suited for discovering\nthe link between features or clues and some particular outcome: logistic regression .logistic\nregression\nIndeed, logistic regression is one of the most important analytic tools in the social\nand natural sciences. In natural language processing, logistic regression is the base-\nline supervised machine learning algorithm for classi\ufb01cation, and also has a very\nclose relationship with neural networks. As we will see in Chapter 7, a neural net-\nwork can be viewed as a series of logistic regression classi\ufb01ers stacked on top of\neach other. Thus the classi\ufb01cation and machine learning techniques introduced here\nwill play an important role throughout the book.\nLogistic regression can be used to classify an observation into one of two classes\n(like \u2018positive sentiment\u2019 and \u2018negative sentiment\u2019), or into one of many classes.\nBecause the mathematics for the two-class case is simpler, we\u2019ll describe this special\ncase of logistic regression \ufb01rst in the next few sections, and then brie\ufb02y summarize\nthe use of multinomial logistic regression for more than two classes in Section 5.3.\nWe\u2019ll introduce the mathematics of logistic regression in the next few sections.\nBut let\u2019s begin with some high-level issues.\nGenerative and Discriminative Classi\ufb01ers: The most important difference be-\ntween naive Bayes and logistic regression is that logistic regression is a discrimina-\ntiveclassi\ufb01er while naive Bayes is a generative classi\ufb01er.\nThese are two very different frameworks for how\nto build a machine learning model. Consider a visual\nmetaphor: imagine we\u2019re trying to distinguish dog\nimages from cat images. A generative model would\nhave the goal of understanding what dogs look like\nand what cats look like. You might literally ask such\na model to \u2018generate\u2019, i.e., draw, a dog. Given a test\nimage, the system then asks whether it\u2019s the cat model or the dog model that better\n\ufb01ts (is less surprised by) the image, and chooses that as its label.\nA discriminative model, by contrast, is only try-\ning to learn to distinguish the classes (perhaps with-\nout learning much about them). So maybe all the\ndogs in the training data are wearing collars and the\ncats aren\u2019t. If that one feature neatly separates the\nclasses, the model is satis\ufb01ed. If you ask such a\nmodel what it knows about cats all it can say is that\nthey don\u2019t wear collars. 78 CHAPTER 5 \u2022 L OGISTIC REGRESSION\nMore formally, recall that the naive Bayes assigns a class cto a document dnot\nby directly computing P(cjd)but by computing a likelihood and a prior\n\u02c6c=argmax\nc2Clikelihoodz}|{\nP(djc)priorz}|{\nP(c) (5.1)\nAgenerative model like naive Bayes makes use of this likelihood term, whichgenerative\nmodel\nexpresses how to generate the features of a document if we knew it was of class c .\nBy contrast a discriminative model in this text categorization scenario attemptsdiscriminative\nmodel\ntodirectly compute P(cjd). Perhaps it will learn to assign a high weight to document\nfeatures that directly improve its ability to discriminate between possible classes,\neven if it couldn\u2019t generate an example of one of the classes.\nComponents of a probabilistic machine learning classi\ufb01er: Like naive Bayes,\nlogistic regression is a probabilistic classi\ufb01er that makes use of supervised machine\nlearning. Machine learning classi\ufb01ers require a training corpus of minput/output\npairs(x(i);y(i)). (We\u2019ll use superscripts in parentheses to refer to individual instances\nin the training set\u2014for sentiment classi\ufb01cation each instance might be an individual\ndocument to be classi\ufb01ed.) A machine learning system for classi\ufb01cation then has\nfour components:\n1. A feature representation of the input. For each input observation x(i), this\nwill be a vector of features [x1;x2;:::;xn]. We will generally refer to feature\nifor input x(j)asx(j)\ni, sometimes simpli\ufb01ed as xi, but we will also see the\nnotation fi,fi(x), or, for multiclass classi\ufb01cation, fi(c;x).\n2. A classi\ufb01cation function that computes \u02c6 y, the estimated class, via p(yjx). In\nthe next section we will introduce the sigmoid andsoftmax tools for classi\ufb01-\ncation.\n3. An objective function that we want to optimize for learning, usually involving\nminimizing a loss function corresponding to error on training examples. We\nwill introduce the cross-entropy loss function .\n4. An algorithm for optimizing the objective function. We introduce the stochas-\ntic gradient descent algorithm.\nLogistic regression has two phases:\ntraining: We train the system (speci\ufb01cally the weights wandb, introduced be-\nlow) using stochastic gradient descent and the cross-entropy loss.\ntest: Given a test example xwe compute p(yjx)and return the higher probability\nlabel y=1 ory=0.\n5.1 The sigmoid function\nThe goal of binary logistic regression is to train a classi\ufb01er that can make a binary\ndecision about the class of a new input observation. Here we introduce the sigmoid\nclassi\ufb01er that will help us make this decision.\nConsider a single input observation x, which we will represent by a vector of\nfeatures [x1;x2;:::;xn]. (We\u2019ll show sample features in the next subsection.) The\nclassi\ufb01er output ycan be 1 (meaning the observation is a member of the class) or\n0 (the observation is not a member of the class). We want to know the probability 5.1 \u2022 T HE SIGMOID FUNCTION 79\nP(y=1jx)that this observation is a member of the class. So perhaps the decision\nis \u201cpositive sentiment\u201d versus \u201cnegative sentiment\u201d, the features represent counts of\nwords in a document, P(y=1jx)is the probability that the document has positive\nsentiment, and P(y=0jx)is the probability that the document has negative senti-\nment.\nLogistic regression solves this task by learning, from a training set, a vector of\nweights and a bias term . Each weight wiis a real number, and is associated with one\nof the input features xi. The weight wirepresents how important that input feature\nis to the classi\ufb01cation decision, and can be positive (providing evidence that the in-\nstance being classi\ufb01ed belongs in the positive class) or negative (providing evidence\nthat the instance being classi\ufb01ed belongs in the negative class). Thus we might\nexpect in a sentiment task the word awesome to have a high positive weight, and\nabysmal to have a very negative weight. The bias term , also called the intercept , is bias term\nintercept another real number that\u2019s added to the weighted inputs.\nTo make a decision on a test instance\u2014after we\u2019ve learned the weights in training\u2014\nthe classi\ufb01er \ufb01rst multiplies each xiby its weight wi, sums up the weighted features,\nand adds the bias term b. The resulting single number zexpresses the weighted sum\nof the evidence for the class.\nz= nX\ni=1wixi!\n+b (5.2)\nIn the rest of the book we\u2019ll represent such sums using the dot product notation dot product\nfrom linear algebra. The dot product of two vectors aandb, written as a\u0001b, is the\nsum of the products of the corresponding elements of each vector. (Notice that we\nrepresent vectors using the boldface notation b). Thus the following is an equivalent\nformation to Eq. 5.2:\nz=w\u0001x+b (5.3)\nBut note that nothing in Eq. 5.3 forces zto be a legal probability, that is, to lie\nbetween 0 and 1. In fact, since weights are real-valued, the output might even be\nnegative; zranges from\u0000\u00a5to\u00a5.\nFigure 5.1 The sigmoid function s(z) =1\n1+e\u0000ztakes a real value and maps it to the range\n(0;1). It is nearly linear around 0 but outlier values get squashed toward 0 or 1.\nTo create a probability, we\u2019ll pass zthrough the sigmoid function, s(z). The sigmoid\nsigmoid function (named because it looks like an s) is also called the logistic func-\ntion, and gives logistic regression its name. The sigmoid has the following equation,logistic\nfunction\nshown graphically in Fig. 5.1:\ns(z) =1\n1+e\u0000z=1\n1+exp(\u0000z)(5.4) 80 CHAPTER 5 \u2022 L OGISTIC REGRESSION\n(For the rest of the book, we\u2019ll use the notation exp (x)to mean ex.) The sigmoid\nhas a number of advantages; it takes a real-valued number and maps it into the range\n(0;1), which is just what we want for a probability. Because it is nearly linear around\n0 but \ufb02attens toward the ends, it tends to squash outlier values toward 0 or 1. And\nit\u2019s differentiable, which as we\u2019ll see in Section 5.10 will be handy for learning.\nWe\u2019re almost there. If we apply the sigmoid to the sum of the weighted features,\nwe get a number between 0 and 1. To make it a probability, we just need to make\nsure that the two cases, p(y=1)andp(y=0), sum to 1. We can do this as follows:\nP(y=1) = s(w\u0001x+b)\n=1\n1+exp(\u0000(w\u0001x+b))\nP(y=0) = 1\u0000s(w\u0001x+b)\n=1\u00001\n1+exp(\u0000(w\u0001x+b))\n=exp(\u0000(w\u0001x+b))\n1+exp(\u0000(w\u0001x+b))(5.5)\nThe sigmoid function has the property\n1\u0000s(x) =s(\u0000x) (5.6)\nso we could also have expressed P(y=0)ass(\u0000(w\u0001x+b)).\nFinally, one terminological point. The input to the sigmoid function, the score\nz=w\u0001x+bfrom (5.3), is often called the logit . This is because the logit function logit\nis the inverse of the sigmoid. The logit function is the log of the odds ratiop\n1\u0000p:\nlogit(p) =s\u00001(p) =lnp\n1\u0000p(5.7)\nUsing the term logit forzis a way of reminding us that by using the sigmoid to turn\nz(which ranges from \u0000\u00a5to\u00a5) into a probability, we are implicitly interpreting zas\nnot just any real-valued number, but as speci\ufb01cally a log odds.\n5.2 Classi\ufb01cation with Logistic Regression\nThe sigmoid function from the prior section thus gives us a way to take an instance\nxand compute the probability P(y=1jx).\nHow do we make a decision about which class to apply to a test instance x? For\na given x, we say yes if the probability P(y=1jx)is more than .5, and no otherwise.\nWe call .5 the decision boundary :decision\nboundary\ndecision (x) =\u001a1 if P(y=1jx)>0:5\n0 otherwise\nLet\u2019s have some examples of applying logistic regression as a classi\ufb01er for language\ntasks. 5.2 \u2022 C LASSIFICATION WITH LOGISTIC REGRESSION 81\n5.2.1 Sentiment Classi\ufb01cation\nSuppose we are doing binary sentiment classi\ufb01cation on movie review text, and\nwe would like to know whether to assign the sentiment class +or\u0000to a review\ndocument doc. We\u2019ll represent each input observation by the 6 features x1:::x6of\nthe input shown in the following table; Fig. 5.2 shows the features in a sample mini\ntest document.\nVar De\ufb01nition Value in Fig. 5.2\nx1 count(positive lexicon words 2doc) 3\nx2 count(negative lexicon words 2doc) 2\nx3\u001a1 if \u201cno\u201d2doc\n0 otherwise1\nx4 count (1st and 2nd pronouns 2doc) 3\nx5\u001a1 if \u201c!\u201d2doc\n0 otherwise0\nx6 ln(word count of doc ) ln(66) =4:19\n It's hokey . There are virtually no surprises , and the writing is second-rate . So why was it so enjoyable ? For one thing , the cast is great . Another nice touch is the music . I was overcome with the urge to get off the couch and start dancing . It sucked me in , and it'll do the same to you .x1=3x6=4.19x3=1x4=3x5=0x2=2\nFigure 5.2 A sample mini test document showing the extracted features in the vector x.\nLet\u2019s assume for the moment that we\u2019ve already learned a real-valued weight\nfor each of these features, and that the 6 weights corresponding to the 6 features\nare[2:5;\u00005:0;\u00001:2;0:5;2:0;0:7], while b= 0.1. (We\u2019ll discuss in the next section\nhow the weights are learned.) The weight w1, for example indicates how important\na feature the number of positive lexicon words ( great ,nice,enjoyable , etc.) is to\na positive sentiment decision, while w2tells us the importance of negative lexicon\nwords. Note that w1=2:5 is positive, while w2=\u00005:0, meaning that negative words\nare negatively associated with a positive sentiment decision, and are about twice as\nimportant as positive words.\nGiven these 6 features and the input review x,P(+jx)andP(\u0000jx)can be com-\nputed using Eq. 5.5:\np(+jx) =P(y=1jx) = s(w\u0001x+b)\n=s([2:5;\u00005:0;\u00001:2;0:5;2:0;0:7]\u0001[3;2;1;3;0;4:19]+0:1)\n=s(:833)\n=0:70 (5.8)\np(\u0000jx) =P(y=0jx) = 1\u0000s(w\u0001x+b)\n=0:30 82 CHAPTER 5 \u2022 L OGISTIC REGRESSION\n5.2.2 Other classi\ufb01cation tasks and features\nLogistic regression is applied to all sorts of NLP tasks, and any property of the input\ncan be a feature. Consider the task of period disambiguation : deciding if a periodperiod\ndisambiguation\nis the end of a sentence or part of a word, by classifying each period into one of two\nclasses, EOS (end-of-sentence) and not-EOS. We might use features like x1below\nexpressing that the current word is lower case, perhaps with a positive weight. Or a\nfeature expressing that the current word is in our abbreviations dictionary (\u201cProf.\u201d),\nperhaps with a negative weight. A feature can also express a combination of proper-\nties. For example a period following an upper case word is likely to be an EOS, but\nif the word itself is St.and the previous word is capitalized then the period is likely\npart of a shortening of the word street following a street name.\nx1=\u001a\n1 if \u201c Case(wi) =Lower\u201d\n0 otherwise\nx2=\u001a1 if \u201c wi2AcronymDict\u201d\n0 otherwise\nx3=\u001a1 if \u201c wi=St. & Case(wi\u00001) =Upper\u201d\n0 otherwise\nDesigning versus learning features: In classic models, features are designed by\nhand by examining the training set with an eye to linguistic intuitions and literature,\nsupplemented by insights from error analysis on the training set of an early version\nof a system. We can also consider ( feature interactions ), complex features that arefeature\ninteractions\ncombinations of more primitive features. We saw such a feature for period disam-\nbiguation above, where a period on the word St.was less likely to be the end of the\nsentence if the previous word was capitalized. Features can be created automatically\nviafeature templates , abstract speci\ufb01cations of features. For example a bigramfeature\ntemplates\ntemplate for period disambiguation might create a feature for every pair of words\nthat occurs before a period in the training set. Thus the feature space is sparse, since\nwe only have to create a feature if that n-gram exists in that position in the training\nset. The feature is generally created as a hash from the string descriptions. A user\ndescription of a feature as, \u201cbigram(American breakfast)\u201d is hashed into a unique\ninteger ithat becomes the feature number fi.\nIt should be clear from the prior paragraph that designing features by hand re-\nquires extensive human effort. For this reason, recent NLP systems avoid hand-\ndesigned features and instead focus on representation learning : ways to learn fea-\ntures automatically in an unsupervised way from the input. We\u2019ll introduce methods\nfor representation learning in Chapter 6 and Chapter 7.\nScaling input features: When different input features have extremely different\nranges of values, it\u2019s common to rescale them so they have comparable ranges. We\nstandardize input values by centering them to result in a zero mean and a standard standardize\ndeviation of one (this transformation is sometimes called the z-score ). That is, if miz-score\nis the mean of the values of feature xiacross the mobservations in the input dataset,\nandsiis the standard deviation of the values of features xiacross the input dataset,\nwe can replace each feature xiby a new feature x0\nicomputed as follows:\nmi=1\nmmX\nj=1x(j)\ni si=vuut1\nmmX\nj=1\u0010\nx(j)\ni\u0000mi\u00112\nx0\ni=xi\u0000mi\nsi(5.9) 5.2 \u2022 C LASSIFICATION WITH LOGISTIC REGRESSION 83\nAlternatively, we can normalize the input features values to lie between 0 and 1: normalize\nx0\ni=xi\u0000min(xi)\nmax(xi)\u0000min(xi)(5.10)\nHaving input data with comparable range is useful when comparing values across\nfeatures. Data scaling is especially important in large neural networks, since it helps\nspeed up gradient descent.\n5.2.3 Processing many examples at once\nWe\u2019ve shown the equations for logistic regression for a single example. But in prac-\ntice we\u2019ll of course want to process an entire test set with many examples. Let\u2019s\nsuppose we have a test set consisting of mtest examples each of which we\u2019d like\nto classify. We\u2019ll continue to use the notation from page 78, in which a superscript\nvalue in parentheses refers to the example index in some set of data (either for train-\ning or for test). So in this case each test example x(i)has a feature vector x(i),\n1\u0014i\u0014m. (As usual, we\u2019ll represent vectors and matrices in bold.)\nOne way to compute each output value \u02c6 y(i)is just to have a for-loop, and compute\neach test example one at a time:\nforeach x(i)in input [x(1);x(2);:::;x(m)]\ny(i)=s(w\u0001x(i)+b) (5.11)\nFor the \ufb01rst 3 test examples, then, we would be separately computing the pre-\ndicted \u02c6 y(i)as follows:\nP(y(1)=1jx(1)) = s(w\u0001x(1)+b)\nP(y(2)=1jx(2)) = s(w\u0001x(2)+b)\nP(y(3)=1jx(3)) = s(w\u0001x(3)+b)\nBut it turns out that we can slightly modify our original equation Eq. 5.5 to do\nthis much more ef\ufb01ciently. We\u2019ll use matrix arithmetic to assign a class to all the\nexamples with one matrix operation!\nFirst, we\u2019ll pack all the input feature vectors for each input xinto a single input\nmatrix X, where each row iis a row vector consisting of the feature vector for in-\nput example x(i)(i.e., the vector x(i)). Assuming each example has ffeatures and\nweights, Xwill therefore be a matrix of shape [m\u0002f], as follows:\nX=2\n66664x(1)\n1x(1)\n2:::x(1)\nf\nx(2)\n1x(2)\n2:::x(2)\nf\nx(3)\n1x(3)\n2:::x(3)\nf\n:::3\n77775(5.12)\nNow if we introduce bas a vector of length mwhich consists of the scalar bias\nterm brepeated mtimes, b= [b;b;:::;b], and ^ y= [\u02c6y(1);\u02c6y(2):::;\u02c6y(m)]as the vector of\noutputs (one scalar \u02c6 y(i)for each input x(i)and its feature vector x(i)), and represent\nthe weight vector was a column vector, we can compute all the outputs with a single\nmatrix multiplication and one addition:\ny=Xw+b (5.13) 84 CHAPTER 5 \u2022 L OGISTIC REGRESSION\nYou should convince yourself that Eq. 5.13 computes the same thing as our for-loop\nin Eq. 5.11. For example \u02c6 y(1), the \ufb01rst entry of the output vector y, will correctly be:\n\u02c6y(1)= [x(1)\n1;x(1)\n2;:::;x(1)\nf]\u0001[w1;w2;:::;wf]+b (5.14)\nNote that we had to reorder Xandwfrom the order they appeared in in Eq. 5.5 to\nmake the multiplications come out properly. Here is Eq. 5.13 again with the shapes\nshown:\ny=X w +b\n(m\u00021) ( m\u0002f)(f\u00021) (m\u00021) (5.15)\nModern compilers and compute hardware can compute this matrix operation very\nef\ufb01ciently, making the computation much faster, which becomes important when\ntraining or testing on very large datasets.\nNote by the way that we could have kept Xandwin the original order ( y=\nXw+b) if we had chosen to de\ufb01ne Xdifferently as a matrix of column vectors, one\nvector for each input example, instead of row vectors, and then it would have shape\n[f\u0002m]. But we conventionally represent inputs as rows.\n5.2.4 Choosing a classi\ufb01er\nLogistic regression has a number of advantages over naive Bayes. Naive Bayes has\noverly strong conditional independence assumptions. Consider two features which\nare strongly correlated; in fact, imagine that we just add the same feature f1twice.\nNaive Bayes will treat both copies of f1as if they were separate, multiplying them\nboth in, overestimating the evidence. By contrast, logistic regression is much more\nrobust to correlated features; if two features f1and f2are perfectly correlated, re-\ngression will simply assign part of the weight to w1and part to w2. Thus when\nthere are many correlated features, logistic regression will assign a more accurate\nprobability than naive Bayes. So logistic regression generally works better on larger\ndocuments or datasets and is a common default.\nDespite the less accurate probabilities, naive Bayes still often makes the correct\nclassi\ufb01cation decision. Furthermore, naive Bayes can work extremely well (some-\ntimes even better than logistic regression) on very small datasets (Ng and Jordan,\n2002) or short documents (Wang and Manning, 2012). Furthermore, naive Bayes is\neasy to implement and very fast to train (there\u2019s no optimization step). So it\u2019s still a\nreasonable approach to use in some situations.\n5.3 Multinomial logistic regression\nSometimes we need more than two classes. Perhaps we might want to do 3-way\nsentiment classi\ufb01cation (positive, negative, or neutral). Or we could be assigning\nsome of the labels we will introduce in Chapter 17, like the part of speech of a word\n(choosing from 10, 30, or even 50 different parts of speech), or the named entity\ntype of a phrase (choosing from tags like person, location, organization).\nIn such cases we use multinomial logistic regression , also called softmax re-multinomial\nlogistic\nregressiongression (in older NLP literature you will sometimes see the name maxent classi-\n\ufb01er). In multinomial logistic regression we want to label each observation with a\nclass kfrom a set of Kclasses, under the stipulation that only one of these classes is 5.3 \u2022 M ULTINOMIAL LOGISTIC REGRESSION 85\nthe correct one (sometimes called hard classi\ufb01cation ; an observation can not be in\nmultiple classes). Let\u2019s use the following representation: the output yfor each input\nxwill be a vector of length K. If class cis the correct class, we\u2019ll set yc=1, and\nset all the other elements of yto be 0, i.e., yc=1 and yj=08j6=c. A vector like\nthisy, with one value=1 and the rest 0, is called a one-hot vector . The job of the\nclassi\ufb01er is to produce an estimate vector ^ y. For each class k, the value \u02c6 ykwill be\nthe classi\ufb01er\u2019s estimate of the probability p(yk=1jx).\n5.3.1 Softmax\nThe multinomial logistic classi\ufb01er uses a generalization of the sigmoid, called the\nsoftmax function, to compute p(yk=1jx). The softmax function takes a vector softmax\nz= [z1;z2;:::;zK]ofKarbitrary values and maps them to a probability distribution,\nwith each value in the range [0,1], and all the values summing to 1. Like the sigmoid,\nit is an exponential function.\nFor a vector zof dimensionality K, the softmax is de\ufb01ned as:\nsoftmax (zi) =exp(zi)PK\nj=1exp(zj)1\u0014i\u0014K (5.16)\nThe softmax of an input vector z= [z1;z2;:::;zK]is thus a vector itself:\nsoftmax (z) =\"\nexp(z1)PK\ni=1exp(zi);exp(z2)PK\ni=1exp(zi);:::;exp(zK)PK\ni=1exp(zi)#\n(5.17)\nThe denominatorPK\ni=1exp(zi)is used to normalize all the values into probabilities.\nThus for example given a vector:\nz= [0:6;1:1;\u00001:5;1:2;3:2;\u00001:1]\nthe resulting (rounded) softmax( z) is\n[0:05;0:09;0:01;0:1;0:74;0:01][0:05;0:09;0:01;0:1;0:74;0:01]\nLike the sigmoid, the softmax has the property of squashing values toward 0 or 1.\nThus if one of the inputs is larger than the others, it will tend to push its probability\ntoward 1, and suppress the probabilities of the smaller inputs.\nFinally, note that, just as for the sigmoid, we refer to z, the vector of scores that\nis the input to the softmax, as logits (see (5.7).\n5.3.2 Applying softmax in logistic regression\nWhen we apply softmax for logistic regression, the input will (just as for the sig-\nmoid) be the dot product between a weight vector wand an input vector x(plus a\nbias). But now we\u2019ll need separate weight vectors wkand bias bkfor each of the K\nclasses. The probability of each of our output classes \u02c6 ykcan thus be computed as:\np(yk=1jx) =exp(wk\u0001x+bk)\nKX\nj=1exp(wj\u0001x+bj)(5.18) 86 CHAPTER 5 \u2022 L OGISTIC REGRESSION\nThe form of Eq. 5.18 makes it seem that we would compute each output sep-\narately. Instead, it\u2019s more common to set up the equation for more ef\ufb01cient com-\nputation by modern vector processing hardware. We\u2019ll do this by representing the\nset of Kweight vectors as a weight matrix Wand a bias vector b. Each row kof\nWcorresponds to the vector of weights wk.Wthus has shape [K\u0002f], for Kthe\nnumber of output classes and fthe number of input features. The bias vector bhas\none value for each of the Koutput classes. If we represent the weights in this way,\nwe can compute \u02c6y, the vector of output probabilities for each of the Kclasses, by a\nsingle elegant equation:\n\u02c6y=softmax (Wx+b) (5.19)\nIf you work out the matrix arithmetic, you can see that the estimated score of\nthe \ufb01rst output class \u02c6 y1(before we take the softmax) will correctly turn out to be\nw1\u0001x+b1.\nFig. 5.3 shows an intuition of the role of the weight vector versus weight matrix\nin the computation of the output class probabilities for binary versus multinomial\nlogistic regression.\n5.3.3 Features in Multinomial Logistic Regression\nFeatures in multinomial logistic regression act like features in binary logistic regres-\nsion, with the difference mentioned above that we\u2019ll need separate weight vectors\nand biases for each of the Kclasses. Recall our binary exclamation point feature x5\nfrom page 81:\nx5=\u001a1 if \u201c!\u201d2doc\n0 otherwise\nIn binary classi\ufb01cation a positive weight w5on a feature in\ufb02uences the classi\ufb01er\ntoward y=1 (positive sentiment) and a negative weight in\ufb02uences it toward y=0\n(negative sentiment) with the absolute value indicating how important the feature\nis. For multinomial logistic regression, by contrast, with separate weights for each\nclass, a feature can be evidence for or against each individual class.\nIn 3-way multiclass sentiment classi\ufb01cation, for example, we must assign each\ndocument one of the 3 classes +,\u0000, or 0 (neutral). Now a feature related to excla-\nmation marks might have a negative weight for 0 documents, and a positive weight\nfor+or\u0000documents:\nFeature De\ufb01nition w5;+w5;\u0000w5;0\nf5(x)\u001a1 if \u201c!\u201d2doc\n0 otherwise3:5 3:1\u00005:3\nBecause these feature weights are dependent both on the input text and the output\nclass, we sometimes make this dependence explicit and represent the features them-\nselves as f(x;y): a function of both the input and the class. Using such a notation\nf5(x)above could be represented as three features f5(x;+),f5(x;\u0000), and f5(x;0),\neach of which has a single weight. We\u2019ll use this kind of notation in our description\nof the CRF in Chapter 17. 5.4 \u2022 L EARNING IN LOGISTIC REGRESSION 87\nBinary Logistic Regression\nw[f \u2a091]Outputsigmoid[1\u2a09f]Input wordsp(+) = 1- p(-)\u2026y^xyInput featurevector [scalar]positive lexiconwords = 1count of \u201cno\u201d = 0wordcount=3x1x2x3xfdessert was greatWeight vector\nMultinomial Logistic Regression\nW[f\u2a091]Outputsoftmax[K\u2a09f]Input wordsp(+)\u2026y1^y2^y3^xyInput featurevector [K\u2a091]positive lexiconwords = 1count of \u201cno\u201d = 0wordcount=3x1x2x3xfdessert was greatp(-)p(neut)Weight matrixThese f red weightsare a row of W correspondingto weight vector w3,(= weights for class 3)\nFigure 5.3 Binary versus multinomial logistic regression. Binary logistic regression uses a\nsingle weight vector w, and has a scalar output \u02c6 y. In multinomial logistic regression we have\nKseparate weight vectors corresponding to the Kclasses, all packed into a single weight\nmatrix W, and a vector output \u02c6y. We omit the biases from both \ufb01gures for clarity.\n5.4 Learning in Logistic Regression\nHow are the parameters of the model, the weights wand bias b, learned? Logistic\nregression is an instance of supervised classi\ufb01cation in which we know the correct\nlabel y(either 0 or 1) for each observation x. What the system produces via Eq. 5.5\nis \u02c6y, the system\u2019s estimate of the true y. We want to learn parameters (meaning w\nandb) that make \u02c6 yfor each training observation as close as possible to the true y.\nThis requires two components that we foreshadowed in the introduction to the\nchapter. The \ufb01rst is a metric for how close the current label ( \u02c6 y) is to the true gold\nlabel y. Rather than measure similarity, we usually talk about the opposite of this:\nthedistance between the system output and the gold output, and we call this distance\nthelossfunction or the cost function . In the next section we\u2019ll introduce the loss loss\nfunction that is commonly used for logistic regression and also for neural networks, 88 CHAPTER 5 \u2022 L OGISTIC REGRESSION\nthecross-entropy loss .\nThe second thing we need is an optimization algorithm for iteratively updating\nthe weights so as to minimize this loss function. The standard algorithm for this is\ngradient descent ; we\u2019ll introduce the stochastic gradient descent algorithm in the\nfollowing section.\nWe\u2019ll describe these algorithms for the simpler case of binary logistic regres-\nsion in the next two sections, and then turn to multinomial logistic regression in\nSection 5.8.\n5.5 The cross-entropy loss function\nWe need a loss function that expresses, for an observation x, how close the classi\ufb01er\noutput ( \u02c6 y=s(w\u0001x+b)) is to the correct output ( y, which is 0 or 1). We\u2019ll call this:\nL(\u02c6y;y) = How much \u02c6 ydiffers from the true y (5.20)\nWe do this via a loss function that prefers the correct class labels of the train-\ning examples to be more likely . This is called conditional maximum likelihood\nestimation : we choose the parameters w;bthatmaximize the log probability of\nthe true ylabels in the training data given the observations x. The resulting loss\nfunction is the negative log likelihood loss , generally called the cross-entropy loss .cross-entropy\nloss\nLet\u2019s derive this loss function, applied to a single observation x. We\u2019d like to\nlearn weights that maximize the probability of the correct label p(yjx). Since there\nare only two discrete outcomes (1 or 0), this is a Bernoulli distribution, and we can\nexpress the probability p(yjx)that our classi\ufb01er produces for one observation as the\nfollowing (keeping in mind that if y=1, Eq. 5.21 simpli\ufb01es to \u02c6 y; ify=0, Eq. 5.21\nsimpli\ufb01es to 1\u0000\u02c6y):\np(yjx) = \u02c6yy(1\u0000\u02c6y)1\u0000y(5.21)\nNow we take the log of both sides. This will turn out to be handy mathematically,\nand doesn\u2019t hurt us; whatever values maximize a probability will also maximize the\nlog of the probability:\nlogp(yjx) = log\u0002\n\u02c6yy(1\u0000\u02c6y)1\u0000y\u0003\n=ylog \u02c6y+(1\u0000y)log(1\u0000\u02c6y) (5.22)\nEq. 5.22 describes a log likelihood that should be maximized. In order to turn this\ninto a loss function (something that we need to minimize), we\u2019ll just \ufb02ip the sign on\nEq. 5.22. The result is the cross-entropy loss LCE:\nLCE(\u02c6y;y) =\u0000logp(yjx) =\u0000[ylog \u02c6y+(1\u0000y)log(1\u0000\u02c6y)] (5.23)\nFinally, we can plug in the de\ufb01nition of \u02c6 y=s(w\u0001x+b):\nLCE(\u02c6y;y) =\u0000[ylogs(w\u0001x+b)+(1\u0000y)log(1\u0000s(w\u0001x+b))] (5.24)\nLet\u2019s see if this loss function does the right thing for our example from Fig. 5.2. We\nwant the loss to be smaller if the model\u2019s estimate is close to correct, and bigger if\nthe model is confused. So \ufb01rst let\u2019s suppose the correct gold label for the sentiment\nexample in Fig. 5.2 is positive, i.e., y=1. In this case our model is doing well, since 5.6 \u2022 G RADIENT DESCENT 89\nfrom Eq. 5.8 it indeed gave the example a higher probability of being positive (.70)\nthan negative (.30). If we plug s(w\u0001x+b) =:70 and y=1 into Eq. 5.24, the right\nside of the equation drops out, leading to the following loss (we\u2019ll use log to mean\nnatural log when the base is not speci\ufb01ed):\nLCE(\u02c6y;y) =\u0000[ylogs(w\u0001x+b)+(1\u0000y)log(1\u0000s(w\u0001x+b))]\n=\u0000[logs(w\u0001x+b)]\n=\u0000log(:70)\n= :36\nBy contrast, let\u2019s pretend instead that the example in Fig. 5.2 was actually negative,\ni.e., y=0 (perhaps the reviewer went on to say \u201cBut bottom line, the movie is\nterrible! I beg you not to see it!\u201d). In this case our model is confused and we\u2019d want\nthe loss to be higher. Now if we plug y=0 and 1\u0000s(w\u0001x+b) =:30 from Eq. 5.8\ninto Eq. 5.24, the left side of the equation drops out:\nLCE(\u02c6y;y) =\u0000[ylogs(w\u0001x+b)+(1\u0000y)log(1\u0000s(w\u0001x+b))]\n= \u0000[log(1\u0000s(w\u0001x+b))]\n= \u0000log(:30)\n= 1:2\nSure enough, the loss for the \ufb01rst classi\ufb01er (.36) is less than the loss for the second\nclassi\ufb01er (1.2).\nWhy does minimizing this negative log probability do what we want? A perfect\nclassi\ufb01er would assign probability 1 to the correct outcome ( y=1 or y=0) and\nprobability 0 to the incorrect outcome. That means if yequals 1, the higher \u02c6 yis (the\ncloser it is to 1), the better the classi\ufb01er; the lower \u02c6 yis (the closer it is to 0), the\nworse the classi\ufb01er. If yequals 0, instead, the higher 1 \u0000\u02c6yis (closer to 1), the better\nthe classi\ufb01er. The negative log of \u02c6 y(if the true yequals 1) or 1\u0000\u02c6y(if the true y\nequals 0) is a convenient loss metric since it goes from 0 (negative log of 1, no loss)\nto in\ufb01nity (negative log of 0, in\ufb01nite loss). This loss function also ensures that as\nthe probability of the correct answer is maximized, the probability of the incorrect\nanswer is minimized; since the two sum to one, any increase in the probability of the\ncorrect answer is coming at the expense of the incorrect answer. It\u2019s called the cross-\nentropy loss, because Eq. 5.22 is also the formula for the cross-entropy between the\ntrue probability distribution yand our estimated distribution \u02c6 y.\nNow we know what we want to minimize; in the next section, we\u2019ll see how to\n\ufb01nd the minimum.\n5.6 Gradient Descent\nOur goal with gradient descent is to \ufb01nd the optimal weights: minimize the loss\nfunction we\u2019ve de\ufb01ned for the model. In Eq. 5.25 below, we\u2019ll explicitly represent\nthe fact that the cross-entropy loss function LCEis parameterized by the weights. In\nmachine learning in general we refer to the parameters being learned as q; in the\ncase of logistic regression q=fw;bg. So the goal is to \ufb01nd the set of weights which\nminimizes the loss function, averaged over all examples:\n\u02c6q=argmin\nq1\nmmX\ni=1LCE(f(x(i);q);y(i)) (5.25) 90 CHAPTER 5 \u2022 L OGISTIC REGRESSION\nHow shall we \ufb01nd the minimum of this (or any) loss function? Gradient descent is\na method that \ufb01nds a minimum of a function by \ufb01guring out in which direction (in\nthe space of the parameters q) the function\u2019s slope is rising the most steeply, and\nmoving in the opposite direction. The intuition is that if you are hiking in a canyon\nand trying to descend most quickly down to the river at the bottom, you might look\naround yourself in all directions, \ufb01nd the direction where the ground is sloping the\nsteepest, and walk downhill in that direction.\nFor logistic regression, this loss function is conveniently convex . A convex func- convex\ntion has at most one minimum; there are no local minima to get stuck in, so gradient\ndescent starting from any point is guaranteed to \ufb01nd the minimum. (By contrast,\nthe loss for multi-layer neural networks is non-convex, and gradient descent may\nget stuck in local minima for neural network training and never \ufb01nd the global opti-\nmum.)\nAlthough the algorithm (and the concept of gradient) are designed for direction\nvectors , let\u2019s \ufb01rst consider a visualization of the case where the parameter of our\nsystem is just a single scalar w, shown in Fig. 5.4.\nGiven a random initialization of wat some value w1, and assuming the loss\nfunction Lhappened to have the shape in Fig. 5.4, we need the algorithm to tell us\nwhether at the next iteration we should move left (making w2smaller than w1) or\nright (making w2bigger than w1) to reach the minimum.\nwLoss\n0w1wminslope of loss at w1 is negative(goal)one stepof gradientdescent\nFigure 5.4 The \ufb01rst step in iteratively \ufb01nding the minimum of this loss function, by moving\nwin the reverse direction from the slope of the function. Since the slope is negative, we need\nto move win a positive direction, to the right. Here superscripts are used for learning steps,\nsow1means the initial value of w(which is 0), w2the value at the second step, and so on.\nThe gradient descent algorithm answers this question by \ufb01nding the gradient gradient\nof the loss function at the current point and moving in the opposite direction. The\ngradient of a function of many variables is a vector pointing in the direction of the\ngreatest increase in a function. The gradient is a multi-variable generalization of the\nslope, so for a function of one variable like the one in Fig. 5.4, we can informally\nthink of the gradient as the slope. The dotted line in Fig. 5.4 shows the slope of this\nhypothetical loss function at point w=w1. You can see that the slope of this dotted\nline is negative. Thus to \ufb01nd the minimum, gradient descent tells us to go in the\nopposite direction: moving win a positive direction.\nThe magnitude of the amount to move in gradient descent is the value of the\nsloped\ndwL(f(x;w);y)weighted by a learning rate h. A higher (faster) learning learning rate 5.6 \u2022 G RADIENT DESCENT 91\nrate means that we should move wmore on each step. The change we make in our\nparameter is the learning rate times the gradient (or the slope, in our single-variable\nexample):\nwt+1=wt\u0000hd\ndwL(f(x;w);y) (5.26)\nNow let\u2019s extend the intuition from a function of one scalar variable wto many\nvariables, because we don\u2019t just want to move left or right, we want to know where\nin the N-dimensional space (of the Nparameters that make up q) we should move.\nThe gradient is just such a vector; it expresses the directional components of the\nsharpest slope along each of those Ndimensions. If we\u2019re just imagining two weight\ndimensions (say for one weight wand one bias b), the gradient might be a vector with\ntwo orthogonal components, each of which tells us how much the ground slopes in\nthewdimension and in the bdimension. Fig. 5.5 shows a visualization of the value\nof a 2-dimensional gradient vector taken at the red point.\nIn an actual logistic regression, the parameter vector wis much longer than 1 or\n2, since the input feature vector xcan be quite long, and we need a weight wifor\neach xi. For each dimension/variable wiinw(plus the bias b), the gradient will have\na component that tells us the slope with respect to that variable. In each dimension\nwi, we express the slope as a partial derivative\u00b6\n\u00b6wiof the loss function. Essentially\nwe\u2019re asking: \u201cHow much would a small change in that variable wiin\ufb02uence the\ntotal loss function L?\u201d\nFormally, then, the gradient of a multi-variable function fis a vector in which\neach component expresses the partial derivative of fwith respect to one of the vari-\nables. We\u2019ll use the inverted Greek delta symbol \u00d1to refer to the gradient, and\nrepresent \u02c6 yasf(x;q)to make the dependence on qmore obvious:\n\u00d1L(f(x;q);y) =2\n6666664\u00b6\n\u00b6w1L(f(x;q);y)\n\u00b6\n\u00b6w2L(f(x;q);y)\n...\n\u00b6\n\u00b6wnL(f(x;q);y)\n\u00b6\n\u00b6bL(f(x;q);y)3\n7777775(5.27)\nThe \ufb01nal equation for updating qbased on the gradient is thus\nqt+1=qt\u0000h\u00d1L(f(x;q);y) (5.28)\nCost(w,b)\nwb\nFigure 5.5 Visualization of the gradient vector at the red point in two dimensions wand\nb, showing a red arrow in the x-y plane pointing in the direction we will go to look for the\nminimum: the opposite direction of the gradient (recall that the gradient points in the direction\nof increase not decrease). 92 CHAPTER 5 \u2022 L OGISTIC REGRESSION\n5.6.1 The Gradient for Logistic Regression\nIn order to update q, we need a de\ufb01nition for the gradient \u00d1L(f(x;q);y). Recall that\nfor logistic regression, the cross-entropy loss function is:\nLCE(\u02c6y;y) =\u0000[ylogs(w\u0001x+b)+(1\u0000y)log(1\u0000s(w\u0001x+b))] (5.29)\nIt turns out that the derivative of this function for one observation vector xis Eq. 5.30\n(the interested reader can see Section 5.10 for the derivation of this equation):\n\u00b6LCE(\u02c6y;y)\n\u00b6wj= [s(w\u0001x+b)\u0000y]xj\n= ( \u02c6y\u0000y)xj (5.30)\nYou\u2019ll also sometimes see this equation in the equivalent form:\n\u00b6LCE(\u02c6y;y)\n\u00b6wj=\u0000(y\u0000\u02c6y)xj (5.31)\nNote in these equations that the gradient with respect to a single weight wjrep-\nresents a very intuitive value: the difference between the true yand our estimated\n\u02c6y=s(w\u0001x+b)for that observation, multiplied by the corresponding input value\nxj.\n5.6.2 The Stochastic Gradient Descent Algorithm\nStochastic gradient descent is an online algorithm that minimizes the loss function\nby computing its gradient after each training example, and nudging qin the right\ndirection (the opposite direction of the gradient). (An \u201conline algorithm\u201d is one that\nprocesses its input example by example, rather than waiting until it sees the entire\ninput.) Stochastic gradient descent is called stochastic because it chooses a single\nrandom example at a time; in Section 5.6.4 we\u2019ll discuss other versions of gradient\ndescent that batch many examples at once. Fig. 5.6 shows the algorithm.\nThe learning rate his ahyperparameter that must be adjusted. If it\u2019s too high, hyperparameter\nthe learner will take steps that are too large, overshooting the minimum of the loss\nfunction. If it\u2019s too low, the learner will take steps that are too small, and take too\nlong to get to the minimum. It is common to start with a higher learning rate and then\nslowly decrease it, so that it is a function of the iteration kof training; the notation\nhkcan be used to mean the value of the learning rate at iteration k.\nWe\u2019ll discuss hyperparameters in more detail in Chapter 7, but in short, they are\na special kind of parameter for any machine learning model. Unlike regular param-\neters of a model (weights like wandb), which are learned by the algorithm from\nthe training set, hyperparameters are special parameters chosen by the algorithm\ndesigner that affect how the algorithm works.\n5.6.3 Working through an example\nLet\u2019s walk through a single step of the gradient descent algorithm. We\u2019ll use a\nsimpli\ufb01ed version of the example in Fig. 5.2 as it sees a single observation x, whose\ncorrect value is y=1 (this is a positive review), and with a feature vector x= [x1;x2]\nconsisting of these two features:\nx1=3 (count of positive lexicon words)\nx2=2 (count of negative lexicon words) 5.6 \u2022 G RADIENT DESCENT 93\nfunction STOCHASTIC GRADIENT DESCENT (L(),f(),x,y)returns q\n# where: L is the loss function\n# f is a function parameterized by q\n# x is the set of training inputs x(1);x(2);:::;x(m)\n# y is the set of training outputs (labels) y(1);y(2);:::;y(m)\nq 0 # (or small random values)\nrepeat til done # see caption\nFor each training tuple (x(i);y(i))(in random order)\n1. Optional (for reporting): # How are we doing on this tuple?\nCompute \u02c6 y(i)=f(x(i);q)# What is our estimated output \u02c6 y?\nCompute the loss L(\u02c6y(i);y(i))# How far off is \u02c6 y(i)from the true output y(i)?\n2.g \u00d1qL(f(x(i);q);y(i)) # How should we move qto maximize loss?\n3.q q\u0000hg # Go the other way instead\nreturn q\nFigure 5.6 The stochastic gradient descent algorithm. Step 1 (computing the loss) is used\nmainly to report how well we are doing on the current tuple; we don\u2019t need to compute the\nloss in order to compute the gradient. The algorithm can terminate when it converges (when\nthe gradient norm <\u000f), or when progress halts (for example when the loss starts going up on\na held-out set). Weights are initialized to 0 for logistic regression, but to small random values\nfor neural networks, as we\u2019ll see in Chapter 7.\nLet\u2019s assume the initial weights and bias in q0are all set to 0, and the initial learning\nratehis 0.1:\nw1=w2=b=0\nh=0:1\nThe single update step requires that we compute the gradient, multiplied by the\nlearning rate\nqt+1=qt\u0000h\u00d1qL(f(x(i);q);y(i))\nIn our mini example there are three parameters, so the gradient vector has 3 dimen-\nsions, for w1,w2, and b. We can compute the \ufb01rst gradient as follows:\n\u00d1w;bL=2\n64\u00b6LCE(\u02c6y;y)\n\u00b6w1\u00b6LCE(\u02c6y;y)\n\u00b6w2\u00b6LCE(\u02c6y;y)\n\u00b6b3\n75=2\n4(s(w\u0001x+b)\u0000y)x1\n(s(w\u0001x+b)\u0000y)x2\ns(w\u0001x+b)\u0000y3\n5=2\n4(s(0)\u00001)x1\n(s(0)\u00001)x2\ns(0)\u000013\n5=2\n4\u00000:5x1\n\u00000:5x2\n\u00000:53\n5=2\n4\u00001:5\n\u00001:0\n\u00000:53\n5\nNow that we have a gradient, we compute the new parameter vector q1by moving\nq0in the opposite direction from the gradient:\nq1=2\n4w1\nw2\nb3\n5\u0000h2\n4\u00001:5\n\u00001:0\n\u00000:53\n5=2\n4:15\n:1\n:053\n5\nSo after one step of gradient descent, the weights have shifted to be: w1=:15,\nw2=:1, and b=:05.\nNote that this observation xhappened to be a positive example. We would expect\nthat after seeing more negative examples with high counts of negative words, that\nthe weight w2would shift to have a negative value. 94 CHAPTER 5 \u2022 L OGISTIC REGRESSION\n5.6.4 Mini-batch training\nStochastic gradient descent is called stochastic because it chooses a single random\nexample at a time, moving the weights so as to improve performance on that single\nexample. That can result in very choppy movements, so it\u2019s common to compute the\ngradient over batches of training instances rather than a single instance.\nFor example in batch training we compute the gradient over the entire dataset. batch training\nBy seeing so many examples, batch training offers a superb estimate of which di-\nrection to move the weights, at the cost of spending a lot of time processing every\nsingle example in the training set to compute this perfect direction.\nA compromise is mini-batch training: we train on a group of mexamples (per- mini-batch\nhaps 512, or 1024) that is less than the whole dataset. (If mis the size of the dataset,\nthen we are doing batch gradient descent; if m=1, we are back to doing stochas-\ntic gradient descent.) Mini-batch training also has the advantage of computational\nef\ufb01ciency. The mini-batches can easily be vectorized, choosing the size of the mini-\nbatch based on the computational resources. This allows us to process all the exam-\nples in one mini-batch in parallel and then accumulate the loss, something that\u2019s not\npossible with individual or batch training.\nWe just need to de\ufb01ne mini-batch versions of the cross-entropy loss function\nwe de\ufb01ned in Section 5.5 and the gradient in Section 5.6.1. Let\u2019s extend the cross-\nentropy loss for one example from Eq. 5.23 to mini-batches of size m. We\u2019ll continue\nto use the notation that x(i)andy(i)mean the ith training features and training label,\nrespectively. We make the assumption that the training examples are independent:\nlogp(training labels ) = logmY\ni=1p(y(i)jx(i))\n=mX\ni=1logp(y(i)jx(i))\n=\u0000mX\ni=1LCE(\u02c6y(i);y(i)) (5.32)\nNow the cost function for the mini-batch of mexamples is the average loss for each\nexample:\nCost(\u02c6y;y) =1\nmmX\ni=1LCE(\u02c6y(i);y(i))\n=\u00001\nmmX\ni=1y(i)logs(w\u0001x(i)+b)+(1\u0000y(i))log\u0010\n1\u0000s(w\u0001x(i)+b)\u0011\n(5.33)\nThe mini-batch gradient is the average of the individual gradients from Eq. 5.30:\n\u00b6Cost(\u02c6y;y)\n\u00b6wj=1\nmmX\ni=1h\ns(w\u0001x(i)+b)\u0000y(i)i\nx(i)\nj(5.34)\nInstead of using the sum notation, we can more ef\ufb01ciently compute the gradient\nin its matrix form, following the vectorization we saw on page 83, where we have\na matrix Xof size [m\u0002f]representing the minputs in the batch, and a vector yof\nsize[m\u00021]representing the correct outputs: 5.7 \u2022 R EGULARIZATION 95\n\u00b6Cost(\u02c6y;y)\n\u00b6w=1\nm(\u02c6y\u0000y)|X\n=1\nm(s(Xw+b)\u0000y)|X (5.35)\n5.7 Regularization\nNumquam ponenda est pluralitas sine necessitate\n\u2018Plurality should never be proposed unless needed\u2019\nWilliam of Occam\nThere is a problem with learning weights that make the model perfectly match the\ntraining data. If a feature is perfectly predictive of the outcome because it happens\nto only occur in one class, it will be assigned a very high weight. The weights for\nfeatures will attempt to perfectly \ufb01t details of the training set, in fact too perfectly,\nmodeling noisy factors that just accidentally correlate with the class. This problem is\ncalled over\ufb01tting . A good model should be able to generalize well from the training over\ufb01tting\ngeneralize data to the unseen test set, but a model that over\ufb01ts will have poor generalization.\nTo avoid over\ufb01tting, a new regularization term R(q)is added to the loss func- regularization\ntion in Eq. 5.25, resulting in the following loss for a batch of mexamples (slightly\nrewritten from Eq. 5.25 to be maximizing log probability rather than minimizing\nloss, and removing the1\nmterm which doesn\u2019t affect the argmax):\n\u02c6q=argmax\nqmX\ni=1logP(y(i)jx(i))\u0000aR(q) (5.36)\nThe new regularization term R(q)is used to penalize large weights. Thus a setting\nof the weights that matches the training data perfectly\u2014 but uses many weights with\nhigh values to do so\u2014will be penalized more than a setting that matches the data a\nlittle less well, but does so using smaller weights. There are two common ways to\ncompute this regularization term R(q).L2 regularization is a quadratic function ofL2\nregularization\nthe weight values, named because it uses the (square of the) L2 norm of the weight\nvalues. The L2 norm, jjqjj2, is the same as the Euclidean distance of the vector q\nfrom the origin. If qconsists of nweights, then:\nR(q) =jjqjj2\n2=nX\nj=1q2\nj (5.37)\nThe L2 regularized loss function becomes:\n\u02c6q=argmax\nq\"mX\ni=1logP(y(i)jx(i))#\n\u0000anX\nj=1q2\nj (5.38)\nL1 regularization is a linear function of the weight values, named after the L1 normL1\nregularization\njjWjj1, the sum of the absolute values of the weights, or Manhattan distance (the 96 CHAPTER 5 \u2022 L OGISTIC REGRESSION\nManhattan distance is the distance you\u2019d have to walk between two points in a city\nwith a street grid like New York):\nR(q) =jjqjj1=nX\ni=1jqij (5.39)\nThe L1 regularized loss function becomes:\n\u02c6q=argmax\nq\"mX\ni=1logP(y(i)jx(i))#\n\u0000anX\nj=1jqjj (5.40)\nThese kinds of regularization come from statistics, where L1 regularization is called\nlasso regression (Tibshirani, 1996) and L2 regularization is called ridge regression , lasso\nridge and both are commonly used in language processing. L2 regularization is easier to\noptimize because of its simple derivative (the derivative of q2is just 2 q), while\nL1 regularization is more complex (the derivative of jqjis non-continuous at zero).\nBut while L2 prefers weight vectors with many small weights, L1 prefers sparse\nsolutions with some larger weights but many more weights set to zero. Thus L1\nregularization leads to much sparser weight vectors, that is, far fewer features.\nBoth L1 and L2 regularization have Bayesian interpretations as constraints on\nthe prior of how weights should look. L1 regularization can be viewed as a Laplace\nprior on the weights. L2 regularization corresponds to assuming that weights are\ndistributed according to a Gaussian distribution with mean m=0. In a Gaussian\nor normal distribution, the further away a value is from the mean, the lower its\nprobability (scaled by the variance s). By using a Gaussian prior on the weights, we\nare saying that weights prefer to have the value 0. A Gaussian for a weight qjis\n1q\n2ps2\njexp \n\u0000(qj\u0000mj)2\n2s2\nj!\n(5.41)\nIf we multiply each weight by a Gaussian prior on the weight, we are thus maximiz-\ning the following constraint:\n\u02c6q=argmax\nqmY\ni=1P(y(i)jx(i))\u0002nY\nj=11q\n2ps2\njexp \n\u0000(qj\u0000mj)2\n2s2\nj!\n(5.42)\nwhich in log space, with m=0, and assuming 2 s2=1, corresponds to\n\u02c6q=argmax\nqmX\ni=1logP(y(i)jx(i))\u0000anX\nj=1q2\nj (5.43)\nwhich is in the same form as Eq. 5.38.\n5.8 Learning in Multinomial Logistic Regression\nThe loss function for multinomial logistic regression generalizes the loss function\nfor binary logistic regression from 2 to Kclasses. Recall that that the cross-entropy\nloss for binary logistic regression (repeated from Eq. 5.23) is:\nLCE(\u02c6y;y) =\u0000logp(yjx) =\u0000[ylog \u02c6y+(1\u0000y)log(1\u0000\u02c6y)] (5.44) 5.8 \u2022 L EARNING IN MULTINOMIAL LOGISTIC REGRESSION 97\nThe loss function for multinomial logistic regression generalizes the two terms in\nEq. 5.44 (one that is non-zero when y=1 and one that is non-zero when y=0) to\nKterms. As we mentioned above, for multinomial regression we\u2019ll represent both y\nand\u02c6yas vectors. The true label yis a vector with Kelements, each corresponding\nto a class, with yc=1 if the correct class is c, with all other elements of ybeing 0.\nAnd our classi\ufb01er will produce an estimate vector with Kelements \u02c6y, each element\n\u02c6ykof which represents the estimated probability p(yk=1jx).\nThe loss function for a single example x, generalizing from binary logistic re-\ngression, is the sum of the logs of the Koutput classes, each weighted by the indi-\ncator function yk(Eq. 5.45). This turns out to be just the negative log probability of\nthe correct class c(Eq. 5.46):\nLCE(\u02c6y;y) =\u0000KX\nk=1yklog \u02c6yk (5.45)\n=\u0000log \u02c6yc;(where cis the correct class) (5.46)\n=\u0000log \u02c6p(yc=1jx)(where cis the correct class)\n=\u0000logexp(wc\u0001x+bc)PK\nj=1exp(wj\u0001x+bj)(cis the correct class) (5.47)\nHow did we get from Eq. 5.45 to Eq. 5.46? Because only one class (let\u2019s call it c) is\nthe correct one, the vector ytakes the value 1 only for this value of k, i.e., has yc=1\nandyj=08j6=c. That means the terms in the sum in Eq. 5.45 will all be 0 except\nfor the term corresponding to the true class c. Hence the cross-entropy loss is simply\nthe log of the output probability corresponding to the correct class, and we therefore\nalso call Eq. 5.46 the negative log likelihood loss .negative log\nlikelihood loss\nOf course for gradient descent we don\u2019t need the loss, we need its gradient. The\ngradient for a single example turns out to be very similar to the gradient for binary\nlogistic regression, (\u02c6y\u0000y)x, that we saw in Eq. 5.30. Let\u2019s consider one piece of the\ngradient, the derivative for a single weight. For each class k, the weight of the ith\nelement of input xiswk;i. What is the partial derivative of the loss with respect to\nwk;i? This derivative turns out to be just the difference between the true value for the\nclass k(which is either 1 or 0) and the probability the classi\ufb01er outputs for class k,\nweighted by the value of the input xicorresponding to the ith element of the weight\nvector for class k:\n\u00b6LCE\n\u00b6wk;i=\u0000(yk\u0000\u02c6yk)xi\n=\u0000(yk\u0000p(yk=1jx))xi\n=\u0000 \nyk\u0000exp(wk\u0001x+bk)PK\nj=1exp(wj\u0001x+bj)!\nxi (5.48)\nWe\u2019ll return to this case of the gradient for softmax regression when we introduce\nneural networks in Chapter 7, and at that time we\u2019ll also discuss the derivation of\nthis gradient in equations Eq. 7.33\u2013Eq. 7.41. 98 CHAPTER 5 \u2022 L OGISTIC REGRESSION\n5.9 Interpreting models\nOften we want to know more than just the correct classi\ufb01cation of an observation.\nWe want to know why the classi\ufb01er made the decision it did. That is, we want our\ndecision to be interpretable . Interpretability can be hard to de\ufb01ne strictly, but the interpretable\ncore idea is that as humans we should know why our algorithms reach the conclu-\nsions they do. Because the features to logistic regression are often human-designed,\none way to understand a classi\ufb01er\u2019s decision is to understand the role each feature\nplays in the decision. Logistic regression can be combined with statistical tests (the\nlikelihood ratio test, or the Wald test); investigating whether a particular feature is\nsigni\ufb01cant by one of these tests, or inspecting its magnitude (how large is the weight\nwassociated with the feature?) can help us interpret why the classi\ufb01er made the\ndecision it makes. This is enormously important for building transparent models.\nFurthermore, in addition to its use as a classi\ufb01er, logistic regression in NLP and\nmany other \ufb01elds is widely used as an analytic tool for testing hypotheses about the\neffect of various explanatory variables (features). In text classi\ufb01cation, perhaps we\nwant to know if logically negative words ( no, not, never ) are more likely to be asso-\nciated with negative sentiment, or if negative reviews of movies are more likely to\ndiscuss the cinematography. However, in doing so it\u2019s necessary to control for po-\ntential confounds: other factors that might in\ufb02uence sentiment (the movie genre, the\nyear it was made, perhaps the length of the review in words). Or we might be study-\ning the relationship between NLP-extracted linguistic features and non-linguistic\noutcomes (hospital readmissions, political outcomes, or product sales), but need to\ncontrol for confounds (the age of the patient, the county of voting, the brand of the\nproduct). In such cases, logistic regression allows us to test whether some feature is\nassociated with some outcome above and beyond the effect of other features.\n5.10 Advanced: Deriving the Gradient Equation\nIn this section we give the derivation of the gradient of the cross-entropy loss func-\ntion LCEfor logistic regression. Let\u2019s start with some quick calculus refreshers.\nFirst, the derivative of ln (x):\nd\ndxln(x) =1\nx(5.49)\nSecond, the (very elegant) derivative of the sigmoid:\nds(z)\ndz=s(z)(1\u0000s(z)) (5.50)\nFinally, the chain rule of derivatives. Suppose we are computing the derivative chain rule\nof a composite function f(x) =u(v(x)). The derivative of f(x)is the derivative of\nu(x)with respect to v(x)times the derivative of v(x)with respect to x:\nd f\ndx=du\ndv\u0001dv\ndx(5.51)\nFirst, we want to know the derivative of the loss function with respect to a single\nweight wj(we\u2019ll need to compute it for each weight, and for the bias): 5.11 \u2022 S UMMARY 99\n\u00b6LCE\n\u00b6wj=\u00b6\n\u00b6wj\u0000[ylogs(w\u0001x+b)+(1\u0000y)log(1\u0000s(w\u0001x+b))]\n=\u0000\u0014\u00b6\n\u00b6wjylogs(w\u0001x+b)+\u00b6\n\u00b6wj(1\u0000y)log[1\u0000s(w\u0001x+b)]\u0015\n(5.52)\nNext, using the chain rule, and relying on the derivative of log:\n\u00b6LCE\n\u00b6wj=\u0000y\ns(w\u0001x+b)\u00b6\n\u00b6wjs(w\u0001x+b)\u00001\u0000y\n1\u0000s(w\u0001x+b)\u00b6\n\u00b6wj1\u0000s(w\u0001x+b)\n(5.53)\nRearranging terms:\n\u00b6LCE\n\u00b6wj=\u0000\u0014y\ns(w\u0001x+b)\u00001\u0000y\n1\u0000s(w\u0001x+b)\u0015\u00b6\n\u00b6wjs(w\u0001x+b)\n(5.54)\nAnd now plugging in the derivative of the sigmoid, and using the chain rule one\nmore time, we end up with Eq. 5.55:\n\u00b6LCE\n\u00b6wj=\u0000\u0014y\u0000s(w\u0001x+b)\ns(w\u0001x+b)[1\u0000s(w\u0001x+b)]\u0015\ns(w\u0001x+b)[1\u0000s(w\u0001x+b)]\u00b6(w\u0001x+b)\n\u00b6wj\n=\u0000\u0014y\u0000s(w\u0001x+b)\ns(w\u0001x+b)[1\u0000s(w\u0001x+b)]\u0015\ns(w\u0001x+b)[1\u0000s(w\u0001x+b)]xj\n=\u0000[y\u0000s(w\u0001x+b)]xj\n= [s(w\u0001x+b)\u0000y]xj (5.55)\n5.11 Summary\nThis chapter introduced the logistic regression model of classi\ufb01cation .\n\u2022 Logistic regression is a supervised machine learning classi\ufb01er that extracts\nreal-valued features from the input, multiplies each by a weight, sums them,\nand passes the sum through a sigmoid function to generate a probability. A\nthreshold is used to make a decision.\n\u2022 Logistic regression can be used with two classes (e.g., positive and negative\nsentiment) or with multiple classes ( multinomial logistic regression , for ex-\nample for n-ary text classi\ufb01cation, part-of-speech labeling, etc.).\n\u2022 Multinomial logistic regression uses the softmax function to compute proba-\nbilities.\n\u2022 The weights (vector wand bias b) are learned from a labeled training set via a\nloss function, such as the cross-entropy loss , that must be minimized.\n\u2022 Minimizing this loss function is a convex optimization problem, and iterative\nalgorithms like gradient descent are used to \ufb01nd the optimal weights.\n\u2022Regularization is used to avoid over\ufb01tting.\n\u2022 Logistic regression is also one of the most useful analytic tools, because of its\nability to transparently study the importance of individual features. 100 CHAPTER 5 \u2022 L OGISTIC REGRESSION\nBibliographical and Historical Notes\nLogistic regression was developed in the \ufb01eld of statistics, where it was used for\nthe analysis of binary data by the 1960s, and was particularly common in medicine\n(Cox, 1969). Starting in the late 1970s it became widely used in linguistics as one\nof the formal foundations of the study of linguistic variation (Sankoff and Labov,\n1979).\nNonetheless, logistic regression didn\u2019t become common in natural language pro-\ncessing until the 1990s, when it seems to have appeared simultaneously from two\ndirections. The \ufb01rst source was the neighboring \ufb01elds of information retrieval and\nspeech processing, both of which had made use of regression, and both of which\nlent many other statistical techniques to NLP. Indeed a very early use of logistic\nregression for document routing was one of the \ufb01rst NLP applications to use (LSI)\nembeddings as word representations (Sch \u00a8utze et al., 1995).\nAt the same time in the early 1990s logistic regression was developed and ap-\nplied to NLP at IBM Research under the name maximum entropy modeling ormaximum\nentropy\nmaxent (Berger et al., 1996), seemingly independent of the statistical literature. Un-\nder that name it was applied to language modeling (Rosenfeld, 1996), part-of-speech\ntagging (Ratnaparkhi, 1996), parsing (Ratnaparkhi, 1997), coreference resolution\n(Kehler, 1997b), and text classi\ufb01cation (Nigam et al., 1999).\nMore on classi\ufb01cation can be found in machine learning textbooks (Hastie et al.\n2001, Witten and Frank 2005, Bishop 2006, Murphy 2012).\nExercises CHAPTER\n6Vector Semantics and\nEmbeddings\n\u8343\u8005\u6240\u4ee5\u5728\u9c7c\uff0c\u5f97\u9c7c\u800c\u5fd8\u8343Nets are for \ufb01sh;\nOnce you get the \ufb01sh, you can forget the net.\n\u8a00\u8005\u6240\u4ee5\u5728\u610f\uff0c\u5f97\u610f\u800c\u5fd8\u8a00Words are for meaning;\nOnce you get the meaning, you can forget the words\n\u5e84\u5b50(Zhuangzi), Chapter 26\nThe asphalt that Los Angeles is famous for occurs mainly on its freeways. But\nin the middle of the city is another patch of asphalt, the La Brea tar pits, and this\nasphalt preserves millions of fossil bones from the last of the Ice Ages of the Pleis-\ntocene Epoch. One of these fossils is the Smilodon , or saber-toothed tiger, instantly\nrecognizable by its long canines. Five million years ago or so, a completely different\nsaber-tooth tiger called Thylacosmilus lived\nin Argentina and other parts of South Amer-\nica. Thylacosmilus was a marsupial whereas\nSmilodon was a placental mammal, but Thy-\nlacosmilus had the same long upper canines\nand, like Smilodon, had a protective bone\n\ufb02ange on the lower jaw. The similarity of\nthese two mammals is one of many examples\nof parallel or convergent evolution, in which particular contexts or environments\nlead to the evolution of very similar structures in different species (Gould, 1980).\nThe role of context is also important in the similarity of a less biological kind\nof organism: the word. Words that occur in similar contexts tend to have similar\nmeanings . This link between similarity in how words are distributed and similarity\nin what they mean is called the distributional hypothesis . The hypothesis wasdistributional\nhypothesis\n\ufb01rst formulated in the 1950s by linguists like Joos (1950), Harris (1954), and Firth\n(1957), who noticed that words which are synonyms (like oculist andeye-doctor )\ntended to occur in the same environment (e.g., near words like eyeorexamined )\nwith the amount of meaning difference between two words \u201ccorresponding roughly\nto the amount of difference in their environments\u201d (Harris, 1954, p. 157).\nIn this chapter we introduce vector semantics , which instantiates this linguisticvector\nsemantics\nhypothesis by learning representations of the meaning of words, called embeddings , embeddings\ndirectly from their distributions in texts. These representations are used in every nat-\nural language processing application that makes use of meaning, and the static em-\nbeddings we introduce here underlie the more powerful dynamic or contextualized\nembeddings likeBERT that we will see in Chapter 11.\nThese word representations are also the \ufb01rst example in this book of repre-\nsentation learning , automatically learning useful representations of the input text.representation\nlearning\nFinding such self-supervised ways to learn representations of the input, instead of\ncreating representations by hand via feature engineering , is an important focus of\nNLP research (Bengio et al., 2013). 102 CHAPTER 6 \u2022 V ECTOR SEMANTICS AND EMBEDDINGS\n6.1 Lexical Semantics\nLet\u2019s begin by introducing some basic principles of word meaning. How should\nwe represent the meaning of a word? In the n-gram models of Chapter 3, and in\nclassical NLP applications, our only representation of a word is as a string of letters,\nor an index in a vocabulary list. This representation is not that different from a\ntradition in philosophy, perhaps you\u2019ve seen it in introductory logic classes, in which\nthe meaning of words is represented by just spelling the word with small capital\nletters; representing the meaning of \u201cdog\u201d as DOG, and \u201ccat\u201d as CAT, or by using an\napostrophe ( DOG \u2019).\nRepresenting the meaning of a word by capitalizing it is a pretty unsatisfactory\nmodel. You might have seen a version of a joke due originally to semanticist Barbara\nPartee (Carlson, 1977):\nQ: What\u2019s the meaning of life?\nA:LIFE \u2019\nSurely we can do better than this! After all, we\u2019ll want a model of word meaning\nto do all sorts of things for us. It should tell us that some words have similar mean-\nings ( catis similar to dog), others are antonyms ( cold is the opposite of hot), some\nhave positive connotations ( happy ) while others have negative connotations ( sad). It\nshould represent the fact that the meanings of buy,sell, and payoffer differing per-\nspectives on the same underlying purchasing event. (If I buy something from you,\nyou\u2019ve probably sold it to me, and I likely paid you.) More generally, a model of\nword meaning should allow us to draw inferences to address meaning-related tasks\nlike question-answering or dialogue.\nIn this section we summarize some of these desiderata, drawing on results in the\nlinguistic study of word meaning, which is called lexical semantics ; we\u2019ll return tolexical\nsemantics\nand expand on this list in Appendix G and Chapter 21.\nLemmas and Senses Let\u2019s start by looking at how one word (we\u2019ll choose mouse )\nmight be de\ufb01ned in a dictionary (simpli\ufb01ed from the online dictionary WordNet):\nmouse (N)\n1. any of numerous small rodents...\n2. a hand-operated device that controls a cursor...\nHere the form mouse is the lemma , also called the citation form . The form lemma\ncitation form mouse would also be the lemma for the word mice ; dictionaries don\u2019t have separate\nde\ufb01nitions for in\ufb02ected forms like mice . Similarly sing is the lemma for sing,sang ,\nsung . In many languages the in\ufb01nitive form is used as the lemma for the verb, so\nSpanish dormir \u201cto sleep\u201d is the lemma for duermes \u201cyou sleep\u201d. The speci\ufb01c forms\nsung orcarpets orsing orduermes are called wordforms . wordform\nAs the example above shows, each lemma can have multiple meanings; the\nlemma mouse can refer to the rodent or the cursor control device. We call each\nof these aspects of the meaning of mouse aword sense . The fact that lemmas can\nbepolysemous (have multiple senses) can make interpretation dif\ufb01cult (is someone\nwho types \u201cmouse info\u201d into a search engine looking for a pet or a tool?). Chap-\nter 11 and Appendix G will discuss the problem of polysemy, and introduce word\nsense disambiguation , the task of determining which sense of a word is being used\nin a particular context.\nSynonymy One important component of word meaning is the relationship be-\ntween word senses. For example when one word has a sense whose meaning is 6.1 \u2022 L EXICAL SEMANTICS 103\nidentical to a sense of another word, or nearly identical, we say the two senses of\nthose two words are synonyms . Synonyms include such pairs as synonym\ncouch/sofa vomit/throw up \ufb01lbert/hazelnut car/automobile\nA more formal de\ufb01nition of synonymy (between words rather than senses) is that\ntwo words are synonymous if they are substitutable for one another in any sentence\nwithout changing the truth conditions of the sentence, the situations in which the\nsentence would be true.\nWhile substitutions between some pairs of words like car/automobile orwa-\nter/H2Oare truth preserving, the words are still not identical in meaning. Indeed,\nprobably no two words are absolutely identical in meaning. One of the fundamental\ntenets of semantics, called the principle of contrast (Girard 1718, Br \u00b4eal 1897, Clarkprinciple of\ncontrast\n1987), states that a difference in linguistic form is always associated with some dif-\nference in meaning. For example, the word H2Ois used in scienti\ufb01c contexts and\nwould be inappropriate in a hiking guide\u2014 water would be more appropriate\u2014 and\nthis genre difference is part of the meaning of the word. In practice, the word syn-\nonym is therefore used to describe a relationship of approximate or rough synonymy.\nWord Similarity While words don\u2019t have many synonyms, most words do have\nlots of similar words. Catis not a synonym of dog, but cats anddogs are certainly\nsimilar words. In moving from synonymy to similarity, it will be useful to shift from\ntalking about relations between word senses (like synonymy) to relations between\nwords (like similarity). Dealing with words avoids having to commit to a particular\nrepresentation of word senses, which will turn out to simplify our task.\nThe notion of word similarity is very useful in larger semantic tasks. Knowing similarity\nhow similar two words are can help in computing how similar the meaning of two\nphrases or sentences are, a very important component of tasks like question answer-\ning, paraphrasing, and summarization. One way of getting values for word similarity\nis to ask humans to judge how similar one word is to another. A number of datasets\nhave resulted from such experiments. For example the SimLex-999 dataset (Hill\net al., 2015) gives values on a scale from 0 to 10, like the examples below, which\nrange from near-synonyms ( vanish ,disappear ) to pairs that scarcely seem to have\nanything in common ( hole,agreement ):\nvanish disappear 9.8\nbelief impression 5.95\nmuscle bone 3.65\nmodest \ufb02exible 0.98\nhole agreement 0.3\nWord Relatedness The meaning of two words can be related in ways other than\nsimilarity. One such class of connections is called word relatedness (Budanitsky relatedness\nand Hirst, 2006), also traditionally called word association in psychology. association\nConsider the meanings of the words coffee andcup. Coffee is not similar to cup;\nthey share practically no features (coffee is a plant or a beverage, while a cup is a\nmanufactured object with a particular shape). But coffee and cup are clearly related;\nthey are associated by co-participating in an everyday event (the event of drinking\ncoffee out of a cup). Similarly scalpel andsurgeon are not similar but are related\neventively (a surgeon tends to make use of a scalpel).\nOne common kind of relatedness between words is if they belong to the same\nsemantic \ufb01eld . A semantic \ufb01eld is a set of words which cover a particular semantic semantic \ufb01eld\ndomain and bear structured relations with each other. For example, words might be 104 CHAPTER 6 \u2022 V ECTOR SEMANTICS AND EMBEDDINGS\nrelated by being in the semantic \ufb01eld of hospitals ( surgeon ,scalpel ,nurse ,anes-\nthetic ,hospital ), restaurants ( waiter ,menu ,plate ,food,chef), or houses ( door ,roof,\nkitchen ,family ,bed). Semantic \ufb01elds are also related to topic models , like Latent topic models\nDirichlet Allocation ,LDA , which apply unsupervised learning on large sets of texts\nto induce sets of associated words from text. Semantic \ufb01elds and topic models are\nvery useful tools for discovering topical structure in documents.\nIn Appendix G we\u2019ll introduce more relations between senses like hypernymy\norIS-A ,antonymy (opposites) and meronymy (part-whole relations).\nSemantic Frames and Roles Closely related to semantic \ufb01elds is the idea of a\nsemantic frame . A semantic frame is a set of words that denote perspectives or semantic frame\nparticipants in a particular type of event. A commercial transaction, for example,\nis a kind of event in which one entity trades money to another entity in return for\nsome good or service, after which the good changes hands or perhaps the service is\nperformed. This event can be encoded lexically by using verbs like buy(the event\nfrom the perspective of the buyer), sell(from the perspective of the seller), pay\n(focusing on the monetary aspect), or nouns like buyer . Frames have semantic roles\n(like buyer ,seller ,goods ,money ), and words in a sentence can take on these roles.\nKnowing that buyandsellhave this relation makes it possible for a system to\nknow that a sentence like Sam bought the book from Ling could be paraphrased as\nLing sold the book to Sam , and that Sam has the role of the buyer in the frame and\nLing the seller . Being able to recognize such paraphrases is important for question\nanswering, and can help in shifting perspective for machine translation.\nConnotation Finally, words have affective meanings orconnotations . The word connotations\nconnotation has different meanings in different \ufb01elds, but here we use it to mean the\naspects of a word\u2019s meaning that are related to a writer or reader\u2019s emotions, senti-\nment, opinions, or evaluations. For example some words have positive connotations\n(wonderful ) while others have negative connotations ( dreary ). Even words whose\nmeanings are similar in other ways can vary in connotation; consider the difference\nin connotations between fake,knockoff ,forgery , on the one hand, and copy ,replica ,\nreproduction on the other, or innocent (positive connotation) and naive (negative\nconnotation). Some words describe positive evaluation ( great ,love) and others neg-\native evaluation ( terrible ,hate). Positive or negative evaluation language is called\nsentiment , as we saw in Chapter 4, and word sentiment plays a role in important sentiment\ntasks like sentiment analysis, stance detection, and applications of NLP to the lan-\nguage of politics and consumer reviews.\nEarly work on affective meaning (Osgood et al., 1957) found that words varied\nalong three important dimensions of affective meaning:\nvalence: the pleasantness of the stimulus\narousal: the intensity of emotion provoked by the stimulus\ndominance: the degree of control exerted by the stimulus\nThus words like happy orsatis\ufb01ed are high on valence, while unhappy oran-\nnoyed are low on valence. Excited is high on arousal, while calm is low on arousal.\nControlling is high on dominance, while awed orin\ufb02uenced are low on dominance.\nEach word is thus represented by three numbers, corresponding to its value on each\nof the three dimensions: 6.2 \u2022 V ECTOR SEMANTICS 105\nValence Arousal Dominance\ncourageous 8.05 5.5 7.38\nmusic 7.67 5.57 6.5\nheartbreak 2.45 5.65 3.58\ncub 6.71 3.95 4.24\nOsgood et al. (1957) noticed that in using these 3 numbers to represent the\nmeaning of a word, the model was representing each word as a point in a three-\ndimensional space, a vector whose three dimensions corresponded to the word\u2019s\nrating on the three scales. This revolutionary idea that word meaning could be rep-\nresented as a point in space (e.g., that part of the meaning of heartbreak can be\nrepresented as the point [2:45;5:65;3:58]) was the \ufb01rst expression of the vector se-\nmantics models that we introduce next.\n6.2 Vector Semantics\nVector semantics is the standard way to represent word meaning in NLP, helpingvector\nsemantics\nus model many of the aspects of word meaning we saw in the previous section. The\nroots of the model lie in the 1950s when two big ideas converged: Osgood\u2019s 1957\nidea mentioned above to use a point in three-dimensional space to represent the\nconnotation of a word, and the proposal by linguists like Joos (1950), Harris (1954),\nand Firth (1957) to de\ufb01ne the meaning of a word by its distribution in language\nuse, meaning its neighboring words or grammatical environments. Their idea was\nthat two words that occur in very similar distributions (whose neighboring words are\nsimilar) have similar meanings.\nFor example, suppose you didn\u2019t know the meaning of the word ongchoi (a re-\ncent borrowing from Cantonese) but you see it in the following contexts:\n(6.1) Ongchoi is delicious sauteed with garlic.\n(6.2) Ongchoi is superb over rice.\n(6.3) ...ongchoi leaves with salty sauces...\nAnd suppose that you had seen many of these context words in other contexts:\n(6.4) ...spinach sauteed with garlic over rice...\n(6.5) ...chard stems and leaves are delicious...\n(6.6) ...collard greens and other salty leafy greens\nThe fact that ongchoi occurs with words like riceandgarlic anddelicious and\nsalty , as do words like spinach ,chard , and collard greens might suggest that ongchoi\nis a leafy green similar to these other leafy greens.1We can do the same thing\ncomputationally by just counting words in the context of ongchoi .\nThe idea of vector semantics is to represent a word as a point in a multidimen-\nsional semantic space that is derived (in ways we\u2019ll see) from the distributions of\nword neighbors. Vectors for representing words are called embeddings (although embeddings\nthe term is sometimes more strictly applied only to dense vectors like word2vec\n(Section 6.8), rather than sparse tf-idf or PPMI vectors (Section 6.3-Section 6.6)).\nThe word \u201cembedding\u201d derives from its mathematical sense as a mapping from one\nspace or structure to another, although the meaning has shifted; see the end of the\nchapter.\n1It\u2019s in fact Ipomoea aquatica , a relative of morning glory sometimes called water spinach in English. 106 CHAPTER 6 \u2022 V ECTOR SEMANTICS AND EMBEDDINGS\ngoodnicebadworstnot good\nwonderfulamazingterri\ufb01cdislikeworsevery goodincredibly goodfantasticincredibly badnowyouithatwithbyto\u2019sareisathan\nFigure 6.1 A two-dimensional (t-SNE) projection of embeddings for some words and\nphrases, showing that words with similar meanings are nearby in space. The original 60-\ndimensional embeddings were trained for sentiment analysis. Simpli\ufb01ed from Li et al. (2015)\nwith colors added for explanation.\nFig. 6.1 shows a visualization of embeddings learned for sentiment analysis,\nshowing the location of selected words projected down from 60-dimensional space\ninto a two dimensional space. Notice the distinct regions containing positive words,\nnegative words, and neutral function words.\nThe \ufb01ne-grained model of word similarity of vector semantics offers enormous\npower to NLP applications. NLP applications like the sentiment classi\ufb01ers of Chap-\nter 4 or Chapter 5 depend on the same words appearing in the training and test sets.\nBut by representing words as embeddings, a classi\ufb01er can assign sentiment as long\nas it sees some words with similar meanings . And as we\u2019ll see, vector semantic\nmodels can be learned automatically from text without supervision.\nIn this chapter we\u2019ll introduce the two most commonly used models. In the tf-idf\nmodel, an important baseline, the meaning of a word is de\ufb01ned by a simple function\nof the counts of nearby words. We will see that this method results in very long\nvectors that are sparse , i.e. mostly zeros (since most words simply never occur in\nthe context of others). We\u2019ll introduce the word2vec model family for construct-\ning short, dense vectors that have useful semantic properties. We\u2019ll also introduce\nthecosine , the standard way to use embeddings to compute semantic similarity , be-\ntween two words, two sentences, or two documents, an important tool in practical\napplications like question answering, summarization, or automatic essay grading.\n6.3 Words and Vectors\n\u201cThe most important attributes of a vector in 3-space are fLocation, Location, Location g\u201d\nRandall Munroe, https://xkcd.com/2358/\nVector or distributional models of meaning are generally based on a co-occurrence\nmatrix , a way of representing how often words co-occur. We\u2019ll look at two popular\nmatrices: the term-document matrix and the term-term matrix.\n6.3.1 Vectors and documents\nIn aterm-document matrix , each row represents a word in the vocabulary and eachterm-document\nmatrix\ncolumn represents a document from some collection of documents. Fig. 6.2 shows a\nsmall selection from a term-document matrix showing the occurrence of four words\nin four plays by Shakespeare. Each cell in this matrix represents the number of times 6.3 \u2022 W ORDS AND VECTORS 107\na particular word (de\ufb01ned by the row) occurs in a particular document (de\ufb01ned by\nthe column). Thus foolappeared 58 times in Twelfth Night .\nAs You Like It Twelfth Night Julius Caesar Henry V\nbattle 1 0 7 13\ngood 114 80 62 89\nfool 36 58 1 4\nwit 20 15 2 3\nFigure 6.2 The term-document matrix for four words in four Shakespeare plays. Each cell\ncontains the number of times the (row) word occurs in the (column) document.\nThe term-document matrix of Fig. 6.2 was \ufb01rst de\ufb01ned as part of the vector\nspace model of information retrieval (Salton, 1971). In this model, a document isvector space\nmodel\nrepresented as a count vector, a column in Fig. 6.3.\nTo review some basic linear algebra, a vector is, at heart, just a list or array of vector\nnumbers. So As You Like It is represented as the list [1,114,36,20] (the \ufb01rst column\nvector in Fig. 6.3) and Julius Caesar is represented as the list [7,62,1,2] (the third\ncolumn vector). A vector space is a collection of vectors, and is characterized by vector space\nitsdimension . Vectors in a 3-dimensional vector space have an element for each dimension\ndimension of the space. We will loosely refer to a vector in a 4-dimensional space\nas a 4-dimensional vector, with one element along each dimension. In the example\nin Fig. 6.3, we\u2019ve chosen to make the document vectors of dimension 4, just so they\n\ufb01t on the page; in real term-document matrices, the document vectors would have\ndimensionalityjVj, the vocabulary size.\nThe ordering of the numbers in a vector space indicates the different dimensions\non which documents vary. The \ufb01rst dimension for both these vectors corresponds to\nthe number of times the word battle occurs, and we can compare each dimension,\nnoting for example that the vectors for As You Like It andTwelfth Night have similar\nvalues (1 and 0, respectively) for the \ufb01rst dimension.\nAs You Like It Twelfth Night Julius Caesar Henry V\nbattle 1 0 7 13\ngood 114 80 62 89\nfool 36 58 1 4\nwit 20 15 2 3\nFigure 6.3 The term-document matrix for four words in four Shakespeare plays. The red\nboxes show that each document is represented as a column vector of length four.\nWe can think of the vector for a document as a point in jVj-dimensional space;\nthus the documents in Fig. 6.3 are points in 4-dimensional space. Since 4-dimensional\nspaces are hard to visualize, Fig. 6.4 shows a visualization in two dimensions; we\u2019ve\narbitrarily chosen the dimensions corresponding to the words battle andfool.\nTerm-document matrices were originally de\ufb01ned as a means of \ufb01nding similar\ndocuments for the task of document information retrieval . Two documents that are\nsimilar will tend to have similar words, and if two documents have similar words\ntheir column vectors will tend to be similar. The vectors for the comedies As You\nLike It [1,114,36,20] and Twelfth Night [0,80,58,15] look a lot more like each other\n(more fools and wit than battles) than they look like Julius Caesar [7,62,1,2] or\nHenry V [13,89,4,3]. This is clear with the raw numbers; in the \ufb01rst dimension\n(battle) the comedies have low numbers and the others have high numbers, and we\ncan see it visually in Fig. 6.4; we\u2019ll see very shortly how to quantify this intuition\nmore formally. 108 CHAPTER 6 \u2022 V ECTOR SEMANTICS AND EMBEDDINGS\n51015202530510Henry V [4,13]As You Like It [36,1]Julius Caesar [1,7]battle foolTwelfth Night [58,0]1540\n354045505560\nFigure 6.4 A spatial visualization of the document vectors for the four Shakespeare play\ndocuments, showing just two of the dimensions, corresponding to the words battle andfool.\nThe comedies have high values for the fooldimension and low values for the battle dimension.\nA real term-document matrix, of course, wouldn\u2019t just have 4 rows and columns,\nlet alone 2. More generally, the term-document matrix has jVjrows (one for each\nword type in the vocabulary) and Dcolumns (one for each document in the collec-\ntion); as we\u2019ll see, vocabulary sizes are generally in the tens of thousands, and the\nnumber of documents can be enormous (think about all the pages on the web).\nInformation retrieval (IR) is the task of \ufb01nding the document dfrom the Dinformation\nretrieval\ndocuments in some collection that best matches a query q. For IR we\u2019ll therefore also\nrepresent a query by a vector, also of length jVj, and we\u2019ll need a way to compare\ntwo vectors to \ufb01nd how similar they are. (Doing IR will also require ef\ufb01cient ways\nto store and manipulate these vectors by making use of the convenient fact that these\nvectors are sparse, i.e., mostly zeros).\nLater in the chapter we\u2019ll introduce some of the components of this vector com-\nparison process: the tf-idf term weighting, and the cosine similarity metric.\n6.3.2 Words as vectors: document dimensions\nWe\u2019ve seen that documents can be represented as vectors in a vector space. But\nvector semantics can also be used to represent the meaning of words . We do this\nby associating each word with a word vector\u2014 a row vector rather than a column row vector\nvector, hence with different dimensions, as shown in Fig. 6.5. The four dimensions\nof the vector for fool, [36,58,1,4], correspond to the four Shakespeare plays. Word\ncounts in the same four dimensions are used to form the vectors for the other 3\nwords: wit, [20,15,2,3]; battle , [1,0,7,13]; and good [114,80,62,89].\nAs You Like It Twelfth Night Julius Caesar Henry V\nbattle 1 0 7 13\ngood 114 80 62 89\nfool 36 58 1 4\nwit 20 15 2 3\nFigure 6.5 The term-document matrix for four words in four Shakespeare plays. The red\nboxes show that each word is represented as a row vector of length four.\nFor documents, we saw that similar documents had similar vectors, because sim-\nilar documents tend to have similar words. This same principle applies to words:\nsimilar words have similar vectors because they tend to occur in similar documents.\nThe term-document matrix thus lets us represent the meaning of a word by the doc-\numents it tends to occur in. 6.3 \u2022 W ORDS AND VECTORS 109\n6.3.3 Words as vectors: word dimensions\nAn alternative to using the term-document matrix to represent words as vectors of\ndocument counts, is to use the term-term matrix , also called the word-word ma-\ntrixor the term-context matrix , in which the columns are labeled by words ratherword-word\nmatrix\nthan documents. This matrix is thus of dimensionality jVj\u0002jVjand each cell records\nthe number of times the row (target) word and the column (context) word co-occur\nin some context in some training corpus. The context could be the document, in\nwhich case the cell represents the number of times the two words appear in the same\ndocument. It is most common, however, to use smaller contexts, generally a win-\ndow around the word, for example of 4 words to the left and 4 words to the right,\nin which case the cell represents the number of times (in some training corpus) the\ncolumn word occurs in such a \u00064 word window around the row word. Here are four\nexamples of words in their windows:\nis traditionally followed by cherry pie, a traditional dessert\noften mixed, such as strawberry rhubarb pie. Apple pie\ncomputer peripherals and personal digital assistants. These devices usually\na computer. This includes information available on the internet\nIf we then take every occurrence of each word (say strawberry ) and count the\ncontext words around it, we get a word-word co-occurrence matrix. Fig. 6.6 shows a\nsimpli\ufb01ed subset of the word-word co-occurrence matrix for these four words com-\nputed from the Wikipedia corpus (Davies, 2015).\naardvark ... computer data result pie sugar ...\ncherry 0 ... 2 8 9 442 25 ...\nstrawberry 0 ... 0 0 1 60 19 ...\ndigital 0 ... 1670 1683 85 5 4 ...\ninformation 0 ... 3325 3982 378 5 13 ...\nFigure 6.6 Co-occurrence vectors for four words in the Wikipedia corpus, showing six of\nthe dimensions (hand-picked for pedagogical purposes). The vector for digital is outlined in\nred. Note that a real vector would have vastly more dimensions and thus be much sparser.\nNote in Fig. 6.6 that the two words cherry andstrawberry are more similar to\neach other (both pieandsugar tend to occur in their window) than they are to other\nwords like digital ; conversely, digital andinformation are more similar to each other\nthan, say, to strawberry . Fig. 6.7 shows a spatial visualization.\n100020003000400010002000digital [1683,1670]computer datainformation [3982,3325] 30004000\nFigure 6.7 A spatial visualization of word vectors for digital andinformation , showing just\ntwo of the dimensions, corresponding to the words data andcomputer .\nNote thatjVj, the dimensionality of the vector, is generally the size of the vo-\ncabulary, often between 10,000 and 50,000 words (using the most frequent words 110 CHAPTER 6 \u2022 V ECTOR SEMANTICS AND EMBEDDINGS\nin the training corpus; keeping words after about the most frequent 50,000 or so is\ngenerally not helpful). Since most of these numbers are zero these are sparse vector\nrepresentations; there are ef\ufb01cient algorithms for storing and computing with sparse\nmatrices.\nNow that we have some intuitions, let\u2019s move on to examine the details of com-\nputing word similarity. Afterwards we\u2019ll discuss methods for weighting cells.\n6.4 Cosine for measuring similarity\nTo measure similarity between two target words vandw, we need a metric that\ntakes two vectors (of the same dimensionality, either both with words as dimensions,\nhence of lengthjVj, or both with documents as dimensions, of length jDj) and gives\na measure of their similarity. By far the most common similarity metric is the cosine\nof the angle between the vectors.\nThe cosine\u2014like most measures for vector similarity used in NLP\u2014is based on\nthedot product operator from linear algebra, also called the inner product : dot product\ninner product\ndot product (v;w) =v\u0001w=NX\ni=1viwi=v1w1+v2w2+:::+vNwN (6.7)\nThe dot product acts as a similarity metric because it will tend to be high just when\nthe two vectors have large values in the same dimensions. Alternatively, vectors that\nhave zeros in different dimensions\u2014orthogonal vectors\u2014will have a dot product of\n0, representing their strong dissimilarity.\nThis raw dot product, however, has a problem as a similarity metric: it favors\nlong vectors. The vector length is de\ufb01ned as vector length\njvj=vuutNX\ni=1v2\ni(6.8)\nThe dot product is higher if a vector is longer, with higher values in each dimension.\nMore frequent words have longer vectors, since they tend to co-occur with more\nwords and have higher co-occurrence values with each of them. The raw dot product\nthus will be higher for frequent words. But this is a problem; we\u2019d like a similarity\nmetric that tells us how similar two words are regardless of their frequency.\nWe modify the dot product to normalize for the vector length by dividing the\ndot product by the lengths of each of the two vectors. This normalized dot product\nturns out to be the same as the cosine of the angle between the two vectors, following\nfrom the de\ufb01nition of the dot product between two vectors aandb:\na\u0001b=jajjbjcosq\na\u0001b\njajjbj=cosq (6.9)\nThecosine similarity metric between two vectors vandwthus can be computed as: cosine 6.5 \u2022 TF-IDF: W EIGHING TERMS IN THE VECTOR 111\ncosine (v;w) =v\u0001w\njvjjwj=NX\ni=1viwi\nvuutNX\ni=1v2\nivuutNX\ni=1w2\ni(6.10)\nFor some applications we pre-normalize each vector, by dividing it by its length,\ncreating a unit vector of length 1. Thus we could compute a unit vector from aby unit vector\ndividing it byjaj. For unit vectors, the dot product is the same as the cosine.\nThe cosine value ranges from 1 for vectors pointing in the same direction, through\n0 for orthogonal vectors, to -1 for vectors pointing in opposite directions. But since\nraw frequency values are non-negative, the cosine for these vectors ranges from 0\u20131.\nLet\u2019s see how the cosine computes which of the words cherry ordigital is closer\nin meaning to information , just using raw counts from the following shortened table:\npie data computer\ncherry 442 8 2\ndigital 5 1683 1670\ninformation 5 3982 3325\ncos(cherry;information ) =442\u00035+8\u00033982+2\u00033325p\n4422+82+22p\n52+39822+33252=:018\ncos(digital;information ) =5\u00035+1683\u00033982+1670\u00033325p\n52+16832+16702p\n52+39822+33252=:996\nThe model decides that information is way closer to digital than it is to cherry , a\nresult that seems sensible. Fig. 6.8 shows a visualization.\n50010001500200025003000500digitalcherryinformationDimension 1: \u2018pie\u2019\nDimension 2: \u2018computer\u2019\nFigure 6.8 A (rough) graphical demonstration of cosine similarity, showing vectors for\nthree words ( cherry ,digital , and information ) in the two dimensional space de\ufb01ned by counts\nof the words computer andpienearby. The \ufb01gure doesn\u2019t show the cosine, but it highlights the\nangles; note that the angle between digital andinformation is smaller than the angle between\ncherry andinformation . When two vectors are more similar, the cosine is larger but the angle\nis smaller; the cosine has its maximum (1) when the angle between two vectors is smallest\n(0\u000e); the cosine of all other angles is less than 1.\n6.5 TF-IDF: Weighing terms in the vector\nThe co-occurrence matrices above represent each cell by frequencies, either of words\nwith documents (Fig. 6.5), or words with other words (Fig. 6.6). But raw frequency 112 CHAPTER 6 \u2022 V ECTOR SEMANTICS AND EMBEDDINGS\nis not the best measure of association between words. Raw frequency is very skewed\nand not very discriminative. If we want to know what kinds of contexts are shared\nbycherry andstrawberry but not by digital andinformation , we\u2019re not going to get\ngood discrimination from words like the,it, orthey, which occur frequently with\nall sorts of words and aren\u2019t informative about any particular word. We saw this\nalso in Fig. 6.3 for the Shakespeare corpus; the dimension for the word good is not\nvery discriminative between plays; good is simply a frequent word and has roughly\nequivalent high frequencies in each of the plays.\nIt\u2019s a bit of a paradox. Words that occur nearby frequently (maybe pienearby\ncherry ) are more important than words that only appear once or twice. Yet words\nthat are too frequent\u2014ubiquitous, like theorgood \u2014 are unimportant. How can we\nbalance these two con\ufb02icting constraints?\nThere are two common solutions to this problem: in this section we\u2019ll describe\nthetf-idf weighting, usually used when the dimensions are documents. In the next\nsection we introduce the PPMI algorithm (usually used when the dimensions are\nwords).\nThetf-idf weighting (the \u2018-\u2019 here is a hyphen, not a minus sign) is the product\nof two terms, each term capturing one of these two intuitions:\nThe \ufb01rst is the term frequency (Luhn, 1957): the frequency of the word tin the term frequency\ndocument d. We can just use the raw count as the term frequency:\ntft;d=count (t;d) (6.11)\nMore commonly we squash the raw frequency a bit, by using the log 10of the fre-\nquency instead. The intuition is that a word appearing 100 times in a document\ndoesn\u2019t make that word 100 times more likely to be relevant to the meaning of the\ndocument. We also need to do something special with counts of 0, since we can\u2019t\ntake the log of 0.2\ntft;d=(\n1+log10count (t;d) if count (t;d)>0\n0 otherwise(6.12)\nIf we use log weighting, terms which occur 0 times in a document would have tf =0,\n1 times in a document tf =1+log10(1) =1+0=1, 10 times in a document tf =\n1+log10(10) =2, 100 times tf =1+log10(100) =3, 1000 times tf =4, and so on.\nThe second factor in tf-idf is used to give a higher weight to words that occur\nonly in a few documents. Terms that are limited to a few documents are useful\nfor discriminating those documents from the rest of the collection; terms that occur\nfrequently across the entire collection aren\u2019t as helpful. The document frequencydocument\nfrequency\ndftof a term tis the number of documents it occurs in. Document frequency is\nnot the same as the collection frequency of a term, which is the total number of\ntimes the word appears in the whole collection in any document. Consider in the\ncollection of Shakespeare\u2019s 37 plays the two words Romeo andaction . The words\nhave identical collection frequencies (they both occur 113 times in all the plays) but\nvery different document frequencies, since Romeo only occurs in a single play. If\nour goal is to \ufb01nd documents about the romantic tribulations of Romeo, the word\nRomeo should be highly weighted, but not action :\nCollection Frequency Document Frequency\nRomeo 113 1\naction 113 31\n2We can also use this alternative formulation, which we have used in earlier editions: tf t;d=\nlog10(count (t;d)+1) 6.5 \u2022 TF-IDF: W EIGHING TERMS IN THE VECTOR 113\nWe emphasize discriminative words like Romeo via the inverse document fre-\nquency oridfterm weight (Sparck Jones, 1972). The idf is de\ufb01ned using the frac- idf\ntionN=dft, where Nis the total number of documents in the collection, and df tis\nthe number of documents in which term toccurs. The fewer documents in which a\nterm occurs, the higher this weight. The lowest weight of 1 is assigned to terms that\noccur in all the documents. It\u2019s usually clear what counts as a document: in Shake-\nspeare we would use a play; when processing a collection of encyclopedia articles\nlike Wikipedia, the document is a Wikipedia page; in processing newspaper articles,\nthe document is a single article. Occasionally your corpus might not have appropri-\nate document divisions and you might need to break up the corpus into documents\nyourself for the purposes of computing idf.\nBecause of the large number of documents in many collections, this measure\ntoo is usually squashed with a log function. The resulting de\ufb01nition for inverse\ndocument frequency (idf) is thus\nidft=log10\u0012N\ndft\u0013\n(6.13)\nHere are some idf values for some words in the Shakespeare corpus, (along with\nthe document frequency df values on which they are based) ranging from extremely\ninformative words which occur in only one play like Romeo , to those that occur in a\nfew like salad orFalstaff , to those which are very common like foolor so common\nas to be completely non-discriminative since they occur in all 37 plays like good or\nsweet .3\nWord df idf\nRomeo 1 1.57\nsalad 2 1.27\nFalstaff 4 0.967\nforest 12 0.489\nbattle 21 0.246\nwit 34 0.037\nfool 36 0.012\ngood 37 0\nsweet 37 0\nThe tf-idf weighted value wt;dfor word tin document dthus combines term tf-idf\nfrequency tf t;d(de\ufb01ned either by Eq. 6.11 or by Eq. 6.12) with idf from Eq. 6.13:\nwt;d=tft;d\u0002idft (6.14)\nFig. 6.9 applies tf-idf weighting to the Shakespeare term-document matrix in Fig. 6.2,\nusing the tf equation Eq. 6.12. Note that the tf-idf values for the dimension corre-\nsponding to the word good have now all become 0; since this word appears in every\ndocument, the tf-idf weighting leads it to be ignored. Similarly, the word fool, which\nappears in 36 out of the 37 plays, has a much lower weight.\nThe tf-idf weighting is the way for weighting co-occurrence matrices in infor-\nmation retrieval, but also plays a role in many other aspects of natural language\nprocessing. It\u2019s also a great baseline, the simple thing to try \ufb01rst. We\u2019ll look at other\nweightings like PPMI (Positive Pointwise Mutual Information) in Section 6.6.\n3Sweet was one of Shakespeare\u2019s favorite adjectives, a fact probably related to the increased use of\nsugar in European recipes around the turn of the 16th century (Jurafsky, 2014, p. 175). 114 CHAPTER 6 \u2022 V ECTOR SEMANTICS AND EMBEDDINGS\nAs You Like It Twelfth Night Julius Caesar Henry V\nbattle 0.246 0 0.454 0.520\ngood 0 0 0 0\nfool 0.030 0.033 0.0012 0.0019\nwit 0.085 0.081 0.048 0.054\nFigure 6.9 A portion of the tf-idf weighted term-document matrix for four words in Shake-\nspeare plays, showing a selection of 4 plays, using counts from Fig. 6.2. For example the\n0:085 value for witinAs You Like It is the product of tf =1+log10(20) =2:301 and idf =:037.\nNote that the idf weighting has eliminated the importance of the ubiquitous word good and\nvastly reduced the impact of the almost-ubiquitous word fool.\n6.6 Pointwise Mutual Information (PMI)\nAn alternative weighting function to tf-idf, PPMI (positive pointwise mutual infor-\nmation), is used for term-term-matrices, when the vector dimensions correspond to\nwords rather than documents. PPMI draws on the intuition that the best way to weigh\nthe association between two words is to ask how much more the two words co-occur\nin our corpus than we would have a priori expected them to appear by chance.\nPointwise mutual information (Fano, 1961)4is one of the most important con-pointwise\nmutual\ninformationcepts in NLP. It is a measure of how often two events xandyoccur, compared with\nwhat we would expect if they were independent:\nI(x;y) =log2P(x;y)\nP(x)P(y)(6.16)\nThe pointwise mutual information between a target word wand a context word\nc(Church and Hanks 1989, Church and Hanks 1990) is then de\ufb01ned as:\nPMI(w;c) =log2P(w;c)\nP(w)P(c)(6.17)\nThe numerator tells us how often we observed the two words together (assuming\nwe compute probability by using the MLE). The denominator tells us how often\nwe would expect the two words to co-occur assuming they each occurred indepen-\ndently; recall that the probability of two independent events both occurring is just\nthe product of the probabilities of the two events. Thus, the ratio gives us an esti-\nmate of how much more the two words co-occur than we expect by chance. PMI is\na useful tool whenever we need to \ufb01nd words that are strongly associated.\nPMI values range from negative to positive in\ufb01nity. But negative PMI values\n(which imply things are co-occurring less often than we would expect by chance)\ntend to be unreliable unless our corpora are enormous. To distinguish whether\ntwo words whose individual probability is each 10\u00006occur together less often than\nchance, we would need to be certain that the probability of the two occurring to-\ngether is signi\ufb01cantly less than 10\u000012, and this kind of granularity would require an\nenormous corpus. Furthermore it\u2019s not clear whether it\u2019s even possible to evaluate\nsuch scores of \u2018unrelatedness\u2019 with human judgments. For this reason it is more\n4PMI is based on the mutual information between two random variables XandY, de\ufb01ned as:\nI(X;Y) =X\nxX\nyP(x;y)log2P(x;y)\nP(x)P(y)(6.15)\nIn a confusion of terminology, Fano used the phrase mutual information to refer to what we now call\npointwise mutual information and the phrase expectation of the mutual information for what we now call\nmutual information 6.6 \u2022 P OINTWISE MUTUAL INFORMATION (PMI) 115\ncommon to use Positive PMI (called PPMI ) which replaces all negative PMI values PPMI\nwith zero (Church and Hanks 1989, Dagan et al. 1993, Niwa and Nitta 1994)5:\nPPMI (w;c) =max(log2P(w;c)\nP(w)P(c);0) (6.18)\nMore formally, let\u2019s assume we have a co-occurrence matrix F with W rows (words)\nand C columns (contexts), where fi jgives the number of times word wioccurs with\ncontext cj. This can be turned into a PPMI matrix where PPMI i jgives the PPMI\nvalue of word wiwith context cj(which we can also express as PPMI( wi;cj) or\nPPMI( w=i;c=j)) as follows:\npi j=fi jPW\ni=1PC\nj=1fi j;pi\u0003=PC\nj=1fi jPW\ni=1PC\nj=1fi j;p\u0003j=PW\ni=1fi jPW\ni=1PC\nj=1fi j(6.19)\nPPMI i j=max(log2pi j\npi\u0003p\u0003j;0) (6.20)\nLet\u2019s see some PPMI calculations. We\u2019ll use Fig. 6.10, which repeats Fig. 6.6 plus\nall the count marginals, and let\u2019s pretend for ease of calculation that these are the\nonly words/contexts that matter.\ncomputer data result pie sugar count(w)\ncherry 2 8 9 442 25 486\nstrawberry 0 0 1 60 19 80\ndigital 1670 1683 85 5 4 3447\ninformation 3325 3982 378 5 13 7703\ncount(context) 4997 5673 473 512 61 11716\nFigure 6.10 Co-occurrence counts for four words in 5 contexts in the Wikipedia corpus,\ntogether with the marginals, pretending for the purpose of this calculation that no other word-\ns/contexts matter.\nThus for example we could compute PPMI(information,data), assuming we pre-\ntended that Fig. 6.6 encompassed all the relevant word contexts/dimensions, as fol-\nlows:\nP(w=information, c=data ) =3982\n11716=:3399\nP(w=information ) =7703\n11716=:6575\nP(c=data ) =5673\n11716=:4842\nPPMI (information,data ) = log2(:3399=(:6575\u0003:4842)) =:0944\nFig. 6.11 shows the joint probabilities computed from the counts in Fig. 6.10, and\nFig. 6.12 shows the PPMI values. Not surprisingly, cherry andstrawberry are highly\nassociated with both pieandsugar , and data is mildly associated with information .\nPMI has the problem of being biased toward infrequent events; very rare words\ntend to have very high PMI values. One way to reduce this bias toward low frequency\n5Positive PMI also cleanly solves the problem of what to do with zero counts, using 0 to replace the\n\u0000\u00a5from log (0). 116 CHAPTER 6 \u2022 V ECTOR SEMANTICS AND EMBEDDINGS\np(w,context) p(w)\ncomputer data result pie sugar p(w)\ncherry 0.0002 0.0007 0.0008 0.0377 0.0021 0.0415\nstrawberry 0.0000 0.0000 0.0001 0.0051 0.0016 0.0068\ndigital 0.1425 0.1436 0.0073 0.0004 0.0003 0.2942\ninformation 0.2838 0.3399 0.0323 0.0004 0.0011 0.6575\np(context) 0.4265 0.4842 0.0404 0.0437 0.0052\nFigure 6.11 Replacing the counts in Fig. 6.6 with joint probabilities, showing the marginals\nin the right column and the bottom row.\ncomputer data result pie sugar\ncherry 0 0 0 4.38 3.30\nstrawberry 0 0 0 4.10 5.51\ndigital 0.18 0.01 0 0 0\ninformation 0.02 0.09 0.28 0 0\nFigure 6.12 The PPMI matrix showing the association between words and context words,\ncomputed from the counts in Fig. 6.11. Note that most of the 0 PPMI values are ones that had\na negative PMI; for example PMI( cherry,computer ) = -6.7, meaning that cherry andcomputer\nco-occur on Wikipedia less often than we would expect by chance, and with PPMI we replace\nnegative values by zero.\nevents is to slightly change the computation for P(c), using a different function Pa(c)\nthat raises the probability of the context word to the power of a:\nPPMI a(w;c) =max(log2P(w;c)\nP(w)Pa(c);0) (6.21)\nPa(c) =count (c)a\nP\nccount (c)a(6.22)\nLevy et al. (2015) found that a setting of a=0:75 improved performance of\nembeddings on a wide range of tasks (drawing on a similar weighting used for skip-\ngrams described below in Eq. 6.32). This works because raising the count to a=\n0:75 increases the probability assigned to rare contexts, and hence lowers their PMI\n(Pa(c)>P(c)when cis rare).\nAnother possible solution is Laplace smoothing: Before computing PMI, a small\nconstant k(values of 0.1-3 are common) is added to each of the counts, shrinking\n(discounting) all the non-zero values. The larger the k, the more the non-zero counts\nare discounted.\n6.7 Applications of the tf-idf or PPMI vector models\nIn summary, the vector semantics model we\u2019ve described so far represents a target\nword as a vector with dimensions corresponding either to the documents in a large\ncollection (the term-document matrix) or to the counts of words in some neighboring\nwindow (the term-term matrix). The values in each dimension are counts, weighted\nby tf-idf (for term-document matrices) or PPMI (for term-term matrices), and the\nvectors are sparse (since most values are zero).\nThe model computes the similarity between two words xandyby taking the\ncosine of their tf-idf or PPMI vectors; high cosine, high similarity. This entire model 6.8 \u2022 W ORD2VEC 117\nis sometimes referred to as the tf-idf model or the PPMI model, after the weighting\nfunction.\nThe tf-idf model of meaning is often used for document functions like deciding\nif two documents are similar. We represent a document by taking the vectors of\nall the words in the document, and computing the centroid of all those vectors. centroid\nThe centroid is the multidimensional version of the mean; the centroid of a set of\nvectors is a single vector that has the minimum sum of squared distances to each of\nthe vectors in the set. Given kword vectors w1;w2;:::;wk, the centroid document\nvector dis:document\nvector\nd=w1+w2+:::+wk\nk(6.23)\nGiven two documents, we can then compute their document vectors d1andd2, and\nestimate the similarity between the two documents by cos (d1;d2). Document sim-\nilarity is also useful for all sorts of applications; information retrieval, plagiarism\ndetection, news recommender systems, and even for digital humanities tasks like\ncomparing different versions of a text to see which are similar to each other.\nEither the PPMI model or the tf-idf model can be used to compute word simi-\nlarity, for tasks like \ufb01nding word paraphrases, tracking changes in word meaning, or\nautomatically discovering meanings of words in different corpora. For example, we\ncan \ufb01nd the 10 most similar words to any target word wby computing the cosines\nbetween wand each of the V\u00001 other words, sorting, and looking at the top 10.\n6.8 Word2vec\nIn the previous sections we saw how to represent a word as a sparse, long vector with\ndimensions corresponding to words in the vocabulary or documents in a collection.\nWe now introduce a more powerful word representation: embeddings , short dense\nvectors. Unlike the vectors we\u2019ve seen so far, embeddings are short , with number\nof dimensions dranging from 50-1000, rather than the much larger vocabulary size\njVjor number of documents Dwe\u2019ve seen. These ddimensions don\u2019t have a clear\ninterpretation. And the vectors are dense : instead of vector entries being sparse,\nmostly-zero counts or functions of counts, the values will be real-valued numbers\nthat can be negative.\nIt turns out that dense vectors work better in every NLP task than sparse vectors.\nWhile we don\u2019t completely understand all the reasons for this, we have some intu-\nitions. Representing words as 300-dimensional dense vectors requires our classi\ufb01ers\nto learn far fewer weights than if we represented words as 50,000-dimensional vec-\ntors, and the smaller parameter space possibly helps with generalization and avoid-\ning over\ufb01tting. Dense vectors may also do a better job of capturing synonymy.\nFor example, in a sparse vector representation, dimensions for synonyms like car\nandautomobile dimension are distinct and unrelated; sparse vectors may thus fail\nto capture the similarity between a word with caras a neighbor and a word with\nautomobile as a neighbor.\nIn this section we introduce one method for computing embeddings: skip-gram skip-gram\nwith negative sampling , sometimes called SGNS . The skip-gram algorithm is one SGNS\nof two algorithms in a software package called word2vec , and so sometimes the word2vec\nalgorithm is loosely referred to as word2vec (Mikolov et al. 2013a, Mikolov et al.\n2013b). The word2vec methods are fast, ef\ufb01cient to train, and easily available on- 118 CHAPTER 6 \u2022 V ECTOR SEMANTICS AND EMBEDDINGS\nline with code and pretrained embeddings. Word2vec embeddings are static em-\nbeddings , meaning that the method learns one \ufb01xed embedding for each word in thestatic\nembeddings\nvocabulary. In Chapter 11 we\u2019ll introduce methods for learning dynamic contextual\nembeddings like the popular family of BERT representations, in which the vector\nfor each word is different in different contexts.\nThe intuition of word2vec is that instead of counting how often each word woc-\ncurs near, say, apricot , we\u2019ll instead train a classi\ufb01er on a binary prediction task: \u201cIs\nword wlikely to show up near apricot ?\u201d We don\u2019t actually care about this prediction\ntask; instead we\u2019ll take the learned classi\ufb01er weights as the word embeddings.\nThe revolutionary intuition here is that we can just use running text as implicitly\nsupervised training data for such a classi\ufb01er; a word cthat occurs near the target\nword apricot acts as gold \u2018correct answer\u2019 to the question \u201cIs word clikely to show\nup near apricot ?\u201d This method, often called self-supervision , avoids the need for self-supervision\nany sort of hand-labeled supervision signal. This idea was \ufb01rst proposed in the task\nof neural language modeling, when Bengio et al. (2003) and Collobert et al. (2011)\nshowed that a neural language model (a neural network that learned to predict the\nnext word from prior words) could just use the next word in running text as its\nsupervision signal, and could be used to learn an embedding representation for each\nword as part of doing this prediction task.\nWe\u2019ll see how to do neural networks in the next chapter, but word2vec is a\nmuch simpler model than the neural network language model, in two ways. First,\nword2vec simpli\ufb01es the task (making it binary classi\ufb01cation instead of word pre-\ndiction). Second, word2vec simpli\ufb01es the architecture (training a logistic regression\nclassi\ufb01er instead of a multi-layer neural network with hidden layers that demand\nmore sophisticated training algorithms). The intuition of skip-gram is:\n1. Treat the target word and a neighboring context word as positive examples.\n2. Randomly sample other words in the lexicon to get negative samples.\n3. Use logistic regression to train a classi\ufb01er to distinguish those two cases.\n4. Use the learned weights as the embeddings.\n6.8.1 The classi\ufb01er\nLet\u2019s start by thinking about the classi\ufb01cation task, and then turn to how to train.\nImagine a sentence like the following, with a target word apricot , and assume we\u2019re\nusing a window of \u00062 context words:\n... lemon, a [tablespoon of apricot jam, a] pinch ...\nc1 c2 w c3 c4\nOur goal is to train a classi\ufb01er such that, given a tuple (w;c)of a target word\nwpaired with a candidate context word c(for example ( apricot ,jam), or perhaps\n(apricot ,aardvark )) it will return the probability that cis a real context word (true\nforjam, false for aardvark ):\nP(+jw;c) (6.24)\nThe probability that word cis not a real context word for wis just 1 minus\nEq. 6.24:\nP(\u0000jw;c) =1\u0000P(+jw;c) (6.25) 6.8 \u2022 W ORD2VEC 119\nHow does the classi\ufb01er compute the probability P? The intuition of the skip-\ngram model is to base this probability on embedding similarity: a word is likely to\noccur near the target if its embedding vector is similar to the target embedding. To\ncompute similarity between these dense embeddings, we rely on the intuition that\ntwo vectors are similar if they have a high dot product (after all, cosine is just a\nnormalized dot product). In other words:\nSimilarity (w;c)\u0019c\u0001w (6.26)\nThe dot product c\u0001wis not a probability, it\u2019s just a number ranging from \u0000\u00a5to\u00a5\n(since the elements in word2vec embeddings can be negative, the dot product can be\nnegative). To turn the dot product into a probability, we\u2019ll use the logistic orsigmoid\nfunction s(x), the fundamental core of logistic regression:\ns(x) =1\n1+exp(\u0000x)(6.27)\nWe model the probability that word cis a real context word for target word was:\nP(+jw;c) = s(c\u0001w) =1\n1+exp(\u0000c\u0001w)(6.28)\nThe sigmoid function returns a number between 0 and 1, but to make it a probability\nwe\u2019ll also need the total probability of the two possible events ( cis a context word,\nandcisn\u2019t a context word) to sum to 1. We thus estimate the probability that word c\nis not a real context word for was:\nP(\u0000jw;c) = 1\u0000P(+jw;c)\n=s(\u0000c\u0001w) =1\n1+exp(c\u0001w)(6.29)\nEquation 6.28 gives us the probability for one word, but there are many context\nwords in the window. Skip-gram makes the simplifying assumption that all context\nwords are independent, allowing us to just multiply their probabilities:\nP(+jw;c1:L) =LY\ni=1s(ci\u0001w) (6.30)\nlogP(+jw;c1:L) =LX\ni=1logs(ci\u0001w) (6.31)\nIn summary, skip-gram trains a probabilistic classi\ufb01er that, given a test target word\nwand its context window of Lwords c1:L, assigns a probability based on how similar\nthis context window is to the target word. The probability is based on applying the\nlogistic (sigmoid) function to the dot product of the embeddings of the target word\nwith each context word. To compute this probability, we just need embeddings for\neach target word and context word in the vocabulary.\nFig. 6.13 shows the intuition of the parameters we\u2019ll need. Skip-gram actually\nstores two embeddings for each word, one for the word as a target, and one for the\nword considered as context. Thus the parameters we need to learn are two matrices\nWandC, each containing an embedding for every one of the jVjwords in the\nvocabulary V.6Let\u2019s now turn to learning these embeddings (which is the real goal\nof training this classi\ufb01er in the \ufb01rst place).\n6In principle the target matrix and the context matrix could use different vocabularies, but we\u2019ll simplify\nby assuming one shared vocabulary V. 120 CHAPTER 6 \u2022 V ECTOR SEMANTICS AND EMBEDDINGS\n1WCaardvark\nzebrazebraaardvarkapricotapricot|V||V|+12V& =target wordscontext & noisewords\u2026\n\u20261..d\u2026\n\u2026\nFigure 6.13 The embeddings learned by the skipgram model. The algorithm stores two\nembeddings for each word, the target embedding (sometimes called the input embedding)\nand the context embedding (sometimes called the output embedding). The parameter qthat\nthe algorithm learns is thus a matrix of 2 jVjvectors, each of dimension d, formed by concate-\nnating two matrices, the target embeddings Wand the context+noise embeddings C.\n6.8.2 Learning skip-gram embeddings\nThe learning algorithm for skip-gram embeddings takes as input a corpus of text,\nand a chosen vocabulary size N. It begins by assigning a random embedding vector\nfor each of the N vocabulary words, and then proceeds to iteratively shift the em-\nbedding of each word wto be more like the embeddings of words that occur nearby\nin texts, and less like the embeddings of words that don\u2019t occur nearby. Let\u2019s start\nby considering a single piece of training data:\n... lemon, a [tablespoon of apricot jam, a] pinch ...\nc1 c2 w c3 c4\nThis example has a target word w(apricot), and 4 context words in the L=\u00062\nwindow, resulting in 4 positive training instances (on the left below):\npositive examples +\nw c pos\napricot tablespoon\napricot of\napricot jam\napricot anegative examples -\nw c neg w c neg\napricot aardvark apricot seven\napricot my apricot forever\napricot where apricot dear\napricot coaxial apricot if\nFor training a binary classi\ufb01er we also need negative examples. In fact skip-\ngram with negative sampling (SGNS) uses more negative examples than positive\nexamples (with the ratio between them set by a parameter k). So for each of these\n(w;cpos)training instances we\u2019ll create knegative samples, each consisting of the\ntarget wplus a \u2018noise word\u2019 cneg. A noise word is a random word from the lexicon,\nconstrained not to be the target word w. The right above shows the setting where\nk=2, so we\u2019ll have 2 negative examples in the negative training set \u0000for each\npositive example w;cpos.\nThe noise words are chosen according to their weighted unigram frequency\npa(w), where ais a weight. If we were sampling according to unweighted fre-\nquency p(w), it would mean that with unigram probability p(\u201cthe\u201d)we would choose\nthe word theas a noise word, with unigram probability p(\u201caardvark \u201d)we would 6.8 \u2022 W ORD2VEC 121\nchoose aardvark , and so on. But in practice it is common to set a=0:75, i.e. use\nthe weighting p3\n4(w):\nPa(w) =count (w)a\nP\nw0count (w0)a(6.32)\nSetting a=:75 gives better performance because it gives rare noise words slightly\nhigher probability: for rare words, Pa(w)>P(w). To illustrate this intuition, it\nmight help to work out the probabilities for an example with a=:75 and two events,\nP(a) =0:99 and P(b) =0:01:\nPa(a) =:99:75\n:99:75+:01:75=0:97\nPa(b) =:01:75\n:99:75+:01:75=0:03 (6.33)\nThus using a=:75 increases the probability of the rare event bfrom 0.01 to 0.03.\nGiven the set of positive and negative training instances, and an initial set of\nembeddings, the goal of the learning algorithm is to adjust those embeddings to\n\u2022 Maximize the similarity of the target word, context word pairs (w;cpos)drawn\nfrom the positive examples\n\u2022 Minimize the similarity of the (w;cneg)pairs from the negative examples.\nIf we consider one word/context pair (w;cpos)with its knoise words cneg1:::cnegk,\nwe can express these two goals as the following loss function Lto be minimized\n(hence the\u0000); here the \ufb01rst term expresses that we want the classi\ufb01er to assign the\nreal context word cposa high probability of being a neighbor, and the second term\nexpresses that we want to assign each of the noise words cnegia high probability of\nbeing a non-neighbor, all multiplied because we assume independence:\nL=\u0000log\"\nP(+jw;cpos)kY\ni=1P(\u0000jw;cnegi)#\n=\u0000\"\nlogP(+jw;cpos)+kX\ni=1logP(\u0000jw;cnegi)#\n=\u0000\"\nlogP(+jw;cpos)+kX\ni=1log\u0000\n1\u0000P(+jw;cnegi)\u0001#\n=\u0000\"\nlogs(cpos\u0001w)+kX\ni=1logs(\u0000cnegi\u0001w)#\n(6.34)\nThat is, we want to maximize the dot product of the word with the actual context\nwords, and minimize the dot products of the word with the knegative sampled non-\nneighbor words.\nWe minimize this loss function using stochastic gradient descent. Fig. 6.14\nshows the intuition of one step of learning.\nTo get the gradient, we need to take the derivative of Eq. 6.34 with respect to\nthe different embeddings. It turns out the derivatives are the following (we leave the 122 CHAPTER 6 \u2022 V ECTOR SEMANTICS AND EMBEDDINGS\nWCmove apricot and jam closer,increasing cpos z waardvark\nmove apricot and matrix apartdecreasing cneg1 z w\u201c\u2026apricot jam\u2026\u201dw\nzebrazebraaardvarkjamapricot\ncposmatrixTolstoymove apricot and Tolstoy apartdecreasing cneg2 z w!cneg1cneg2k=2\nFigure 6.14 Intuition of one step of gradient descent. The skip-gram model tries to shift\nembeddings so the target embeddings (here for apricot ) are closer to (have a higher dot prod-\nuct with) context embeddings for nearby words (here jam) and further from (lower dot product\nwith) context embeddings for noise words that don\u2019t occur nearby (here Tolstoy andmatrix ).\nproof as an exercise at the end of the chapter):\n\u00b6L\n\u00b6cpos= [s(cpos\u0001w)\u00001]w (6.35)\n\u00b6L\n\u00b6cneg= [s(cneg\u0001w)]w (6.36)\n\u00b6L\n\u00b6w= [s(cpos\u0001w)\u00001]cpos+kX\ni=1[s(cnegi\u0001w)]cnegi(6.37)\nThe update equations going from time step ttot+1 in stochastic gradient descent\nare thus:\nct+1\npos=ct\npos\u0000h[s(ct\npos\u0001wt)\u00001]wt(6.38)\nct+1\nneg=ct\nneg\u0000h[s(ct\nneg\u0001wt)]wt(6.39)\nwt+1=wt\u0000h\"\n[s(ct\npos\u0001wt)\u00001]ct\npos+kX\ni=1[s(ct\nnegi\u0001wt)]ct\nnegi#\n(6.40)\nJust as in logistic regression, then, the learning algorithm starts with randomly ini-\ntialized WandCmatrices, and then walks through the training corpus using gradient\ndescent to move WandCso as to minimize the loss in Eq. 6.34 by making the up-\ndates in (Eq. 6.38)-(Eq. 6.40).\nRecall that the skip-gram model learns twoseparate embeddings for each word i:\nthetarget embedding wiand the context embedding ci, stored in two matrices, thetarget\nembeddingcontext\nembedding target matrix Wand the context matrix C. It\u2019s common to just add them together,\nrepresenting word iwith the vector wi+ci. Alternatively we can throw away the C\nmatrix and just represent each word iby the vector wi.\nAs with the simple count-based methods like tf-idf, the context window size L\naffects the performance of skip-gram embeddings, and experiments often tune the\nparameter Lon a devset. 6.9 \u2022 V ISUALIZING EMBEDDINGS 123\n6.8.3 Other kinds of static embeddings\nThere are many kinds of static embeddings. An extension of word2vec, fasttext fasttext\n(Bojanowski et al., 2017), addresses a problem with word2vec as we have presented\nit so far: it has no good way to deal with unknown words \u2014words that appear in\na test corpus but were unseen in the training corpus. A related problem is word\nsparsity, such as in languages with rich morphology, where some of the many forms\nfor each noun and verb may only occur rarely. Fasttext deals with these problems\nby using subword models, representing each word as itself plus a bag of constituent\nn-grams, with special boundary symbols added to each word. For example,\nwith n=3 the word where would be represented by the sequence plus the\ncharacter n-grams:\n\nThen a skipgram embedding is learned for each constituent n-gram, and the word\nwhere is represented by the sum of all of the embeddings of its constituent n-grams.\nUnknown words can then be presented only by the sum of the constituent n-grams.\nA fasttext open-source library, including pretrained embeddings for 157 languages,\nis available at https://fasttext.cc .\nAnother very widely used static embedding model is GloVe (Pennington et al.,\n2014), short for Global Vectors, because the model is based on capturing global\ncorpus statistics. GloVe is based on ratios of probabilities from the word-word co-\noccurrence matrix, combining the intuitions of count-based models like PPMI while\nalso capturing the linear structures used by methods like word2vec.\nIt turns out that dense embeddings like word2vec actually have an elegant math-\nematical relationship with sparse embeddings like PPMI, in which word2vec can\nbe seen as implicitly optimizing a function of a PPMI matrix (Levy and Goldberg,\n2014c).\n6.9 Visualizing Embeddings\n\u201cI see well in many dimensions as long as the dimensions are around two.\u201d\nThe late economist Martin Shubik\nVisualizing embeddings is an important goal in helping understand, apply, and\nimprove these models of word meaning. But how can we visualize a (for example)\n100-dimensional vector?\nRohde, Gonnerman, Plaut Modeling Word Meaning Using Lexical Co-Occurrence\nHEADHANDFACE\nDOGAMERICA\nCATEYEEUROPE\nFOOTCHINAFRANCE\nCHICAGOARM\nFINGER\nNOSELEGRUSSIA\nMOUSEAFRICA\nATLANTAEARSHOULDERASIA\nCOW\nBULLPUPPYLIONHAWAII\nMONTREALTOKYOTOEMOSCOW\nTOOTH\nNASHVILLEBRAZILWRIST\nKITTENANKLE\nTURTLE\nOYSTER\nFigure 8: Multidimensional scaling for three noun classes.WRIST\nANKLE\nSHOULDER\nARM\nLEG\nHAND\nFOOT\nHEAD\nNOSE\nFINGER\nTOE\nFACE\nEAR\nEYE\nTOOTH\nDOG\nCAT\nPUPPY\nKITTEN\nCOW\nMOUSE\nTURTLE\nOYSTER\nLION\nBULL\nCHICAGO\nATLANTA\nMONTREAL\nNASHVILLE\nTOKYOCHINA\nRUSSIA\nAFRICA\nASIA\nEUROPE\nAMERICA\nBRAZIL\nMOSCOW\nFRANCEHAWAIIFigure 9: Hierarchical clustering for three noun classes using distances based on vector correlations.\n20\nThe simplest way to visualize the meaning of a word\nwembedded in a space is to list the most similar words to\nwby sorting the vectors for all words in the vocabulary by\ntheir cosine with the vector for w. For example the 7 closest\nwords to frogusing a particular embeddings computed with\nthe GloVe algorithm are: frogs ,toad,litoria ,leptodactyli-\ndae,rana,lizard , and eleutherodactylus (Pennington et al.,\n2014).\nYet another visualization method is to use a clustering\nalgorithm to show a hierarchical representation of which\nwords are similar to others in the embedding space. The\nuncaptioned \ufb01gure on the left uses hierarchical clustering\nof some embedding vectors for nouns as a visualization 124 CHAPTER 6 \u2022 V ECTOR SEMANTICS AND EMBEDDINGS\nmethod (Rohde et al., 2006).\nProbably the most common visualization method, how-\never, is to project the 100 dimensions of a word down into 2\ndimensions. Fig. 6.1 showed one such visualization, as does\nFig. 6.16, using a projection method called t-SNE (van der\nMaaten and Hinton, 2008).\n6.10 Semantic properties of embeddings\nIn this section we brie\ufb02y summarize some of the semantic properties of embeddings\nthat have been studied.\nDifferent types of similarity or association: One parameter of vector semantic\nmodels that is relevant to both sparse tf-idf vectors and dense word2vec vectors is\nthe size of the context window used to collect counts. This is generally between 1\nand 10 words on each side of the target word (for a total context of 2-20 words).\nThe choice depends on the goals of the representation. Shorter context windows\ntend to lead to representations that are a bit more syntactic, since the information is\ncoming from immediately nearby words. When the vectors are computed from short\ncontext windows, the most similar words to a target word wtend to be semantically\nsimilar words with the same parts of speech. When vectors are computed from long\ncontext windows, the highest cosine words to a target word wtend to be words that\nare topically related but not similar.\nFor example Levy and Goldberg (2014a) showed that using skip-gram with a\nwindow of\u00062, the most similar words to the word Hogwarts (from the Harry Potter\nseries) were names of other \ufb01ctional schools: Sunnydale (from Buffy the Vampire\nSlayer ) orEvernight (from a vampire series). With a window of \u00065, the most similar\nwords to Hogwarts were other words topically related to the Harry Potter series:\nDumbledore ,Malfoy , and half-blood .\nIt\u2019s also often useful to distinguish two kinds of similarity or association between\nwords (Sch \u00a8utze and Pedersen, 1993). Two words have \ufb01rst-order co-occurrence\ufb01rst-order\nco-occurrence\n(sometimes called syntagmatic association ) if they are typically nearby each other.\nThus wrote is a \ufb01rst-order associate of book orpoem . Two words have second-order\nco-occurrence (sometimes called paradigmatic association ) if they have similarsecond-order\nco-occurrence\nneighbors. Thus wrote is a second-order associate of words like said orremarked .\nAnalogy/Relational Similarity: Another semantic property of embeddings is their\nability to capture relational meanings. In an important early vector space model of\ncognition, Rumelhart and Abrahamson (1973) proposed the parallelogram modelparallelogram\nmodel\nfor solving simple analogy problems of the form a is to b as a* is to what? . In\nsuch problems, a system is given a problem like apple:tree::grape:? , i.e., apple is\nto tree as grape is to , and must \ufb01ll in the word vine. In the parallelogram\nmodel, illustrated in Fig. 6.15, the vector from the word apple to the word tree(=# \u0014tree\u0000# \u0014apple) is added to the vector for grape (# \u0014grape); the nearest word to that point\nis returned.\nIn early work with sparse embeddings, scholars showed that sparse vector mod-\nels of meaning could solve such analogy problems (Turney and Littman, 2005),\nbut the parallelogram method received more modern attention because of its suc-\ncess with word2vec or GloVe vectors (Mikolov et al. 2013c, Levy and Goldberg\n2014b, Pennington et al. 2014). For example, the result of the expression# \u0014king\u0000 6.10 \u2022 S EMANTIC PROPERTIES OF EMBEDDINGS 125\ntreeapplegrapevine\nFigure 6.15 The parallelogram model for analogy problems (Rumelhart and Abrahamson,\n1973): the location of# \u0014vine can be found by subtracting# \u0014apple from# \u0014tree and adding# \u0014grape.\n# \u0014man+# \u0014woman is a vector close to# \u0014queen. Similarly,# \u0014Paris\u0000# \u0014France +# \u0014Italy results\nin a vector that is close to# \u0014Rome. The embedding model thus seems to be extract-\ning representations of relations like MALE -FEMALE , or CAPITAL -CITY -OF, or even\nCOMPARATIVE /SUPERLATIVE , as shown in Fig. 6.16 from GloVe.\n(a) (b)\nFigure 6.16 Relational properties of the GloVe vector space, shown by projecting vectors onto two dimen-\nsions. (a)# \u0014king\u0000# \u0014man+# \u0014woman is close to# \u0014queen. (b) offsets seem to capture comparative and superlative\nmorphology (Pennington et al., 2014).\nFor a a:b::a\u0003:b\u0003problem, meaning the algorithm is given vectors a,b, and\na\u0003and must \ufb01nd b\u0003, the parallelogram method is thus:\n\u02c6b\u0003=argmin\nxdistance (x;b\u0000a+a\u0003) (6.41)\nwith some distance function, such as Euclidean distance.\nThere are some caveats. For example, the closest value returned by the paral-\nlelogram algorithm in word2vec or GloVe embedding spaces is usually not in fact\nb* but one of the 3 input words or their morphological variants (i.e., cherry:red ::\npotato:x returns potato orpotatoes instead of brown ), so these must be explicitly\nexcluded. Furthermore while embedding spaces perform well if the task involves\nfrequent words, small distances, and certain relations (like relating countries with\ntheir capitals or verbs/nouns with their in\ufb02ected forms), the parallelogram method\nwith embeddings doesn\u2019t work as well for other relations (Linzen 2016, Gladkova\net al. 2016, Schluter 2018, Ethayarajh et al. 2019a), and indeed Peterson et al. (2020)\nargue that the parallelogram method is in general too simple to model the human\ncognitive process of forming analogies of this kind. 126 CHAPTER 6 \u2022 V ECTOR SEMANTICS AND EMBEDDINGS\n6.10.1 Embeddings and Historical Semantics\nEmbeddings can also be a useful tool for studying how meaning changes over time,\nby computing multiple embedding spaces, each from texts written in a particular\ntime period. For example Fig. 6.17 shows a visualization of changes in meaning in\nEnglish words over the last two centuries, computed by building separate embed-\nding spaces for each decade from historical corpora like Google n-grams (Lin et al.,\n2012b) and the Corpus of Historical American English (Davies, 2012).\nCHAPTER 5. DYNAMIC SOCIAL REPRESENTATIONS OF WORD MEANING 79\nFigure 5.1: Two-dimensional visualization of semantic change in English using SGNS\nvectors (see Section 5.8 for the visualization algorithm). A,T h ew o r d gay shifted\nfrom meaning \u201ccheerful\u201d or \u201cfrolicsome\u201d to referring to homosexuality. A,I nt h ee a r l y\n20th century broadcast referred to \u201ccasting out seeds\u201d; with the rise of television and\nradio its meaning shifted to \u201ctransmitting signals\u201d. C,Awful underwent a process of\npejoration, as it shifted from meaning \u201cfull of awe\u201d to meaning \u201cterrible or appalling\u201d\n[212].\nthat adverbials (e.g., actually )h a v eag e n e r a lt e n d e n c yt ou n d e r g os u b j e c t i \ufb01 c a t i o n\nwhere they shift from objective statements about the world (e.g., \u201cSorry, the car is\nactually broken\u201d) to subjective statements (e.g., \u201cI can\u2019t believe he actually did that\u201d,\nindicating surprise/disbelief).\n5.2.2 Computational linguistic studies\nThere are also a number of recent works analyzing semantic change using computational\nmethods. [ 200] use latent semantic analysis to analyze how word meanings broaden\nand narrow over time. [ 113]u s er a wc o - o c c u r r e n c ev e c t o r st op e r f o r man u m b e ro f\nhistorical case-studies on semantic change, and [ 252] perform a similar set of small-\nscale case-studies using temporal topic models. [ 87]c o n s t r u c tp o i n t - w i s em u t u a l\ninformation-based embeddings and found that semantic changes uncovered by their\nmethod had reasonable agreement with human judgments. [ 129]a n d[ 119]u s e\u201c n e u r a l \u201d\nword-embedding methods to detect linguistic change points. Finally, [ 257]a n a l y z e\nhistorical co-occurrences to test whether synonyms tend to change in similar ways.\nFigure 6.17 A t-SNE visualization of the semantic change of 3 words in English using\nword2vec vectors. The modern sense of each word, and the grey context words, are com-\nputed from the most recent (modern) time-point embedding space. Earlier points are com-\nputed from earlier historical embedding spaces. The visualizations show the changes in the\nword gayfrom meanings related to \u201ccheerful\u201d or \u201cfrolicsome\u201d to referring to homosexuality,\nthe development of the modern \u201ctransmission\u201d sense of broadcast from its original sense of\nsowing seeds, and the pejoration of the word awful as it shifted from meaning \u201cfull of awe\u201d\nto meaning \u201cterrible or appalling\u201d (Hamilton et al., 2016b).\n6.11 Bias and Embeddings\nIn addition to their ability to learn word meaning from text, embeddings, alas,\nalso reproduce the implicit biases and stereotypes that were latent in the text. As\nthe prior section just showed, embeddings can roughly model relational similar-\nity: \u2018queen\u2019 as the closest word to \u2018king\u2019 - \u2018man\u2019 + \u2018woman\u2019 implies the analogy\nman:woman::king:queen . But these same embedding analogies also exhibit gender\nstereotypes. For example Bolukbasi et al. (2016) \ufb01nd that the closest occupation\nto \u2018computer programmer\u2019 - \u2018man\u2019 + \u2018woman\u2019 in word2vec embeddings trained on\nnews text is \u2018homemaker\u2019, and that the embeddings similarly suggest the analogy\n\u2018father\u2019 is to \u2018doctor\u2019 as \u2018mother\u2019 is to \u2018nurse\u2019. This could result in what Crawford\n(2017) and Blodgett et al. (2020) call an allocational harm , when a system allo-allocational\nharm\ncates resources (jobs or credit) unfairly to different groups. For example algorithms\nthat use embeddings as part of a search for hiring potential programmers or doctors\nmight thus incorrectly downweight documents with women\u2019s names.\nIt turns out that embeddings don\u2019t just re\ufb02ect the statistics of their input, but also\namplify bias; gendered terms become more gendered in embedding space than theybias\nampli\ufb01cation\nwere in the input text statistics (Zhao et al. 2017, Ethayarajh et al. 2019b, Jia et al.\n2020), and biases are more exaggerated than in actual labor employment statistics\n(Garg et al., 2018).\nEmbeddings also encode the implicit associations that are a property of human\nreasoning. The Implicit Association Test (Greenwald et al., 1998) measures peo- 6.12 \u2022 E VALUATING VECTOR MODELS 127\nple\u2019s associations between concepts (like \u2018\ufb02owers\u2019 or \u2018insects\u2019) and attributes (like\n\u2018pleasantness\u2019 and \u2018unpleasantness\u2019) by measuring differences in the latency with\nwhich they label words in the various categories.7Using such methods, people\nin the United States have been shown to associate African-American names with\nunpleasant words (more than European-American names), male names more with\nmathematics and female names with the arts, and old people\u2019s names with unpleas-\nant words (Greenwald et al. 1998, Nosek et al. 2002a, Nosek et al. 2002b). Caliskan\net al. (2017) replicated all these \ufb01ndings of implicit associations using GloVe vectors\nand cosine similarity instead of human latencies. For example African-American\nnames like \u2018Leroy\u2019 and \u2018Shaniqua\u2019 had a higher GloVe cosine with unpleasant words\nwhile European-American names (\u2018Brad\u2019, \u2018Greg\u2019, \u2018Courtney\u2019) had a higher cosine\nwith pleasant words. These problems with embeddings are an example of a repre-\nsentational harm (Crawford 2017, Blodgett et al. 2020), which is a harm caused byrepresentational\nharm\na system demeaning or even ignoring some social groups. Any embedding-aware al-\ngorithm that made use of word sentiment could thus exacerbate bias against African\nAmericans.\nRecent research focuses on ways to try to remove these kinds of biases, for\nexample by developing a transformation of the embedding space that removes gen-\nder stereotypes but preserves de\ufb01nitional gender (Bolukbasi et al. 2016, Zhao et al.\n2017) or changing the training procedure (Zhao et al., 2018b). However, although\nthese sorts of debiasing may reduce bias in embeddings, they do not eliminate it debiasing\n(Gonen and Goldberg, 2019), and this remains an open problem.\nHistorical embeddings are also being used to measure biases in the past. Garg\net al. (2018) used embeddings from historical texts to measure the association be-\ntween embeddings for occupations and embeddings for names of various ethnici-\nties or genders (for example the relative cosine similarity of women\u2019s names versus\nmen\u2019s to occupation words like \u2018librarian\u2019 or \u2018carpenter\u2019) across the 20th century.\nThey found that the cosines correlate with the empirical historical percentages of\nwomen or ethnic groups in those occupations. Historical embeddings also repli-\ncated old surveys of ethnic stereotypes; the tendency of experimental participants in\n1933 to associate adjectives like \u2018industrious\u2019 or \u2018superstitious\u2019 with, e.g., Chinese\nethnicity, correlates with the cosine between Chinese last names and those adjectives\nusing embeddings trained on 1930s text. They also were able to document historical\ngender biases, such as the fact that embeddings for adjectives related to competence\n(\u2018smart\u2019, \u2018wise\u2019, \u2018thoughtful\u2019, \u2018resourceful\u2019) had a higher cosine with male than fe-\nmale words, and showed that this bias has been slowly decreasing since 1960. We\nreturn in later chapters to this question about the role of bias in natural language\nprocessing.\n6.12 Evaluating Vector Models\nThe most important evaluation metric for vector models is extrinsic evaluation on\ntasks, i.e., using vectors in an NLP task and seeing whether this improves perfor-\nmance over some other model.\n7Roughly speaking, if humans associate \u2018\ufb02owers\u2019 with \u2018pleasantness\u2019 and \u2018insects\u2019 with \u2018unpleasant-\nness\u2019, when they are instructed to push a green button for \u2018\ufb02owers\u2019 (daisy, iris, lilac) and \u2018pleasant words\u2019\n(love, laughter, pleasure) and a red button for \u2018insects\u2019 (\ufb02ea, spider, mosquito) and \u2018unpleasant words\u2019\n(abuse, hatred, ugly) they are faster than in an incongruous condition where they push a red button for\n\u2018\ufb02owers\u2019 and \u2018unpleasant words\u2019 and a green button for \u2018insects\u2019 and \u2018pleasant words\u2019. 128 CHAPTER 6 \u2022 V ECTOR SEMANTICS AND EMBEDDINGS\nNonetheless it is useful to have intrinsic evaluations. The most common metric\nis to test their performance on similarity , computing the correlation between an\nalgorithm\u2019s word similarity scores and word similarity ratings assigned by humans.\nWordSim-353 (Finkelstein et al., 2002) is a commonly used set of ratings from 0\nto 10 for 353 noun pairs; for example ( plane ,car) had an average score of 5.77.\nSimLex-999 (Hill et al., 2015) is a more complex dataset that quanti\ufb01es similarity\n(cup, mug ) rather than relatedness ( cup, coffee ), and includes concrete and abstract\nadjective, noun and verb pairs. The TOEFL dataset is a set of 80 questions, each\nconsisting of a target word with 4 additional word choices; the task is to choose\nwhich is the correct synonym, as in the example: Levied is closest in meaning to:\nimposed, believed, requested, correlated (Landauer and Dumais, 1997). All of these\ndatasets present words without context.\nSlightly more realistic are intrinsic similarity tasks that include context. The\nStanford Contextual Word Similarity (SCWS) dataset (Huang et al., 2012) and the\nWord-in-Context (WiC) dataset (Pilehvar and Camacho-Collados, 2019) offer richer\nevaluation scenarios. SCWS gives human judgments on 2,003 pairs of words in\ntheir sentential context, while WiC gives target words in two sentential contexts that\nare either in the same or different senses; see Appendix G. The semantic textual\nsimilarity task (Agirre et al. 2012, Agirre et al. 2015) evaluates the performance of\nsentence-level similarity algorithms, consisting of a set of pairs of sentences, each\npair with human-labeled similarity scores.\nAnother task used for evaluation is the analogy task, discussed on page 124,\nwhere the system has to solve problems of the form a is to b as a* is to b* , given a, b,\nanda*and having to \ufb01nd b*(Turney and Littman, 2005). A number of sets of tuples\nhave been created for this task (Mikolov et al. 2013a, Mikolov et al. 2013c, Gladkova\net al. 2016), covering morphology ( city:cities::child:children ), lexicographic rela-\ntions ( leg:table::spout:teapot ) and encyclopedia relations ( Beijing:China::Dublin:Ireland ),\nsome drawing from the SemEval-2012 Task 2 dataset of 79 different relations (Jur-\ngens et al., 2012).\nAll embedding algorithms suffer from inherent variability. For example because\nof randomness in the initialization and the random negative sampling, algorithms\nlike word2vec may produce different results even from the same dataset, and in-\ndividual documents in a collection may strongly impact the resulting embeddings\n(Tian et al. 2016, Hellrich and Hahn 2016, Antoniak and Mimno 2018). When em-\nbeddings are used to study word associations in particular corpora, therefore, it is\nbest practice to train multiple embeddings with bootstrap sampling over documents\nand average the results (Antoniak and Mimno, 2018).\n6.13 Summary\n\u2022 In vector semantics, a word is modeled as a vector\u2014a point in high-dimensional\nspace, also called an embedding . In this chapter we focus on static embed-\ndings , where each word is mapped to a \ufb01xed embedding.\n\u2022 Vector semantic models fall into two classes: sparse anddense . In sparse\nmodels each dimension corresponds to a word in the vocabulary Vand cells\nare functions of co-occurrence counts . The term-document matrix has a\nrow for each word ( term ) in the vocabulary and a column for each document.\nTheword-context orterm-term matrix has a row for each (target) word in BIBLIOGRAPHICAL AND HISTORICAL NOTES 129\nthe vocabulary and a column for each context term in the vocabulary. Two\nsparse weightings are common: the tf-idf weighting which weights each cell\nby its term frequency andinverse document frequency , and PPMI (point-\nwise positive mutual information), which is most common for word-context\nmatrices.\n\u2022 Dense vector models have dimensionality 50\u20131000. Word2vec algorithms\nlikeskip-gram are a popular way to compute dense embeddings. Skip-gram\ntrains a logistic regression classi\ufb01er to compute the probability that two words\nare \u2018likely to occur nearby in text\u2019. This probability is computed from the dot\nproduct between the embeddings for the two words.\n\u2022 Skip-gram uses stochastic gradient descent to train the classi\ufb01er, by learning\nembeddings that have a high dot product with embeddings of words that occur\nnearby and a low dot product with noise words.\n\u2022 Other important embedding algorithms include GloVe , a method based on\nratios of word co-occurrence probabilities.\n\u2022 Whether using sparse or dense vectors, word and document similarities are\ncomputed by some function of the dot product between vectors. The cosine\nof two vectors\u2014a normalized dot product\u2014is the most popular such metric.\nBibliographical and Historical Notes\nThe idea of vector semantics arose out of research in the 1950s in three distinct\n\ufb01elds: linguistics, psychology, and computer science, each of which contributed a\nfundamental aspect of the model.\nThe idea that meaning is related to the distribution of words in context was\nwidespread in linguistic theory of the 1950s, among distributionalists like Zellig\nHarris, Martin Joos, and J. R. Firth, and semioticians like Thomas Sebeok. As Joos\n(1950) put it,\nthe linguist\u2019s \u201cmeaning\u201d of a morpheme. . . is by de\ufb01nition the set of conditional\nprobabilities of its occurrence in context with all other morphemes.\nThe idea that the meaning of a word might be modeled as a point in a multi-\ndimensional semantic space came from psychologists like Charles E. Osgood, who\nhad been studying how people responded to the meaning of words by assigning val-\nues along scales like happy/sad orhard/soft . Osgood et al. (1957) proposed that the\nmeaning of a word in general could be modeled as a point in a multidimensional\nEuclidean space, and that the similarity of meaning between two words could be\nmodeled as the distance between these points in the space.\nA \ufb01nal intellectual source in the 1950s and early 1960s was the \ufb01eld then called\nmechanical indexing , now known as information retrieval . In what became knownmechanical\nindexing\nas the vector space model for information retrieval (Salton 1971, Sparck Jones\n1986), researchers demonstrated new ways to de\ufb01ne the meaning of words in terms\nof vectors (Switzer, 1965), and re\ufb01ned methods for word similarity based on mea-\nsures of statistical association between words like mutual information (Giuliano,\n1965) and idf (Sparck Jones, 1972), and showed that the meaning of documents\ncould be represented in the same vector spaces used for words. Around the same\ntime, (Cordier, 1965) showed that factor analysis of word association probabilities\ncould be used to form dense vector representations of words. 130 CHAPTER 6 \u2022 V ECTOR SEMANTICS AND EMBEDDINGS\nSome of the philosophical underpinning of the distributional way of thinking\ncame from the late writings of the philosopher Wittgenstein, who was skeptical of\nthe possibility of building a completely formal theory of meaning de\ufb01nitions for\neach word. Wittgenstein suggested instead that \u201cthe meaning of a word is its use in\nthe language\u201d (Wittgenstein, 1953, PI 43). That is, instead of using some logical lan-\nguage to de\ufb01ne each word, or drawing on denotations or truth values, Wittgenstein\u2019s\nidea is that we should de\ufb01ne a word by how it is used by people in speaking and un-\nderstanding in their day-to-day interactions, thus pre\ufb01guring the movement toward\nembodied and experiential models in linguistics and NLP (Glenberg and Robertson\n2000, Lake and Murphy 2021, Bisk et al. 2020, Bender and Koller 2020).\nMore distantly related is the idea of de\ufb01ning words by a vector of discrete fea-\ntures, which has roots at least as far back as Descartes and Leibniz (Wierzbicka 1992,\nWierzbicka 1996). By the middle of the 20th century, beginning with the work of\nHjelmslev (Hjelmslev, 1969) (originally 1943) and \ufb02eshed out in early models of\ngenerative grammar (Katz and Fodor, 1963), the idea arose of representing mean-\ning with semantic features , symbols that represent some sort of primitive meaning.semantic\nfeature\nFor example words like hen,rooster , orchick , have something in common (they all\ndescribe chickens) and something different (their age and sex), representable as:\nhen+female, +chicken, +adult\nrooster-female, +chicken, +adult\nchick+chicken, -adult\nThe dimensions used by vector models of meaning to de\ufb01ne words, however, are\nonly abstractly related to this idea of a small \ufb01xed number of hand-built dimensions.\nNonetheless, there has been some attempt to show that certain dimensions of em-\nbedding models do contribute some speci\ufb01c compositional aspect of meaning like\nthese early semantic features.\nThe use of dense vectors to model word meaning, and indeed the term embed-\nding , grew out of the latent semantic indexing (LSI) model (Deerwester et al.,\n1988) recast as LSA (latent semantic analysis ) (Deerwester et al., 1990). In LSA\nsingular value decomposition \u2014SVD \u2014 is applied to a term-document matrix (each SVD\ncell weighted by log frequency and normalized by entropy), and then the \ufb01rst 300\ndimensions are used as the LSA embedding. Singular Value Decomposition (SVD)\nis a method for \ufb01nding the most important dimensions of a data set, those dimen-\nsions along which the data varies the most. LSA was then quickly widely applied:\nas a cognitive model Landauer and Dumais (1997), and for tasks like spell checking\n(Jones and Martin, 1997), language modeling (Bellegarda 1997, Coccaro and Ju-\nrafsky 1998, Bellegarda 2000), morphology induction (Schone and Jurafsky 2000,\nSchone and Jurafsky 2001b), multiword expressions (MWEs) (Schone and Juraf-\nsky, 2001a), and essay grading (Rehder et al., 1998). Related models were simul-\ntaneously developed and applied to word sense disambiguation by Sch \u00a8utze (1992b).\nLSA also led to the earliest use of embeddings to represent words in a probabilis-\ntic classi\ufb01er, in the logistic regression document router of Sch \u00a8utze et al. (1995).\nThe idea of SVD on the term-term matrix (rather than the term-document matrix)\nas a model of meaning for NLP was proposed soon after LSA by Sch \u00a8utze (1992b).\nSch\u00a8utze applied the low-rank (97-dimensional) embeddings produced by SVD to the\ntask of word sense disambiguation, analyzed the resulting semantic space, and also\nsuggested possible techniques like dropping high-order dimensions. See Sch \u00a8utze\n(1997).\nA number of alternative matrix models followed on from the early SVD work,\nincluding Probabilistic Latent Semantic Indexing (PLSI) (Hofmann, 1999), Latent EXERCISES 131\nDirichlet Allocation (LDA) (Blei et al., 2003), and Non-negative Matrix Factoriza-\ntion (NMF) (Lee and Seung, 1999).\nThe LSA community seems to have \ufb01rst used the word \u201cembedding\u201d in Landauer\net al. (1997), in a variant of its mathematical meaning as a mapping from one space\nor mathematical structure to another. In LSA, the word embedding seems to have\ndescribed the mapping from the space of sparse count vectors to the latent space of\nSVD dense vectors. Although the word thus originally meant the mapping from one\nspace to another, it has metonymically shifted to mean the resulting dense vector in\nthe latent space, and it is in this sense that we currently use the word.\nBy the next decade, Bengio et al. (2003) and Bengio et al. (2006) showed that\nneural language models could also be used to develop embeddings as part of the task\nof word prediction. Collobert and Weston (2007), Collobert and Weston (2008), and\nCollobert et al. (2011) then demonstrated that embeddings could be used to represent\nword meanings for a number of NLP tasks. Turian et al. (2010) compared the value\nof different kinds of embeddings for different NLP tasks. Mikolov et al. (2011)\nshowed that recurrent neural nets could be used as language models. The idea of\nsimplifying the hidden layer of these neural net language models to create the skip-\ngram (and also CBOW) algorithms was proposed by Mikolov et al. (2013a). The\nnegative sampling training algorithm was proposed in Mikolov et al. (2013b). There\nare numerous surveys of static embeddings and their parameterizations (Bullinaria\nand Levy 2007, Bullinaria and Levy 2012, Lapesa and Evert 2014, Kiela and Clark\n2014, Levy et al. 2015).\nSee Manning et al. (2008) and Chapter 14 for a deeper understanding of the role\nof vectors in information retrieval, including how to compare queries with docu-\nments, more details on tf-idf, and issues of scaling to very large datasets. See Kim\n(2019) for a clear and comprehensive tutorial on word2vec. Cruse (2004) is a useful\nintroductory linguistic text on lexical semantics.\nExercises 132 CHAPTER 7 \u2022 N EURAL NETWORKS\nCHAPTER\n7Neural Networks\n\u201c[M]achines of this character can behave in a very complicated manner when\nthe number of units is large.\u201d\nAlan Turing (1948) \u201cIntelligent Machines\u201d, page 6\nNeural networks are a fundamental computational tool for language process-\ning, and a very old one. They are called neural because their origins lie in the\nMcCulloch-Pitts neuron (McCulloch and Pitts, 1943), a simpli\ufb01ed model of the\nbiological neuron as a kind of computing element that could be described in terms\nof propositional logic. But the modern use in language processing no longer draws\non these early biological inspirations.\nInstead, a modern neural network is a network of small computing units, each\nof which takes a vector of input values and produces a single output value. In this\nchapter we introduce the neural net applied to classi\ufb01cation. The architecture we\nintroduce is called a feedforward network because the computation proceeds iter- feedforward\natively from one layer of units to the next. The use of modern neural nets is often\ncalled deep learning , because modern networks are often deep (have many layers). deep learning\nNeural networks share much of the same mathematics as logistic regression. But\nneural networks are a more powerful classi\ufb01er than logistic regression, and indeed a\nminimal neural network (technically one with a single \u2018hidden layer\u2019) can be shown\nto learn any function.\nNeural net classi\ufb01ers are different from logistic regression in another way. With\nlogistic regression, we applied the regression classi\ufb01er to many different tasks by\ndeveloping many rich kinds of feature templates based on domain knowledge. When\nworking with neural networks, it is more common to avoid most uses of rich hand-\nderived features, instead building neural networks that take raw words as inputs\nand learn to induce features as part of the process of learning to classify. We saw\nexamples of this kind of representation learning for embeddings in Chapter 6. Nets\nthat are very deep are particularly good at representation learning. For that reason\ndeep neural nets are the right tool for tasks that offer suf\ufb01cient data to learn features\nautomatically.\nIn this chapter we\u2019ll introduce feedforward networks as classi\ufb01ers, and also ap-\nply them to the simple task of language modeling: assigning probabilities to word\nsequences and predicting upcoming words. In subsequent chapters we\u2019ll introduce\nmany other aspects of neural models, such as recurrent neural networks (Chap-\nter 8), the Transformer (Chapter 9), and masked language modeling (Chapter 11). 7.1 \u2022 U NITS 133\n7.1 Units\nThe building block of a neural network is a single computational unit. A unit takes\na set of real valued numbers as input, performs some computation on them, and\nproduces an output.\nAt its heart, a neural unit is taking a weighted sum of its inputs, with one addi-\ntional term in the sum called a bias term . Given a set of inputs x1:::xn, a unit has bias term\na set of corresponding weights w1:::wnand a bias b, so the weighted sum zcan be\nrepresented as:\nz=b+X\niwixi (7.1)\nOften it\u2019s more convenient to express this weighted sum using vector notation; recall\nfrom linear algebra that a vector is, at heart, just a list or array of numbers. Thus vector\nwe\u2019ll talk about zin terms of a weight vector w, a scalar bias b, and an input vector\nx, and we\u2019ll replace the sum with the convenient dot product :\nz=w\u0001x+b (7.2)\nAs de\ufb01ned in Eq. 7.2, zis just a real valued number.\nFinally, instead of using z, a linear function of x, as the output, neural units\napply a non-linear function ftoz. We will refer to the output of this function as\ntheactivation value for the unit, a. Since we are just modeling a single unit, the activation\nactivation for the node is in fact the \ufb01nal output of the network, which we\u2019ll generally\ncally. So the value yis de\ufb01ned as:\ny=a=f(z)\nWe\u2019ll discuss three popular non-linear functions fbelow (the sigmoid, the tanh, and\nthe recti\ufb01ed linear unit or ReLU) but it\u2019s pedagogically convenient to start with the\nsigmoid function since we saw it in Chapter 5: sigmoid\ny=s(z) =1\n1+e\u0000z(7.3)\nThe sigmoid (shown in Fig. 7.1) has a number of advantages; it maps the output\ninto the range (0;1), which is useful in squashing outliers toward 0 or 1. And it\u2019s\ndifferentiable, which as we saw in Section 5.10 will be handy for learning.\nFigure 7.1 The sigmoid function takes a real value and maps it to the range (0;1). It is\nnearly linear around 0 but outlier values get squashed toward 0 or 1.\nSubstituting Eq. 7.2 into Eq. 7.3 gives us the output of a neural unit:\ny=s(w\u0001x+b) =1\n1+exp(\u0000(w\u0001x+b))(7.4) 134 CHAPTER 7 \u2022 N EURAL NETWORKS\nFig. 7.2 shows a \ufb01nal schematic of a basic neural unit. In this example the unit\ntakes 3 input values x1;x2, and x3, and computes a weighted sum, multiplying each\nvalue by a weight ( w1,w2, and w3, respectively), adds them to a bias term b, and then\npasses the resulting sum through a sigmoid function to result in a number between 0\nand 1.\nx1x2x3\nyw1w2w3\u2211b\u03c3+1za\nFigure 7.2 A neural unit, taking 3 inputs x1,x2, and x3(and a bias bthat we represent as a\nweight for an input clamped at +1) and producing an output y. We include some convenient\nintermediate variables: the output of the summation, z, and the output of the sigmoid, a. In\nthis case the output of the unit yis the same as a, but in deeper networks we\u2019ll reserve yto\nmean the \ufb01nal output of the entire network, leaving aas the activation of an individual node.\nLet\u2019s walk through an example just to get an intuition. Let\u2019s suppose we have a\nunit with the following weight vector and bias:\nw= [0:2;0:3;0:9]\nb=0:5\nWhat would this unit do with the following input vector:\nx= [0:5;0:6;0:1]\nThe resulting output ywould be:\ny=s(w\u0001x+b) =1\n1+e\u0000(w\u0001x+b)=1\n1+e\u0000(:5\u0003:2+:6\u0003:3+:1\u0003:9+:5)=1\n1+e\u00000:87=:70\nIn practice, the sigmoid is not commonly used as an activation function. A function\nthat is very similar but almost always better is the tanh function shown in Fig. 7.3a; tanh\ntanh is a variant of the sigmoid that ranges from -1 to +1:\ny=tanh(z) =ez\u0000e\u0000z\nez+e\u0000z(7.5)\nThe simplest activation function, and perhaps the most commonly used, is the rec-\nti\ufb01ed linear unit, also called the ReLU , shown in Fig. 7.3b. It\u2019s just the same as z ReLU\nwhen zis positive, and 0 otherwise:\ny=ReLU(z) =max(z;0) (7.6)\nThese activation functions have different properties that make them useful for differ-\nent language applications or network architectures. For example, the tanh function\nhas the nice properties of being smoothly differentiable and mapping outlier values\ntoward the mean. The recti\ufb01er function, on the other hand, has nice properties that 7.2 \u2022 T HEXOR PROBLEM 135\n(a) (b)\nFigure 7.3 The tanh and ReLU activation functions.\nresult from it being very close to linear. In the sigmoid or tanh functions, very high\nvalues of zresult in values of ythat are saturated , i.e., extremely close to 1, and have saturated\nderivatives very close to 0. Zero derivatives cause problems for learning, because as\nwe\u2019ll see in Section 7.5, we\u2019ll train networks by propagating an error signal back-\nwards, multiplying gradients (partial derivatives) from each layer of the network;\ngradients that are almost 0 cause the error signal to get smaller and smaller until it is\ntoo small to be used for training, a problem called the vanishing gradient problem.vanishing\ngradient\nRecti\ufb01ers don\u2019t have this problem, since the derivative of ReLU for high values of z\nis 1 rather than very close to 0.\n7.2 The XOR problem\nEarly in the history of neural networks it was realized that the power of neural net-\nworks, as with the real neurons that inspired them, comes from combining these\nunits into larger networks.\nOne of the most clever demonstrations of the need for multi-layer networks was\nthe proof by Minsky and Papert (1969) that a single neural unit cannot compute\nsome very simple functions of its input. Consider the task of computing elementary\nlogical functions of two inputs, like AND, OR, and XOR. As a reminder, here are\nthe truth tables for those functions:\nAND OR XOR\nx1 x2y x1 x2 y x1 x2 y\n0 00 0 0 0 0 0 0\n0 10 0 1 1 0 1 1\n1 00 1 0 1 1 0 1\n1 11 1 1 1 1 1 0\nThis example was \ufb01rst shown for the perceptron , which is a very simple neural perceptron\nunit that has a binary output and does nothave a non-linear activation function. The\noutput yof a perceptron is 0 or 1, and is computed as follows (using the same weight\nw, input x, and bias bas in Eq. 7.2):\ny=\u001a0;ifw\u0001x+b\u00140\n1;ifw\u0001x+b>0(7.7) 136 CHAPTER 7 \u2022 N EURAL NETWORKS\nIt\u2019s very easy to build a perceptron that can compute the logical AND and OR\nfunctions of its binary inputs; Fig. 7.4 shows the necessary weights.\nx1x2+1-111\nx1x2+1011\n(a) (b)\nFigure 7.4 The weights wand bias bfor perceptrons for computing logical functions. The\ninputs are shown as x1andx2and the bias as a special node with value +1 which is multiplied\nwith the bias weight b. (a) logical AND, with weights w1=1 and w2=1 and bias weight\nb=\u00001. (b) logical OR, with weights w1=1 and w2=1 and bias weight b=0. These\nweights/biases are just one from an in\ufb01nite number of possible sets of weights and biases that\nwould implement the functions.\nIt turns out, however, that it\u2019s not possible to build a perceptron to compute\nlogical XOR! (It\u2019s worth spending a moment to give it a try!)\nThe intuition behind this important result relies on understanding that a percep-\ntron is a linear classi\ufb01er. For a two-dimensional input x1andx2, the perceptron\nequation, w1x1+w2x2+b=0 is the equation of a line. (We can see this by putting\nit in the standard linear format: x2= (\u0000w1=w2)x1+ (\u0000b=w2).) This line acts as a\ndecision boundary in two-dimensional space in which the output 0 is assigned to alldecision\nboundary\ninputs lying on one side of the line, and the output 1 to all input points lying on the\nother side of the line. If we had more than 2 inputs, the decision boundary becomes\na hyperplane instead of a line, but the idea is the same, separating the space into two\ncategories.\nFig. 7.5 shows the possible logical inputs ( 00,01,10, and11) and the line drawn\nby one possible set of parameters for an AND and an OR classi\ufb01er. Notice that there\nis simply no way to draw a line that separates the positive cases of XOR (01 and 10)\nfrom the negative cases (00 and 11). We say that XOR is not a linearly separablelinearly\nseparable\nfunction. Of course we could draw a boundary with a curve, or some other function,\nbut not a single line.\n7.2.1 The solution: neural networks\nWhile the XOR function cannot be calculated by a single perceptron, it can be cal-\nculated by a layered network of perceptron units. Rather than see this with networks\nof simple perceptrons, however, let\u2019s see how to compute XOR using two layers of\nReLU-based units following Goodfellow et al. (2016). Fig. 7.6 shows a \ufb01gure with\nthe input being processed by two layers of neural units. The middle layer (called\nh) has two units, and the output layer (called y) has one unit. A set of weights and\nbiases are shown that allows the network to correctly compute the XOR function.\nLet\u2019s walk through what happens with the input x= [0, 0]. If we multiply each\ninput value by the appropriate weight, sum, and then add the bias b, we get the vector\n[0, -1], and we then apply the recti\ufb01ed linear transformation to give the output of the\nhlayer as [0, 0]. Now we once again multiply by the weights, sum, and add the\nbias (0 in this case) resulting in the value 0. The reader should work through the\ncomputation of the remaining 3 possible input pairs to see that the resulting yvalues\nare 1 for the inputs [0, 1] and [1, 0] and 0 for [0, 0] and [1, 1]. 7.2 \u2022 T HEXOR PROBLEM 137\n0011x1x20011x1x20011x1x2\na) x1 AND x2b) x1 OR x2c) x1 XOR x2?\nFigure 7.5 The functions AND, OR, and XOR, represented with input x1on the x-axis and input x2on the\ny-axis. Filled circles represent perceptron outputs of 1, and white circles perceptron outputs of 0. There is no\nway to draw a line that correctly separates the two categories for XOR. Figure styled after Russell and Norvig\n(2002).\nx1x2h1h2y1+11-1111-201+10\nFigure 7.6 XOR solution after Goodfellow et al. (2016). There are three ReLU units, in\ntwo layers; we\u2019ve called them h1,h2(hfor \u201chidden layer\u201d) and y1. As before, the numbers\non the arrows represent the weights wfor each unit, and we represent the bias bas a weight\non a unit clamped to +1, with the bias weights/units in gray.\nIt\u2019s also instructive to look at the intermediate results, the outputs of the two\nhidden nodes h1andh2. We showed in the previous paragraph that the hvector for\nthe inputs x= [0, 0] was [0, 0]. Fig. 7.7b shows the values of the hlayer for all\n4 inputs. Notice that hidden representations of the two input points x= [0, 1] and\nx= [1, 0] (the two cases with XOR output = 1) are merged to the single point h=\n[1, 0]. The merger makes it easy to linearly separate the positive and negative cases\nof XOR. In other words, we can view the hidden layer of the network as forming a\nrepresentation of the input.\nIn this example we just stipulated the weights in Fig. 7.6. But for real examples\nthe weights for neural networks are learned automatically using the error backprop-\nagation algorithm to be introduced in Section 7.5. That means the hidden layers will\nlearn to form useful representations. This intuition, that neural networks can auto-\nmatically learn useful representations of the input, is one of their key advantages,\nand one that we will return to again and again in later chapters. 138 CHAPTER 7 \u2022 N EURAL NETWORKS\n0011x1x2\na) The original x space0011h1h2\n2b) The new (linearly separable) h space\nFigure 7.7 The hidden layer forming a new representation of the input. (b) shows the\nrepresentation of the hidden layer, h, compared to the original input representation xin (a).\nNotice that the input point [0, 1] has been collapsed with the input point [1, 0], making it\npossible to linearly separate the positive and negative cases of XOR. After Goodfellow et al.\n(2016).\n7.3 Feedforward Neural Networks\nLet\u2019s now walk through a slightly more formal presentation of the simplest kind of\nneural network, the feedforward network . A feedforward network is a multilayerfeedforward\nnetwork\nnetwork in which the units are connected with no cycles; the outputs from units in\neach layer are passed to units in the next higher layer, and no outputs are passed\nback to lower layers. (In Chapter 8 we\u2019ll introduce networks with cycles, called\nrecurrent neural networks .)\nFor historical reasons multilayer networks, especially feedforward networks, are\nsometimes called multi-layer perceptrons (orMLP s); this is a technical misnomer,multi-layer\nperceptrons\nMLP since the units in modern multilayer networks aren\u2019t perceptrons (perceptrons are\npurely linear, but modern networks are made up of units with non-linearities like\nsigmoids), but at some point the name stuck.\nSimple feedforward networks have three kinds of nodes: input units, hidden\nunits, and output units.\nFig. 7.8 shows a picture. The input layer xis a vector of simple scalar values just\nas we saw in Fig. 7.2.\nThe core of the neural network is the hidden layer hformed of hidden units hi, hidden layer\neach of which is a neural unit as described in Section 7.1, taking a weighted sum of\nits inputs and then applying a non-linearity. In the standard architecture, each layer\nisfully-connected , meaning that each unit in each layer takes as input the outputs fully-connected\nfrom all the units in the previous layer, and there is a link between every pair of units\nfrom two adjacent layers. Thus each hidden unit sums over all the input units.\nRecall that a single hidden unit has as parameters a weight vector and a bias. We\nrepresent the parameters for the entire hidden layer by combining the weight vector\nand bias for each unit iinto a single weight matrix Wand a single bias vector bfor\nthe whole layer (see Fig. 7.8). Each element Wjiof the weight matrix Wrepresents\nthe weight of the connection from the ith input unit xito the jth hidden unit hj.\nThe advantage of using a single matrix Wfor the weights of the entire layer is\nthat now the hidden layer computation for a feedforward network can be done very\nef\ufb01ciently with simple matrix operations. In fact, the computation only has three 7.3 \u2022 F EEDFORWARD NEURAL NETWORKS 139\nx1x2xn0\u2026\u2026+1b\u2026UW\ninput layerhidden layeroutput layerh1y1y2yn2h2h3hn1\nFigure 7.8 A simple 2-layer feedforward network, with one hidden layer, one output layer,\nand one input layer (the input layer is usually not counted when enumerating layers).\nsteps: multiplying the weight matrix by the input vector x, adding the bias vector b,\nand applying the activation function g(such as the sigmoid, tanh, or ReLU activation\nfunction de\ufb01ned above).\nThe output of the hidden layer, the vector h, is thus the following (for this exam-\nple we\u2019ll use the sigmoid function sas our activation function):\nh=s(Wx+b) (7.8)\nNotice that we\u2019re applying the sfunction here to a vector, while in Eq. 7.3 it was\napplied to a scalar. We\u2019re thus allowing s(\u0001), and indeed any activation function\ng(\u0001), to apply to a vector element-wise, so g[z1;z2;z3] = [g(z1);g(z2);g(z3)].\nLet\u2019s introduce some constants to represent the dimensionalities of these vectors\nand matrices. We\u2019ll refer to the input layer as layer 0 of the network, and have n0\nrepresent the number of inputs, so xis a vector of real numbers of dimension n0,\nor more formally x2Rn0, a column vector of dimensionality [n0;1]. Let\u2019s call the\nhidden layer layer 1 and the output layer layer 2. The hidden layer has dimensional-\nityn1, soh2Rn1and also b2Rn1(since each hidden unit can take a different bias\nvalue). And the weight matrix Whas dimensionality W2Rn1\u0002n0, i.e.[n1;n0].\nTake a moment to convince yourself that the matrix multiplication in Eq. 7.8 will\ncompute the value of each hjass\u0000Pn0\ni=1Wjixi+bj\u0001\n.\nAs we saw in Section 7.2, the resulting value h(forhidden but also for hypoth-\nesis) forms a representation of the input. The role of the output layer is to take\nthis new representation hand compute a \ufb01nal output. This output could be a real-\nvalued number, but in many cases the goal of the network is to make some sort of\nclassi\ufb01cation decision, and so we will focus on the case of classi\ufb01cation.\nIf we are doing a binary task like sentiment classi\ufb01cation, we might have a sin-\ngle output node, and its scalar value yis the probability of positive versus negative\nsentiment. If we are doing multinomial classi\ufb01cation, such as assigning a part-of-\nspeech tag, we might have one output node for each potential part-of-speech, whose\noutput value is the probability of that part-of-speech, and the values of all the output\nnodes must sum to one. The output layer is thus a vector ythat gives a probability\ndistribution across the output nodes.\nLet\u2019s see how this happens. Like the hidden layer, the output layer has a weight\nmatrix (let\u2019s call it U), but some models don\u2019t include a bias vector bin the output 140 CHAPTER 7 \u2022 N EURAL NETWORKS\nlayer, so we\u2019ll simplify by eliminating the bias vector in this example. The weight\nmatrix is multiplied by its input vector ( h) to produce the intermediate output z:\nz=Uh\nThere are n2output nodes, so z2Rn2, weight matrix Uhas dimensionality U2\nRn2\u0002n1, and element Ui jis the weight from unit jin the hidden layer to unit iin the\noutput layer.\nHowever, zcan\u2019t be the output of the classi\ufb01er, since it\u2019s a vector of real-valued\nnumbers, while what we need for classi\ufb01cation is a vector of probabilities. There is\na convenient function for normalizing a vector of real values, by which we mean normalizing\nconverting it to a vector that encodes a probability distribution (all the numbers lie\nbetween 0 and 1 and sum to 1): the softmax function that we saw on page 85 of softmax\nChapter 5. More generally for any vector zof dimensionality d, the softmax is\nde\ufb01ned as:\nsoftmax (zi) =exp(zi)Pd\nj=1exp(zj)1\u0014i\u0014d (7.9)\nThus for example given a vector\nz= [0:6;1:1;\u00001:5;1:2;3:2;\u00001:1]; (7.10)\nthe softmax function will normalize it to a probability distribution (shown rounded):\nsoftmax (z) = [ 0:055;0:090;0:0067;0:10;0:74;0:010] (7.11)\nYou may recall that we used softmax to create a probability distribution from a\nvector of real-valued numbers (computed from summing weights times features) in\nthe multinomial version of logistic regression in Chapter 5.\nThat means we can think of a neural network classi\ufb01er with one hidden layer\nas building a vector hwhich is a hidden layer representation of the input, and then\nrunning standard multinomial logistic regression on the features that the network\ndevelops in h. By contrast, in Chapter 5 the features were mainly designed by hand\nvia feature templates. So a neural network is like multinomial logistic regression,\nbut (a) with many layers, since a deep neural network is like layer after layer of lo-\ngistic regression classi\ufb01ers; (b) with those intermediate layers having many possible\nactivation functions (tanh, ReLU, sigmoid) instead of just sigmoid (although we\u2019ll\ncontinue to use sfor convenience to mean any activation function); (c) rather than\nforming the features by feature templates, the prior layers of the network induce the\nfeature representations themselves.\nHere are the \ufb01nal equations for a feedforward network with a single hidden layer,\nwhich takes an input vector x, outputs a probability distribution y, and is parameter-\nized by weight matrices WandUand a bias vector b:\nh=s(Wx+b)\nz=Uh\ny=softmax (z) (7.12)\nAnd just to remember the shapes of all our variables, x2Rn0,h2Rn1,b2Rn1,\nW2Rn1\u0002n0,U2Rn2\u0002n1, and the output vector y2Rn2. We\u2019ll call this network a 2-\nlayer network (we traditionally don\u2019t count the input layer when numbering layers,\nbut do count the output layer). So by this terminology logistic regression is a 1-layer\nnetwork. 7.3 \u2022 F EEDFORWARD NEURAL NETWORKS 141\n7.3.1 More details on feedforward networks\nLet\u2019s now set up some notation to make it easier to talk about deeper networks of\ndepth more than 2. We\u2019ll use superscripts in square brackets to mean layer num-\nbers, starting at 0 for the input layer. So W[1]will mean the weight matrix for the\n(\ufb01rst) hidden layer, and b[1]will mean the bias vector for the (\ufb01rst) hidden layer. nj\nwill mean the number of units at layer j. We\u2019ll use g(\u0001)to stand for the activation\nfunction, which will tend to be ReLU or tanh for intermediate layers and softmax\nfor output layers. We\u2019ll use a[i]to mean the output from layer i, and z[i]to mean the\ncombination of previous layer output, weights and biases W[i]a[i\u00001]+b[i]. The 0th\nlayer is for inputs, so we\u2019ll refer to the inputs xmore generally as a[0].\nThus we can re-represent our 2-layer net from Eq. 7.12 as follows:\nz[1]=W[1]a[0]+b[1]\na[1]=g[1](z[1])\nz[2]=W[2]a[1]+b[2]\na[2]=g[2](z[2])\n\u02c6y=a[2](7.13)\nNote that with this notation, the equations for the computation done at each layer are\nthe same. The algorithm for computing the forward step in an n-layer feedforward\nnetwork, given the input vector a[0]is thus simply:\nforiin1,...,n\nz[i]=W[i]a[i\u00001]+b[i]\na[i]=g[i](z[i])\n\u02c6y=a[n]\nIt\u2019s often useful to have a name for the \ufb01nal set of activations right before the \ufb01nal\nsoftmax. So however many layers we have, we\u2019ll generally call the unnormalized\nvalues in the \ufb01nal vector z[n], the vector of scores right before the \ufb01nal softmax, the\nlogits (see (5.7). logits\nThe need for non-linear activation functions One of the reasons we use non-\nlinear activation functions for each layer in a neural network is that if we did not, the\nresulting network is exactly equivalent to a single-layer network. Let\u2019s see why this\nis true. Imagine the \ufb01rst two layers of such a network of purely linear layers:\nz[1]=W[1]x+b[1]\nz[2]=W[2]z[1]+b[2]\nWe can rewrite the function that the network is computing as:\nz[2]=W[2]z[1]+b[2]\n=W[2](W[1]x+b[1])+b[2]\n=W[2]W[1]x+W[2]b[1]+b[2]\n=W0x+b0(7.14)\nThis generalizes to any number of layers. So without non-linear activation functions,\na multilayer network is just a notational variant of a single layer network with a\ndifferent set of weights, and we lose all the representational power of multilayer\nnetworks. 142 CHAPTER 7 \u2022 N EURAL NETWORKS\nReplacing the bias unit In describing networks, we will often use a slightly sim-\npli\ufb01ed notation that represents exactly the same function without referring to an ex-\nplicit bias node b. Instead, we add a dummy node a0to each layer whose value will\nalways be 1. Thus layer 0, the input layer, will have a dummy node a[0]\n0=1, layer 1\nwill have a[1]\n0=1, and so on. This dummy node still has an associated weight, and\nthat weight represents the bias value b. For example instead of an equation like\nh=s(Wx+b) (7.15)\nwe\u2019ll use:\nh=s(Wx) (7.16)\nBut now instead of our vector xhaving n0values: x=x1;:::;xn0, it will have n0+\n1 values, with a new 0th dummy value x0=1:x=x0;:::;xn0. And instead of\ncomputing each hjas follows:\nhj=s n0X\ni=1Wjixi+bj!\n; (7.17)\nwe\u2019ll instead use:\nhj=s n0X\ni=0Wjixi!\n; (7.18)\nwhere the value Wj0replaces what had been bj. Fig. 7.9 shows a visualization.\nx1x2xn0\u2026\u2026+1b\u2026UWh1y1y2yn2h2h3hn1\nx1x2xn0\u2026\u2026x0=1\u2026UWh1y1y2yn2h2h3hn1\n(a) (b)\nFigure 7.9 Replacing the bias node (shown in a) with x0(b).\nWe\u2019ll continue showing the bias as bwhen we go over the learning algorithm\nin Section 7.5, but then we\u2019ll switch to this simpli\ufb01ed notation without explicit bias\nterms for the rest of the book.\n7.4 Feedforward networks for NLP: Classi\ufb01cation\nLet\u2019s see how to apply feedforward networks to NLP tasks! In this section we\u2019ll\nlook at classi\ufb01cation tasks like sentiment analysis; in the next section we\u2019ll introduce\nneural language modeling. 7.4 \u2022 F EEDFORWARD NETWORKS FOR NLP: C LASSIFICATION 143\nLet\u2019s begin with a simple 2-layer sentiment classi\ufb01er. You might imagine taking\nour logistic regression classi\ufb01er from Chapter 5, which corresponds to a 1-layer net-\nwork, and just adding a hidden layer. The input element xicould be scalar features\nlike those in Fig. 5.2, e.g., x1= count(words2doc), x2= count(positive lexicon\nwords2doc), x3= 1 if \u201cno\u201d2doc, and so on. And the output layer \u02c6ycould have\ntwo nodes (one each for positive and negative), or 3 nodes (positive, negative, neu-\ntral), in which case \u02c6y1would be the estimated probability of positive sentiment, \u02c6y2\nthe probability of negative and \u02c6y3the probability of neutral. The resulting equations\nwould be just what we saw above for a 2-layer network (as always, we\u2019ll continue\nto use the sto stand for any non-linearity, whether sigmoid, ReLU or other).\nx= [x1;x2;:::xN](each xiis a hand-designed feature)\nh=s(Wx+b)\nz=Uh\n\u02c6y=softmax (z) (7.19)\nFig. 7.10 shows a sketch of this architecture. As we mentioned earlier, adding this\nhidden layer to our logistic regression classi\ufb01er allows the network to represent the\nnon-linear interactions between features. This alone might give us a better sentiment\nclassi\ufb01er.\nUW[n\u2a091]Hidden layerOutput layersoftmax[dh\u2a09n][dh\u2a091][3\u2a09dh]Input wordsp(+)h1h2h3hdh\u2026y1^y2^y3^xhyInput layer n=3 features[3\u2a091]x1x2x3dessertwasgreatpositive lexiconwords = 1count of \u201cno\u201d = 0wordcount=3p(-)p(neut)\nFigure 7.10 Feedforward network sentiment analysis using traditional hand-built features\nof the input text.\nMost applications of neural networks for NLP do something different, however.\nInstead of using hand-built human-engineered features as the input to our classi\ufb01er,\nwe draw on deep learning\u2019s ability to learn features from the data by representing\nwords as embeddings, like the word2vec or GloVe embeddings we saw in Chapter 6.\nThere are various ways to represent an input for classi\ufb01cation. One simple baseline\nis to apply some sort of pooling function to the embeddings of all the words in the pooling\ninput. For example, for a text with ninput words/tokens w1;:::;wn, we can turn the\nnembeddings e(w1);:::;e(wn)(each of dimensionality d) into a single embedding\nalso of dimensionality dby just summing the embeddings, or by taking their mean\n(summing and then dividing by n):\nxmean=1\nnnX\ni=1e(wi) (7.20) 144 CHAPTER 7 \u2022 N EURAL NETWORKS\nThere are many other options, like taking the element-wise max. The element-wise\nmax of a set of nvectors is a new vector whose kth element is the max of the kth\nelements of all the nvectors. Here are the equations for this classi\ufb01er assuming\nmean pooling; the architecture is sketched in Fig. 7.11:\nx=mean(e(w1);e(w2);:::;e(wn))\nh=s(Wx+b)\nz=Uh\n\u02c6y=softmax (z) (7.21)\nUW[d\u2a091]Hidden layerOutput layersoftmax[dh\u2a09d][dh\u2a091][3\u2a09dh]Input wordsp(+)embedding for\u201cgreat\u201dembedding for\u201cdessert\u201dh1h2h3hdh\u2026y1^y2^y3^xhyInput layer pooled embedding[3\u2a091]pooling+dessertwasgreatembedding for\u201cwas\u201dp(-)p(neut)\nFigure 7.11 Feedforward network sentiment analysis using a pooled embedding of the in-\nput words.\nWhile Eq. 7.21 shows how to classify a single example x, in practice we want\nto ef\ufb01ciently classify an entire test set of mexamples. We do this by vectorizing\nthe process, just as we saw with logistic regression; instead of using for-loops to go\nthrough each example, we\u2019ll use matrix multiplication to do the entire computation\nof an entire test set at once. First, we pack all the input feature vectors for each input\nxinto a single input matrix X, with each row ia row vector consisting of the pooled\nembedding for input example x(i)(i.e., the vector x(i)). If the dimensionality of our\npooled input embedding is d,Xwill be a matrix of shape [m\u0002d].\nWe will then need to slightly modify Eq. 7.21. Xis of shape [m\u0002d]andWis of\nshape [dh\u0002d], so we\u2019ll have to reorder how we multiply XandWand transpose W\nso they correctly multiply to yield a matrix Hof shape [m\u0002dh].1The bias vector b\nfrom Eq. 7.21 of shape [1\u0002dh]will now have to be replicated into a matrix of shape\n[m\u0002dh]. We\u2019ll need to similarly reorder the next step and transpose U. Finally, our\noutput matrix \u02c6Ywill be of shape [m\u00023](or more generally [m\u0002do], where dois\nthe number of output classes), with each row iof our output matrix \u02c6Yconsisting of\nthe output vector \u02c6y(i).\u2018 Here are the \ufb01nal equations for computing the output class\n1Note that we could have kept the original order of our products if we had instead made our input\nmatrix Xrepresent each input as a column vector instead of a row vector, making it of shape [d\u0002m]. But\nrepresenting inputs as row vectors is convenient and common in neural network models. 7.5 \u2022 T RAINING NEURAL NETS 145\ndistribution for an entire test set:\nH=s(XW|+b)\nZ=HU|\n\u02c6Y=softmax (Z) (7.22)\nThe idea of using word2vec or GloVe embeddings as our input representation\u2014\nand more generally the idea of relying on another algorithm to have already learned\nan embedding representation for our input words\u2014is called pretraining . Using pretraining\npretrained embedding representations, whether simple static word embeddings like\nword2vec or the much more powerful contextual embeddings we\u2019ll introduce in\nChapter 11, is one of the central ideas of deep learning. (It\u2019s also possible, how-\never, to train the word embeddings as part of an NLP task; we\u2019ll talk about how to\ndo this in Section 7.7 in the context of the neural language modeling task.)\n7.5 Training Neural Nets\nA feedforward neural net is an instance of supervised machine learning in which we\nknow the correct output yfor each observation x. What the system produces, via\nEq. 7.13, is \u02c6 y, the system\u2019s estimate of the true y. The goal of the training procedure\nis to learn parameters W[i]andb[i]for each layer ithat make \u02c6 yfor each training\nobservation as close as possible to the true y.\nIn general, we do all this by drawing on the methods we introduced in Chapter 5\nfor logistic regression, so the reader should be comfortable with that chapter before\nproceeding.\nFirst, we\u2019ll need a loss function that models the distance between the system\noutput and the gold output, and it\u2019s common to use the loss function used for logistic\nregression, the cross-entropy loss .\nSecond, to \ufb01nd the parameters that minimize this loss function, we\u2019ll use the\ngradient descent optimization algorithm introduced in Chapter 5.\nThird, gradient descent requires knowing the gradient of the loss function, the\nvector that contains the partial derivative of the loss function with respect to each\nof the parameters. In logistic regression, for each observation we could directly\ncompute the derivative of the loss function with respect to an individual worb. But\nfor neural networks, with millions of parameters in many layers, it\u2019s much harder to\nsee how to compute the partial derivative of some weight in layer 1 when the loss\nis attached to some much later layer. How do we partial out the loss over all those\nintermediate layers? The answer is the algorithm called error backpropagation or\nbackward differentiation .\n7.5.1 Loss function\nThecross-entropy loss that is used in neural networks is the same one we saw forcross-entropy\nloss\nlogistic regression. If the neural network is being used as a binary classi\ufb01er, with\nthe sigmoid at the \ufb01nal layer, the loss function is the same logistic regression loss\nwe saw in Eq. 5.23:\nLCE(\u02c6y;y) =\u0000logp(yjx) =\u0000[ylog \u02c6y+(1\u0000y)log(1\u0000\u02c6y)] (7.23)\nIf we are using the network to classify into 3 or more classes, the loss function is\nexactly the same as the loss for multinomial regression that we saw in Chapter 5 on 146 CHAPTER 7 \u2022 N EURAL NETWORKS\npage 97. Let\u2019s brie\ufb02y summarize the explanation here for convenience. First, when\nwe have more than 2 classes we\u2019ll need to represent both yand\u02c6yas vectors. Let\u2019s\nassume we\u2019re doing hard classi\ufb01cation , where only one class is the correct one.\nThe true label yis then a vector with Kelements, each corresponding to a class,\nwithyc=1 if the correct class is c, with all other elements of ybeing 0. Recall that\na vector like this, with one value equal to 1 and the rest 0, is called a one-hot vector .\nAnd our classi\ufb01er will produce an estimate vector with Kelements \u02c6y, each element\n\u02c6ykof which represents the estimated probability p(yk=1jx).\nThe loss function for a single example xis the negative sum of the logs of the K\noutput classes, each weighted by their probability yk:\nLCE(\u02c6y;y) =\u0000KX\nk=1yklog\u02c6yk (7.24)\nWe can simplify this equation further; let\u2019s \ufb01rst rewrite the equation using the func-\ntion 1fgwhich evaluates to 1 if the condition in the brackets is true and to 0 oth-\nerwise. This makes it more obvious that the terms in the sum in Eq. 7.24 will be 0\nexcept for the term corresponding to the true class for which yk=1:\nLCE(\u02c6y;y) =\u0000KX\nk=11fyk=1glog\u02c6yk\nIn other words, the cross-entropy loss is simply the negative log of the output proba-\nbility corresponding to the correct class, and we therefore also call this the negative\nlog likelihood loss :negative log\nlikelihood loss\nLCE(\u02c6y;y) =\u0000log\u02c6yc(where cis the correct class) (7.25)\nPlugging in the softmax formula from Eq. 7.9, and with Kthe number of classes:\nLCE(\u02c6y;y) =\u0000logexp(zc)PK\nj=1exp(zj)(where cis the correct class) (7.26)\n7.5.2 Computing the Gradient\nHow do we compute the gradient of this loss function? Computing the gradient\nrequires the partial derivative of the loss function with respect to each parameter.\nFor a network with one weight layer and sigmoid output (which is what logistic\nregression is), we could simply use the derivative of the loss that we used for logistic\nregression in Eq. 7.27 (and derived in Section 5.10):\n\u00b6LCE(\u02c6y;y)\n\u00b6wj= ( \u02c6y\u0000y)xj\n= (s(w\u0001x+b)\u0000y)xj (7.27)\nOr for a network with one weight layer and softmax output (=multinomial logistic\nregression), we could use the derivative of the softmax loss from Eq. 5.48, shown\nfor a particular weight wkand input xi\n\u00b6LCE(\u02c6y;y)\n\u00b6wk;i=\u0000(yk\u0000\u02c6yk)xi\n=\u0000(yk\u0000p(yk=1jx))xi\n=\u0000 \nyk\u0000exp(wk\u0001x+bk)PK\nj=1exp(wj\u0001x+bj)!\nxi (7.28) 7.5 \u2022 T RAINING NEURAL NETS 147\nBut these derivatives only give correct updates for one weight layer: the last one!\nFor deep networks, computing the gradients for each weight is much more complex,\nsince we are computing the derivative with respect to weight parameters that appear\nall the way back in the very early layers of the network, even though the loss is\ncomputed only at the very end of the network.\nThe solution to computing this gradient is an algorithm called error backprop-\nagation orbackprop (Rumelhart et al., 1986). While backprop was invented spe-error back-\npropagation\ncially for neural networks, it turns out to be the same as a more general procedure\ncalled backward differentiation , which depends on the notion of computation\ngraphs . Let\u2019s see how that works in the next subsection.\n7.5.3 Computation Graphs\nA computation graph is a representation of the process of computing a mathematical\nexpression, in which the computation is broken down into separate operations, each\nof which is modeled as a node in a graph.\nConsider computing the function L(a;b;c) =c(a+2b). If we make each of the\ncomponent addition and multiplication operations explicit, and add names ( dande)\nfor the intermediate outputs, the resulting series of computations is:\nd=2\u0003b\ne=a+d\nL=c\u0003e\nWe can now represent this as a graph, with nodes for each operation, and di-\nrected edges showing the outputs from each operation as the inputs to the next, as\nin Fig. 7.12. The simplest use of computation graphs is to compute the value of\nthe function with some given inputs. In the \ufb01gure, we\u2019ve assumed the inputs a=3,\nb=1,c=\u00002, and we\u2019ve shown the result of the forward pass to compute the re-\nsultL(3;1;\u00002) =\u000010. In the forward pass of a computation graph, we apply each\noperation left to right, passing the outputs of each computation as the input to the\nnext node.\ne=a+dd = 2bL=cea=3b=1c=-2e=5d=2L=-10forward passabc\nFigure 7.12 Computation graph for the function L(a;b;c) =c(a+2b), with values for input\nnodes a=3,b=1,c=\u00002, showing the forward pass computation of L.\n7.5.4 Backward differentiation on computation graphs\nThe importance of the computation graph comes from the backward pass , which\nis used to compute the derivatives that we\u2019ll need for the weight update. In this\nexample our goal is to compute the derivative of the output function Lwith respect 148 CHAPTER 7 \u2022 N EURAL NETWORKS\nto each of the input variables, i.e.,\u00b6L\n\u00b6a,\u00b6L\n\u00b6b, and\u00b6L\n\u00b6c. The derivative\u00b6L\n\u00b6atells us how\nmuch a small change in aaffects L.\nBackwards differentiation makes use of the chain rule in calculus, so let\u2019s re- chain rule\nmind ourselves of that. Suppose we are computing the derivative of a composite\nfunction f(x) =u(v(x)). The derivative of f(x)is the derivative of u(x)with respect\ntov(x)times the derivative of v(x)with respect to x:\nd f\ndx=du\ndv\u0001dv\ndx(7.29)\nThe chain rule extends to more than two functions. If computing the derivative of a\ncomposite function f(x) =u(v(w(x))), the derivative of f(x)is:\nd f\ndx=du\ndv\u0001dv\ndw\u0001dw\ndx(7.30)\nThe intuition of backward differentiation is to pass gradients back from the \ufb01nal\nnode to all the nodes in the graph. Fig. 7.13 shows part of the backward computation\nat one node e. Each node takes an upstream gradient that is passed in from its parent\nnode to the right, and for each of its inputs computes a local gradient (the gradient\nof its output with respect to its input), and uses the chain rule to multiply these two\nto compute a downstream gradient to be passed on to the next earlier node.\nedLed\u2202L\u2202d\u2202L\u2202e=\u2202e\u2202d\u2202L\u2202e\u2202e\u2202dupstream gradientdownstream gradientlocal gradient\nFigure 7.13 Each node (like ehere) takes an upstream gradient, multiplies it by the local\ngradient (the gradient of its output with respect to its input), and uses the chain rule to compute\na downstream gradient to be passed on to a prior node. A node may have multiple local\ngradients if it has multiple inputs.\nLet\u2019s now compute the 3 derivatives we need. Since in the computation graph\nL=ce, we can directly compute the derivative\u00b6L\n\u00b6c:\n\u00b6L\n\u00b6c=e (7.31)\nFor the other two, we\u2019ll need to use the chain rule:\n\u00b6L\n\u00b6a=\u00b6L\n\u00b6e\u00b6e\n\u00b6a\n\u00b6L\n\u00b6b=\u00b6L\n\u00b6e\u00b6e\n\u00b6d\u00b6d\n\u00b6b(7.32)\nEq. 7.32 and Eq. 7.31 thus require \ufb01ve intermediate derivatives:\u00b6L\n\u00b6e,\u00b6L\n\u00b6c,\u00b6e\n\u00b6a,\u00b6e\n\u00b6d, and\n\u00b6d\n\u00b6b, which are as follows (making use of the fact that the derivative of a sum is the 7.5 \u2022 T RAINING NEURAL NETS 149\nsum of the derivatives):\nL=ce:\u00b6L\n\u00b6e=c;\u00b6L\n\u00b6c=e\ne=a+d:\u00b6e\n\u00b6a=1;\u00b6e\n\u00b6d=1\nd=2b:\u00b6d\n\u00b6b=2\nIn the backward pass, we compute each of these partials along each edge of the\ngraph from right to left, using the chain rule just as we did above. Thus we begin by\ncomputing the downstream gradients from node L, which are\u00b6L\n\u00b6eand\u00b6L\n\u00b6c. For node e,\nwe then multiply this upstream gradient\u00b6L\n\u00b6eby the local gradient (the gradient of the\noutput with respect to the input),\u00b6e\n\u00b6dto get the output we send back to node d:\u00b6L\n\u00b6d.\nAnd so on, until we have annotated the graph all the way to all the input variables.\nThe forward pass conveniently already will have computed the values of the forward\nintermediate variables we need (like dande) to compute these derivatives. Fig. 7.14\nshows the backward pass.\ne=d+ad = 2bL=cea=3b=1e=5d=2L=-10 abc\u2202L=5\u2202c\u2202L=-2\u2202e\u2202e=1\u2202d\u2202d=2\u2202b\u2202e=1\u2202abackward passc=-2\u2202L=-2\u2202e\u2202L=5\u2202c\u2202L\u2202d=-2\u2202e\u2202d\u2202L\u2202e=\u2202L\u2202a=-2\u2202e\u2202a\u2202L\u2202e=\u2202L\u2202b=-4\u2202d\u2202b\u2202L\u2202d=\nFigure 7.14 Computation graph for the function L(a;b;c) =c(a+2b), showing the backward pass computa-\ntion of\u00b6L\n\u00b6a,\u00b6L\n\u00b6b, and\u00b6L\n\u00b6c.\nBackward differentiation for a neural network\nOf course computation graphs for real neural networks are much more complex.\nFig. 7.15 shows a sample computation graph for a 2-layer neural network with n0=\n2,n1=2, and n2=1, assuming binary classi\ufb01cation and hence using a sigmoid\noutput unit for simplicity. The function that the computation graph is computing is:\nz[1]=W[1]x+b[1]\na[1]=ReLU (z[1])\nz[2]=W[2]a[1]+b[2]\na[2]=s(z[2])\n\u02c6y=a[2](7.33) 150 CHAPTER 7 \u2022 N EURAL NETWORKS\nFor the backward pass we\u2019ll also need to compute the loss L. The loss function\nfor binary sigmoid output from Eq. 7.23 is\nLCE(\u02c6y;y) =\u0000[ylog \u02c6y+(1\u0000y)log(1\u0000\u02c6y)] (7.34)\nOur output \u02c6 y=a[2], so we can rephrase this as\nLCE(a[2];y) =\u0000h\nyloga[2]+(1\u0000y)log(1\u0000a[2])i\n(7.35)\nz[2] = +a[2] = \u03c3 a[1] = ReLUz[1] = +b[1]****x1x2a[1] = ReLUz[1] = +b[1]**w[2]11w[1]11w[1]12\nw[1]21w[1]22b[2]w[2]12L (a[2],y)1\n2111\n22\nFigure 7.15 Sample computation graph for a simple 2-layer neural net (= 1 hidden layer) with two input units\nand 2 hidden units. We\u2019ve adjusted the notation a bit to avoid long equations in the nodes by just mentioning\nthe function that is being computed, and the resulting variable name. Thus the * to the right of node w[1]\n11means\nthatw[1]\n11is to be multiplied by x1, and the node z[1]= + means that the value of z[1]is computed by summing\nthe three nodes that feed into it (the two products, and the bias term b[1]\ni).\nThe weights that need updating (those for which we need to know the partial\nderivative of the loss function) are shown in teal. In order to do the backward pass,\nwe\u2019ll need to know the derivatives of all the functions in the graph. We already saw\nin Section 5.10 the derivative of the sigmoid s:\nds(z)\ndz=s(z)(1\u0000s(z)) (7.36)\nWe\u2019ll also need the derivatives of each of the other activation functions. The\nderivative of tanh is:\ndtanh(z)\ndz=1\u0000tanh2(z) (7.37)\nThe derivative of the ReLU is2\ndReLU (z)\ndz=\u001a0f or z<0\n1f or z\u00150(7.38)\n2The derivative is actually unde\ufb01ned at the point z=0, but by convention we treat it as 1. 7.5 \u2022 T RAINING NEURAL NETS 151\nWe\u2019ll give the start of the computation, computing the derivative of the loss function\nLwith respect to z, or\u00b6L\n\u00b6z(and leaving the rest of the computation as an exercise for\nthe reader). By the chain rule:\n\u00b6L\n\u00b6z=\u00b6L\n\u00b6a[2]\u00b6a[2]\n\u00b6z(7.39)\nSo let\u2019s \ufb01rst compute\u00b6L\n\u00b6a[2], taking the derivative of Eq. 7.35, repeated here:\nLCE(a[2];y) =\u0000h\nyloga[2]+(1\u0000y)log(1\u0000a[2])i\n\u00b6L\n\u00b6a[2]=\u0000 \ny\u00b6log(a[2])\n\u00b6a[2]!\n+(1\u0000y)\u00b6log(1\u0000a[2])\n\u00b6a[2]!\n=\u0000\u0012\u0012\ny1\na[2]\u0013\n+(1\u0000y)1\n1\u0000a[2](\u00001)\u0013\n=\u0000\u0012y\na[2]+y\u00001\n1\u0000a[2]\u0013\n(7.40)\nNext, by the derivative of the sigmoid:\n\u00b6a[2]\n\u00b6z=a[2](1\u0000a[2])\nFinally, we can use the chain rule:\n\u00b6L\n\u00b6z=\u00b6L\n\u00b6a[2]\u00b6a[2]\n\u00b6z\n=\u0000\u0012y\na[2]+y\u00001\n1\u0000a[2]\u0013\na[2](1\u0000a[2])\n=a[2]\u0000y (7.41)\nContinuing the backward computation of the gradients (next by passing the gra-\ndients over b[2]\n1and the two product nodes, and so on, back to all the teal nodes), is\nleft as an exercise for the reader.\n7.5.5 More details on learning\nOptimization in neural networks is a non-convex optimization problem, more com-\nplex than for logistic regression, and for that and other reasons there are many best\npractices for successful learning.\nFor logistic regression we can initialize gradient descent with all the weights and\nbiases having the value 0. In neural networks, by contrast, we need to initialize the\nweights with small random numbers. It\u2019s also helpful to normalize the input values\nto have 0 mean and unit variance.\nVarious forms of regularization are used to prevent over\ufb01tting. One of the most\nimportant is dropout : randomly dropping some units and their connections from dropout\nthe network during training (Hinton et al. 2012, Srivastava et al. 2014). At each\niteration of training (whenever we update parameters, i.e. each mini-batch if we are\nusing mini-batch gradient descent), we repeatedly choose a probability pand for\neach unit we replace its output with zero with probability p(and renormalize the\nrest of the outputs from that layer). 152 CHAPTER 7 \u2022 N EURAL NETWORKS\nTuning of hyperparameters is also important. The parameters of a neural net- hyperparameter\nwork are the weights Wand biases b; those are learned by gradient descent. The\nhyperparameters are things that are chosen by the algorithm designer; optimal val-\nues are tuned on a devset rather than by gradient descent learning on the training\nset. Hyperparameters include the learning rate h, the mini-batch size, the model\narchitecture (the number of layers, the number of hidden nodes per layer, the choice\nof activation functions), how to regularize, and so on. Gradient descent itself also\nhas many architectural variants such as Adam (Kingma and Ba, 2015).\nFinally, most modern neural networks are built using computation graph for-\nmalisms that make it easy and natural to do gradient computation and parallelization\non vector-based GPUs (Graphic Processing Units). PyTorch (Paszke et al., 2017)\nand TensorFlow (Abadi et al., 2015) are two of the most popular. The interested\nreader should consult a neural network textbook for further details; some sugges-\ntions are at the end of the chapter.\n7.6 Feedforward Neural Language Modeling\nAs our second application of feedforward networks, let\u2019s consider language mod-\neling : predicting upcoming words from prior words. Neural language modeling\u2014\nbased on the transformer architecture that we will see in Chapter 9\u2014is the algorithm\nthat underlies all of modern NLP. In this section and the next we\u2019ll introduce a sim-\npler version of neural language models for feedforward networks, an algorithm \ufb01rst\nintroduced by Bengio et al. (2003). The feedforward language model introduces\nmany of the important concepts of neural language modeling, concepts we\u2019ll return\nto as we describe more powerful models in Chapter 8 and Chapter 9.\nNeural language models have many advantages over the n-gram language mod-\nels of Chapter 3. Compared to n-gram models, neural language models can handle\nmuch longer histories, can generalize better over contexts of similar words, and are\nmore accurate at word-prediction. On the other hand, neural net language models\nare much more complex, are slower and need more energy to train, and are less inter-\npretable than n-gram models, so for some smaller tasks an n-gram language model\nis still the right tool.\nA feedforward neural language model (LM) is a feedforward network that takes\nas input at time ta representation of some number of previous words ( wt\u00001;wt\u00002,\netc.) and outputs a probability distribution over possible next words. Thus\u2014like the\nn-gram LM\u2014the feedforward neural LM approximates the probability of a word\ngiven the entire prior context P(wtjw1:t\u00001)by approximating based on the N\u00001\nprevious words:\nP(wtjw1;:::; wt\u00001)\u0019P(wtjwt\u0000N+1;:::; wt\u00001) (7.42)\nIn the following examples we\u2019ll use a 4-gram example, so we\u2019ll show a neural net to\nestimate the probability P(wt=ijwt\u00003;wt\u00002;wt\u00001).\nNeural language models represent words in this prior context by their embed-\ndings , rather than just by their word identity as used in n-gram language models.\nUsing embeddings allows neural language models to generalize better to unseen\ndata. For example, suppose we\u2019ve seen this sentence in training:\nI have to make sure that the cat gets fed. 7.6 \u2022 F EEDFORWARD NEURAL LANGUAGE MODELING 153\nbut have never seen the words \u201cgets fed\u201d after the word \u201cdog\u201d. Our test set has the\npre\ufb01x \u201cI forgot to make sure that the dog gets\u201d. What\u2019s the next word? An n-gram\nlanguage model will predict \u201cfed\u201d after \u201cthat the cat gets\u201d, but not after \u201cthat the dog\ngets\u201d. But a neural LM, knowing that \u201ccat\u201d and \u201cdog\u201d have similar embeddings, will\nbe able to generalize from the \u201ccat\u201d context to assign a high enough probability to\n\u201cfed\u201d even after seeing \u201cdog\u201d.\n7.6.1 Forward inference in the neural language model\nLet\u2019s walk through forward inference ordecoding for neural language models.forward\ninference\nForward inference is the task, given an input, of running a forward pass on the\nnetwork to produce a probability distribution over possible outputs, in this case next\nwords.\nWe \ufb01rst represent each of the Nprevious words as a one-hot vector of length\njVj, i.e., with one dimension for each word in the vocabulary. A one-hot vector is one-hot vector\na vector that has one element equal to 1\u2014in the dimension corresponding to that\nword\u2019s index in the vocabulary\u2014 while all the other elements are set to zero. Thus\nin a one-hot representation for the word \u201ctoothpaste\u201d, supposing it is V5, i.e., index\n5 in the vocabulary, x5=1, and xi=08i6=5, as shown here:\n[0 0 0 0 1 0 0 ... 0 0 0 0]\n1 2 3 4 5 6 7 ... ... |V|\nThe feedforward neural language model (sketched in Fig. 7.17) has a moving\nwindow that can see N words into the past. We\u2019ll let N equal 3, so the 3 words\nwt\u00001,wt\u00002, and wt\u00003are each represented as a one-hot vector. We then multiply\nthese one-hot vectors by the embedding matrix E. The embedding weight matrix E\nhas a column for each word, each a column vector of ddimensions, and hence has\ndimensionality d\u0002jVj. Multiplying by a one-hot vector that has only one non-zero\nelement xi=1 simply selects out the relevant column vector for word i, resulting in\nthe embedding for word i, as shown in Fig. 7.16.\nE|V|d1|V|d1=\u271555e5\nFigure 7.16 Selecting the embedding vector for word V5by multiplying the embedding\nmatrix Ewith a one-hot vector with a 1 in index 5.\nThe 3 resulting embedding vectors are concatenated to produce e, the embedding\nlayer. This is followed by a hidden layer and an output layer whose softmax produces\na probability distribution over words. For example y42, the value of output node 42,\nis the probability of the next word wtbeing V42, the vocabulary word with index 42\n(which is the word \u2018\ufb01sh\u2019 in our example).\nHere\u2019s the algorithm in detail for our mini example:\n1.Select three embeddings from E : Given the three previous words, we look\nup their indices, create 3 one-hot vectors, and then multiply each by the em-\nbedding matrix E. Consider wt\u00003. The one-hot vector for \u2018for\u2019 (index 35) is\nmultiplied by the embedding matrix E, to give the \ufb01rst part of the \ufb01rst hidden 154 CHAPTER 7 \u2022 N EURAL NETWORKS\nUWembedding layer3d\u2a091hiddenlayeroutput layersoftmaxdh\u2a093ddh\u2a091|V|\u2a09dhinput layerone-hot vectorsE\n|V|\u2a093d\u2a09|V|p(do|\u2026)p(aardvark|\u2026)\np(zebra|\u2026)p(fish|\u2026)\n|V|\u2a091EEh1h2y1\nh3hdh\u2026\u2026y34\ny|V|\u2026001001|V|35\n001001|V|451001001|V|9920\n0\u2026\u2026y42y35102^^^\n^^hexyforallthe?thanksand\u2026wt-3wt-2wt-1wt\u2026\nFigure 7.17 Forward inference in a feedforward neural language model. At each timestep\ntthe network computes a d-dimensional embedding for each context word (by multiplying a\none-hot vector by the embedding matrix E), and concatenates the 3 resulting embeddings to\nget the embedding layer e. The embedding vector eis multiplied by a weight matrix Wand\nthen an activation function is applied element-wise to produce the hidden layer h, which is\nthen multiplied by another weight matrix U. Finally, a softmax output layer predicts at each\nnode ithe probability that the next word wtwill be vocabulary word Vi.\nlayer, the embedding layer . Since each column of the input matrix Eis anembedding\nlayer\nembedding for a word, and the input is a one-hot column vector xifor word\nVi, the embedding layer for input wwill be Exi=ei, the embedding for word\ni. We now concatenate the three embeddings for the three context words to\nproduce the embedding layer e.\n2.Multiply by W : We multiply by W(and add b) and pass through the ReLU\n(or other) activation function to get the hidden layer h.\n3.Multiply by U :his now multiplied by U\n4.Apply softmax : After the softmax, each node iin the output layer estimates\nthe probability P(wt=ijwt\u00001;wt\u00002;wt\u00003)\nIn summary, the equations for a neural language model with a window size of 3,\ngiven one-hot input vectors for each input context word, are:\ne= [Ext\u00003;Ext\u00002;Ext\u00001]\nh=s(We+b)\nz=Uh\n\u02c6y=softmax (z) (7.43)\nNote that we formed the embedding layer eby concatenating the 3 embeddings\nfor the three context vectors; we\u2019ll often use semicolons to mean concatenation of\nvectors. 7.7 \u2022 T RAINING THE NEURAL LANGUAGE MODEL 155\n7.7 Training the neural language model\nThe high-level intuition of training neural language models, whether the simple\nfeedforward language models we describe here or the more powerful transformer\nlanguage models of Chapter 9, is the idea of self-training orself-supervision that self-training\nwe saw in Chapter 6 for learning word representations. In self-training for language\nmodeling, we take a corpus of text as training material and at each time step task\nthe model to predict the next word. At \ufb01rst it will do poorly at this task, but since\nin each case we know the correct answer (it\u2019s the next word in the corpus!) we can\neasily train it to be better at predicting the correct next word. We call such a model\nself-supervised because we don\u2019t have to add any special gold labels to the data;\nthe natural sequence of words is its own supervision! We simply train the model to\nminimize the error in predicting the true next word in the training sequence.\nIn practice, training the model means setting the parameters q=E;W;U;b. For\nsome tasks, it\u2019s ok to freeze the embedding layer Ewith initial word2vec values. freeze\nFreezing means we use word2vec or some other pretraining algorithm to compute\nthe initial embedding matrix E, and then hold it constant while we only modify W,\nU, and b, i.e., we don\u2019t update Eduring language model training. However, often\nwe\u2019d like to learn the embeddings simultaneously with training the network. This is\nuseful when the task the network is designed for (like sentiment classi\ufb01cation, trans-\nlation, or parsing) places strong constraints on what makes a good representation for\nwords.\nLet\u2019s see how to train the entire model including E, i.e. to set all the parameters\nq=E;W;U;b. We\u2019ll do this via gradient descent (Fig. 5.6), using error backprop-\nagation on the computation graph to compute the gradient. Training thus not only\nsets the weights WandUof the network, but also as we\u2019re predicting upcoming\nwords, we\u2019re learning the embeddings Efor each word that best predict upcoming\nwords.\nFig. 7.18 shows the set up for a window size of N=3 context words. The input x\nconsists of 3 one-hot vectors, fully connected to the embedding layer via 3 instanti-\nations of the embedding matrix E. We don\u2019t want to learn separate weight matrices\nfor mapping each of the 3 previous words to the projection layer. We want one single\nembedding dictionary Ethat\u2019s shared among these three. That\u2019s because over time,\nmany different words will appear as wt\u00002orwt\u00001, and we\u2019d like to just represent\neach word with one vector, whichever context position it appears in. Recall that the\nembedding weight matrix Ehas a column for each word, each a column vector of d\ndimensions, and hence has dimensionality d\u0002jVj.\nGenerally training proceeds by taking as input a very long text, concatenating all\nthe sentences, starting with random weights, and then iteratively moving through the\ntext predicting each word wt. At each word wt, we use the cross-entropy (negative\nlog likelihood) loss. Recall that the general form for this (repeated from Eq. 7.25)\nis:\nLCE(\u02c6y;y) =\u0000log \u02c6yi;(where iis the correct class) (7.44)\nFor language modeling, the classes are the words in the vocabulary, so \u02c6 yihere means\nthe probability that the model assigns to the correct next word wt:\nLCE=\u0000logp(wtjwt\u00001;:::;wt\u0000n+1) (7.45)\nThe parameter update for stochastic gradient descent for this loss from step stos+1 156 CHAPTER 7 \u2022 N EURAL NETWORKS\nUWembedding layer3d\u2a091hiddenlayeroutput layersoftmaxdh\u2a093ddh\u2a091|V|\u2a09dhinput layerone-hot vectorsE\n|V|\u2a093d\u2a09|V|p(do|\u2026)p(aardvark|\u2026)\np(zebra|\u2026)p(fish|\u2026)\n|V|\u2a091EEh1h2y1\nh3hdh\u2026\u2026y34\ny|V|\u2026001001|V|35\n001001|V|451001001|V|9920\n0\u2026\u2026y42y35102^^^\n^^hexyforallthefishthanksand\u2026wt-3wt-2wt-1wt\u2026L = \u2212log P(fish | for, all, the)wt=fish\nFigure 7.18 Learning all the way back to embeddings. Again, the embedding matrix Eis\nshared among the 3 context words.\nis then:\nqs+1=qs\u0000h\u00b6[\u0000logp(wtjwt\u00001;:::;wt\u0000n+1)]\n\u00b6q(7.46)\nThis gradient can be computed in any standard neural network framework which\nwill then backpropagate through q=E;W;U;b.\nTraining the parameters to minimize loss will result both in an algorithm for\nlanguage modeling (a word predictor) but also a new set of embeddings Ethat can\nbe used as word representations for other tasks.\n7.8 Summary\n\u2022 Neural networks are built out of neural units , originally inspired by biological\nneurons but now simply an abstract computational device.\n\u2022 Each neural unit multiplies input values by a weight vector, adds a bias, and\nthen applies a non-linear activation function like sigmoid, tanh, or recti\ufb01ed\nlinear unit.\n\u2022 In a fully-connected ,feedforward network, each unit in layer iis connected\nto each unit in layer i+1, and there are no cycles.\n\u2022 The power of neural networks comes from the ability of early layers to learn\nrepresentations that can be utilized by later layers in the network.\n\u2022 Neural networks are trained by optimization algorithms like gradient de-\nscent .\n\u2022Error backpropagation , backward differentiation on a computation graph ,\nis used to compute the gradients of the loss function for a network. BIBLIOGRAPHICAL AND HISTORICAL NOTES 157\n\u2022Neural language models use a neural network as a probabilistic classi\ufb01er, to\ncompute the probability of the next word given the previous nwords.\n\u2022 Neural language models can use pretrained embeddings , or can learn embed-\ndings from scratch in the process of language modeling.\nBibliographical and Historical Notes\nThe origins of neural networks lie in the 1940s McCulloch-Pitts neuron (McCul-\nloch and Pitts, 1943), a simpli\ufb01ed model of the biological neuron as a kind of com-\nputing element that could be described in terms of propositional logic. By the late\n1950s and early 1960s, a number of labs (including Frank Rosenblatt at Cornell and\nBernard Widrow at Stanford) developed research into neural networks; this phase\nsaw the development of the perceptron (Rosenblatt, 1958), and the transformation\nof the threshold into a bias, a notation we still use (Widrow and Hoff, 1960).\nThe \ufb01eld of neural networks declined after it was shown that a single perceptron\nunit was unable to model functions as simple as XOR (Minsky and Papert, 1969).\nWhile some small amount of work continued during the next two decades, a major\nrevival for the \ufb01eld didn\u2019t come until the 1980s, when practical tools for building\ndeeper networks like error backpropagation became widespread (Rumelhart et al.,\n1986). During the 1980s a wide variety of neural network and related architec-\ntures were developed, particularly for applications in psychology and cognitive sci-\nence (Rumelhart and McClelland 1986b, McClelland and Elman 1986, Rumelhart\nand McClelland 1986a, Elman 1990), for which the term connectionist orparal- connectionist\nlel distributed processing was often used (Feldman and Ballard 1982, Smolensky\n1988). Many of the principles and techniques developed in this period are foun-\ndational to modern work, including the ideas of distributed representations (Hinton,\n1986), recurrent networks (Elman, 1990), and the use of tensors for compositionality\n(Smolensky, 1990).\nBy the 1990s larger neural networks began to be applied to many practical lan-\nguage processing tasks as well, like handwriting recognition (LeCun et al. 1989) and\nspeech recognition (Morgan and Bourlard 1990). By the early 2000s, improvements\nin computer hardware and advances in optimization and training techniques made it\npossible to train even larger and deeper networks, leading to the modern term deep\nlearning (Hinton et al. 2006, Bengio et al. 2007). We cover more related history in\nChapter 8 and Chapter 16.\nThere are a number of excellent books on the subject. Goldberg (2017) has\nsuperb coverage of neural networks for natural language processing. For neural\nnetworks in general see Goodfellow et al. (2016) and Nielsen (2015). 158 CHAPTER 8 \u2022 RNN S AND LSTM S\nCHAPTER\n8RNNs and LSTMs\nTime will explain.\nJane Austen, Persuasion\nLanguage is an inherently temporal phenomenon. Spoken language is a sequence of\nacoustic events over time, and we comprehend and produce both spoken and written\nlanguage as a sequential input stream. The temporal nature of language is re\ufb02ected\nin the metaphors we use; we talk of the \ufb02ow of conversations ,news feeds , and twitter\nstreams , all of which emphasize that language is a sequence that unfolds in time.\nThis temporal nature is re\ufb02ected in some language processing algorithms. For\nexample, the Viterbi algorithm we introduced for HMM part-of-speech tagging pro-\nceeds through the input a word at a time, carrying forward information gleaned along\nthe way. But other machine learning approaches, like those we\u2019ve studied for senti-\nment analysis or other text classi\ufb01cation tasks don\u2019t have this temporal nature \u2013 they\nassume simultaneous access to all aspects of their input.\nThe feedforward networks of Chapter 7 also assumed simultaneous access, al-\nthough they also had a simple model for time. Recall that we applied feedforward\nnetworks to language modeling by having them look only at a \ufb01xed-size window\nof words, and then sliding this window over the input, making independent predic-\ntions along the way. This sliding-window approach is also used in the transformer\narchitecture we will introduce in Chapter 9.\nThis chapter introduces a deep learning architecture that offers an alternative\nway of representing time: recurrent neural networks (RNNs), and their variants like\nLSTMs. RNNs have a mechanism that deals directly with the sequential nature of\nlanguage, allowing them to handle the temporal nature of language without the use of\narbitrary \ufb01xed-sized windows. The recurrent network offers a new way to represent\nthe prior context, in its recurrent connections , allowing the model\u2019s decision to\ndepend on information from hundreds of words in the past. We\u2019ll see how to apply\nthe model to the task of language modeling, to sequence modeling tasks like part-\nof-speech tagging, and to text classi\ufb01cation tasks like sentiment analysis.\n8.1 Recurrent Neural Networks\nA recurrent neural network (RNN) is any network that contains a cycle within its\nnetwork connections, meaning that the value of some unit is directly, or indirectly,\ndependent on its own earlier outputs as an input. While powerful, such networks\nare dif\ufb01cult to reason about and to train. However, within the general class of recur-\nrent networks there are constrained architectures that have proven to be extremely\neffective when applied to language. In this section, we consider a class of recurrent\nnetworks referred to as Elman Networks (Elman, 1990) or simple recurrent net-Elman\nNetworks 8.1 \u2022 R ECURRENT NEURAL NETWORKS 159\nworks . These networks are useful in their own right and serve as the basis for more\ncomplex approaches like the Long Short-Term Memory (LSTM) networks discussed\nlater in this chapter. In this chapter when we use the term RNN we\u2019ll be referring to\nthese simpler more constrained networks (although you will often see the term RNN\nto mean any net with recurrent properties including LSTMs).\nxthtyt\nFigure 8.1 Simple recurrent neural network after Elman (1990). The hidden layer includes\na recurrent connection as part of its input. That is, the activation value of the hidden layer\ndepends on the current input as well as the activation value of the hidden layer from the\nprevious time step.\nFig. 8.1 illustrates the structure of an RNN. As with ordinary feedforward net-\nworks, an input vector representing the current input, xt, is multiplied by a weight\nmatrix and then passed through a non-linear activation function to compute the val-\nues for a layer of hidden units. This hidden layer is then used to calculate a cor-\nresponding output, yt. In a departure from our earlier window-based approach, se-\nquences are processed by presenting one item at a time to the network. We\u2019ll use\nsubscripts to represent time, thus xtwill mean the input vector xat time t. The key\ndifference from a feedforward network lies in the recurrent link shown in the \ufb01gure\nwith the dashed line. This link augments the input to the computation at the hidden\nlayer with the value of the hidden layer from the preceding point in time .\nThe hidden layer from the previous time step provides a form of memory, or\ncontext, that encodes earlier processing and informs the decisions to be made at\nlater points in time. Critically, this approach does not impose a \ufb01xed-length limit\non this prior context; the context embodied in the previous hidden layer can include\ninformation extending back to the beginning of the sequence.\nAdding this temporal dimension makes RNNs appear to be more complex than\nnon-recurrent architectures. But in reality, they\u2019re not all that different. Given an\ninput vector and the values for the hidden layer from the previous time step, we\u2019re\nstill performing the standard feedforward calculation introduced in Chapter 7. To\nsee this, consider Fig. 8.2 which clari\ufb01es the nature of the recurrence and how it\nfactors into the computation at the hidden layer. The most signi\ufb01cant change lies in\nthe new set of weights, U, that connect the hidden layer from the previous time step\nto the current hidden layer. These weights determine how the network makes use of\npast context in calculating the output for the current input. As with the other weights\nin the network, these connections are trained via backpropagation.\n8.1.1 Inference in RNNs\nForward inference (mapping a sequence of inputs to a sequence of outputs) in an\nRNN is nearly identical to what we\u2019ve already seen with feedforward networks. To\ncompute an output ytfor an input xt, we need the activation value for the hidden\nlayer ht. To calculate this, we multiply the input xtwith the weight matrix W, and\nthe hidden layer from the previous time step ht\u00001with the weight matrix U. We\nadd these values together and pass them through a suitable activation function, g,\nto arrive at the activation value for the current hidden layer, ht. Once we have the 160 CHAPTER 8 \u2022 RNN S AND LSTM S\n+UVWyt\nxththt-1\nFigure 8.2 Simple recurrent neural network illustrated as a feedforward network. The hid-\nden layer ht\u00001from the prior time step is multiplied by weight matrix Uand then added to\nthe feedforward component from the current time step.\nvalues for the hidden layer, we proceed with the usual computation to generate the\noutput vector.\nht=g(Uht\u00001+Wx t) (8.1)\nyt=f(Vht) (8.2)\nLet\u2019s refer to the input, hidden and output layer dimensions as din,dh, and dout\nrespectively. Given this, our three parameter matrices are: W2Rdh\u0002din,U2Rdh\u0002dh,\nandV2Rdout\u0002dh.\nWe compute ytvia a softmax computation that gives a probability distribution\nover the possible output classes.\nyt=softmax (Vht) (8.3)\nThe fact that the computation at time trequires the value of the hidden layer from\ntime t\u00001 mandates an incremental inference algorithm that proceeds from the start\nof the sequence to the end as illustrated in Fig. 8.3. The sequential nature of simple\nrecurrent networks can also be seen by unrolling the network in time as is shown in\nFig. 8.4. In this \ufb01gure, the various layers of units are copied for each time step to\nillustrate that they will have differing values over time. However, the various weight\nmatrices are shared across time.\nfunction FORWARD RNN( x,network )returns output sequence y\nh0 0\nfori 1toLENGTH (x)do\nhi g(Uhi\u00001+Wx i)\nyi f(Vhi)\nreturn y\nFigure 8.3 Forward inference in a simple recurrent network. The matrices U,VandWare\nshared across time, while new values for handyare calculated with each time step.\n8.1.2 Training\nAs with feedforward networks, we\u2019ll use a training set, a loss function, and back-\npropagation to obtain the gradients needed to adjust the weights in these recurrent 8.1 \u2022 R ECURRENT NEURAL NETWORKS 161\nUVWUVWUVW\nx1x2x3y1y2y3\nh1h3h2\nh0\nFigure 8.4 A simple recurrent neural network shown unrolled in time. Network layers are recalculated for\neach time step, while the weights U,VandWare shared across all time steps.\nnetworks. As shown in Fig. 8.2, we now have 3 sets of weights to update: W, the\nweights from the input layer to the hidden layer, U, the weights from the previous\nhidden layer to the current hidden layer, and \ufb01nally V, the weights from the hidden\nlayer to the output layer.\nFig. 8.4 highlights two considerations that we didn\u2019t have to worry about with\nbackpropagation in feedforward networks. First, to compute the loss function for\nthe output at time twe need the hidden layer from time t\u00001. Second, the hidden\nlayer at time tin\ufb02uences both the output at time tand the hidden layer at time t+1\n(and hence the output and loss at t+1). It follows from this that to assess the error\naccruing to ht, we\u2019ll need to know its in\ufb02uence on both the current output as well as\nthe ones that follow .\nTailoring the backpropagation algorithm to this situation leads to a two-pass al-\ngorithm for training the weights in RNNs. In the \ufb01rst pass, we perform forward\ninference, computing ht,yt, accumulating the loss at each step in time, saving the\nvalue of the hidden layer at each step for use at the next time step. In the second\nphase, we process the sequence in reverse, computing the required gradients as we\ngo, computing and saving the error term for use in the hidden layer for each step\nbackward in time. This general approach is commonly referred to as backpropaga-\ntion through time (Werbos 1974, Rumelhart et al. 1986, Werbos 1990).backpropaga-\ntion through\ntimeFortunately, with modern computational frameworks and adequate computing\nresources, there is no need for a specialized approach to training RNNs. As illus-\ntrated in Fig. 8.4, explicitly unrolling a recurrent network into a feedforward com-\nputational graph eliminates any explicit recurrences, allowing the network weights\nto be trained directly. In such an approach, we provide a template that speci\ufb01es the\nbasic structure of the network, including all the necessary parameters for the input,\noutput, and hidden layers, the weight matrices, as well as the activation and output\nfunctions to be used. Then, when presented with a speci\ufb01c input sequence, we can\ngenerate an unrolled feedforward network speci\ufb01c to that input, and use that graph 162 CHAPTER 8 \u2022 RNN S AND LSTM S\nto perform forward inference or training via ordinary backpropagation.\nFor applications that involve much longer input sequences, such as speech recog-\nnition, character-level processing, or streaming continuous inputs, unrolling an en-\ntire input sequence may not be feasible. In these cases, we can unroll the input into\nmanageable \ufb01xed-length segments and treat each segment as a distinct training item.\n8.2 RNNs as Language Models\nLet\u2019s see how to apply RNNs to the language modeling task. Recall from Chapter 3\nthat language models predict the next word in a sequence given some preceding\ncontext. For example, if the preceding context is \u201cThanks for all the\u201d and we want\nto know how likely the next word is \u201c\ufb01sh\u201d we would compute:\nP(\ufb01shjThanks for all the )\nLanguage models give us the ability to assign such a conditional probability to every\npossible next word, giving us a distribution over the entire vocabulary. We can also\nassign probabilities to entire sequences by combining these conditional probabilities\nwith the chain rule:\nP(w1:n) =nY\ni=1P(wijw