v9.1.1
Menu

Chapter 11: NLP Fundamentals

Week 21-22

Master the foundations of Natural Language Processing, from text preprocessing and tokenization to word embeddings that capture semantic meaning. Learn to build text classification systems and understand the transformer architecture that powers modern language models like BERT and GPT.

Topics
4
Demos
4
Min read
34

Chapter Overview

Natural Language Processing (NLP) enables machines to understand, interpret, and generate human language. This field has undergone a dramatic transformation with the advent of deep learning, particularly the Transformer architecture introduced in 2017.

Traditional NLP relied heavily on hand-crafted features and rule-based systems. Modern NLP leverages neural networks that learn representations directly from raw text, capturing nuances of meaning, context, and linguistic structure that were previously impossible to encode manually.

The key insight driving modern NLP is that words and sentences can be represented as dense vectors (embeddings) in a continuous space where semantic relationships are preserved. Words with similar meanings cluster together, and analogies can be computed through vector arithmetic.

This chapter covers:

  • Text Processing: Converting raw text into numerical form through tokenization, handling vocabulary, and special tokens
  • Word Embeddings: Dense vector representations that capture semantic relationships between words
  • Text Classification: Building models for sentiment analysis, spam detection, and topic categorization
  • Transformers: The attention-based architecture behind BERT, GPT, and all modern language models

Chapter Roadmap

Click any topic to jump in

Interactive demo
1
Text Processing

Tokenization, vocabulary building, and TF-IDF — converting raw text into numerical representations for models.

TokenizationText PreprocessingVocabularySpecial Tokens
From tokens to semantic vectors
2
Word Embeddings

Dense vector representations that capture semantic meaning — Word2Vec, GloVe, and contextual embeddings from transformers.

Word2VecGloVeEmbedding LayerContextual Embeddings
Applying embeddings to real tasks

Classification and generation

3
Text Classification

Bag of words to fine-tuned transformers — sentiment analysis, spam detection, and multi-label categorization.

Bag of WordsRNN/LSTM ClassificationFine-tuning BERTMulti-label Classification
4
Transformers

BERT, GPT, and T5 — pre-trained architectures that dominate modern NLP through self-supervised learning.

BERT (Bidirectional)GPT (Autoregressive)T5 (Encoder-Decoder)Fine-tuning Strategies

Topics

4 topics in this chapter

The previous chapter, CNNs and Sequence Models, ended with attention and the Transformer, which turn a sequence of vectors into a sequence of better vectors. Text, though, does not arrive as vectors. It arrives as a string of characters such as 'The movie wasn't great!', and a neural network can only multiply numbers. Somewhere between the raw string and the first layer, the text must be cut into units, and each unit must get an integer id. Which units should we choose? Whole words leave every rare or misspelled word unknown, while single characters make sequences very long and push the job of spelling onto the model.

This chapter, NLP Fundamentals, follows text from raw string to trained model. This topic covers the first step. It starts with tokenization, especially subword methods such as BPE and WordPiece. It then covers classic preprocessing such as lowercasing and stemming, and when modern models skip it. Next comes the vocabulary that maps tokens to ids and handles unknown tokens. The topic closes with special tokens such as [CLS], [SEP], and [PAD].

Definition

Tokenization is the deterministic mapping from a raw string to a sequence of tokens drawn from a fixed vocabulary V\mathcal{V}, each replaced by its integer id in {0,…,∣V∣−1}\{0, \dots, |\mathcal{V}|-1\}. Subword tokenizers such as BPE, WordPiece, and Unigram learn V\mathcal{V} from a corpus, so frequent words remain single tokens and rare words split into known pieces.

In this topic

  1. 1Tokenization
  2. 2Text Preprocessing
  3. 3Vocabulary
  4. 4Special Tokens
1 of 4
Tokenization

Tokenization decides what a model sees as one symbol. Word-level tokenizers split on spaces and punctuation, which is intuitive but needs a huge vocabulary and still meets unseen words. Character-level tokenizers never meet an unknown symbol, but they make sequences several times longer. Subword methods sit between the two. Byte-Pair Encoding starts from characters and repeatedly merges the most frequent adjacent pair until the vocabulary reaches a target size, often 30,000 to 50,000. WordPiece, used by BERT, picks merges by likelihood gain and marks word-internal pieces with ##. Frequent words stay whole, and rare words break into known pieces. The pieces do not always match morphemes.

Mathematical Intuition

Byte-Pair Encoding starts with a character vocabulary and repeatedly merges the most frequent adjacent pair until the vocabulary reaches size VV. Each merge rescans the pair counts, so naive training costs O(V⋅N)O(V \cdot N) for corpus size NN, though efficient implementations update counts incrementally. Applying the learned merges to a word of length LL costs at most O(L2)O(L^2). A 30,000 to 50,000 token vocabulary typically produces sequences several times shorter than character-level tokenization while still covering any input. Byte-level BPE, as in GPT-2, starts from the 256 byte values, so no string is ever out of vocabulary.

Example:

Tokenize 'unhappiness' using word-level vs BPE (subword). Which handles rare words better?

2 of 4
Text Preprocessing

Classic NLP pipelines normalize text before counting words: lowercasing, stripping punctuation, removing stopwords such as 'the', and reducing words to a base form. Stemming chops suffixes by rule, so Porter's stemmer maps 'running' to 'run' but may produce non-words such as 'studi'. Lemmatization uses a dictionary and part of speech, so it maps 'ran' to 'run'. For count-based models such as TF-IDF, this merges spellings of the same concept into one feature and shrinks a sparse vocabulary. For pretrained Transformers, it usually hurts: the model was trained on raw text, and case, punctuation, and 'not' all carry meaning it can use.

Mathematical Intuition

Stemming applies rule-based suffix stripping, such as Porter's algorithm with its five phases of rules, in O(L)O(L) per word, while lemmatization uses a dictionary and part-of-speech tags to find the base form. Both merge rows of the term-document matrix, which helps count-based models by pooling sparse counts. Modern subword tokenizers do not perform this normalization: bert-base-uncased keeps 'running' and 'ran' as separate whole tokens, and its WordPiece splits 'unhappiness' as un, ##ha, ##pp, ##iness, pieces that follow corpus statistics rather than morphemes. The network learns the shared meaning from context instead.

Example:

'Running' vs 'ran' — should we lemmatize for BERT? For TF-IDF?

3 of 4
Vocabulary

The vocabulary is the lookup table from token string to integer id, built once from the training corpus and then frozen. Every id indexes a row of the embedding matrix, so vocabulary size sets both the embedding parameter count and the size of the output softmax. Tokens absent from the table either map to a reserved [UNK] id, which discards their identity, or, with subword tokenizers, are split into smaller pieces that are present. Byte-level BPE, used by GPT-2, includes all 256 bytes, so no input is ever unknown. The trade-off: a bigger vocabulary gives shorter sequences but more parameters and rarer, less trained tokens.

Mathematical Intuition

A vocabulary of size VV maps tokens to integers in [0,V)[0, V), enabling O(1)O(1) lookup via hash tables. The embedding matrix E∈RV×dE \in \mathbb{R}^{V \times d} has V⋅dV \cdot d parameters: for V=50,000V = 50{,}000 and d=768d = 768, that is 38.4 million parameters before any Transformer layer. Zipf's law, word frequency f(r)∝1/rsf(r) \propto 1/r^s for rank rr, means a small set of frequent words covers most running text, while a long tail of rare words, names, and typos never appears often enough to earn its own entry. Subword methods handle that tail by composing it from shared pieces.

Example:

Vocab: {'the':0, 'cat':1, 'sat':2, [UNK]:3}. Encode 'the dog sat'. What happens?

4 of 4
Special Tokens

Special tokens are reserved vocabulary entries that carry structure rather than text. In BERT, [CLS] is prepended to every input, and its final hidden state serves as the summary vector for classification. [SEP] ends a segment and separates sentence pairs, while segment ids of 0 and 1 tell the model which sentence each token belongs to. [PAD] fills shorter sequences so a batch forms a rectangle, and an attention mask of zeros stops real tokens from attending to padding. [MASK] replaces hidden words during masked language model pretraining. GPT-style models use different markers, such as an end-of-text token.

Mathematical Intuition

Special tokens partition the input for the model: [CLS] at position 0 aggregates sequence-level information via attention (its final hidden state serves as the sequence representation for classification), [SEP] signals segment boundaries, and [PAD] fills sequences to uniform length Lmax⁡L_{\max} with attention mask values of 0. The attention mask prevents O(n2)O(n^2) computation from wasting cycles on padding — masked positions contribute zero to the attention-weighted sum.

Example:

BERT input for sentiment classification of 'great movie'. How is it formatted?

Theory Exercise

Problem:

A corpus has 50,000 unique words. Word-level tokenization yields a vocabulary of 50,000 with frequent [UNK] tokens at test time. Why does a BPE vocabulary of only 32,000 subword tokens both shrink the embedding table AND eliminate out-of-vocabulary tokens?

Hints:
  • Think about what BPE starts from before any merges
  • Any word can be decomposed into smaller pieces
  • Relate vocabulary size to the embedding matrix dimensions

Coding Exercise

Problem:

Compare how a word-level split and a pre-trained subword tokenizer (BERT's WordPiece) handle a rare/compound word. Show that the subword tokenizer avoids out-of-vocabulary tokens by decomposing the word into pieces.

Hints:
  • Use AutoTokenizer.from_pretrained('bert-base-uncased') from the transformers library
  • Call tokenizer.tokenize(text) to see the subword pieces (## marks a continuation piece)
  • Compare the naive text.split() word list against the subword pieces