1. Foundations of Natural Language Processing
Text Normalization and Tokenization
Text normalization is the foundational preprocessing step that transforms raw unstructured text into a canonical form. By applying techniques like lowercasing, punctuation removal, and stopword filtering, we reduce the noise in our vocabulary space, allowing models to focus on semantic content rather than morphological variations. However, one must be cautious: while removing stopwords like 'the' or 'a' might reduce dimensionality, it can inadvertently strip away critical syntactical nuance in tasks like sentiment analysis or linguistic modeling.
Tokenization acts as the bridge between raw text and numerical representations. We move from word-level tokenization, which suffers from the out-of-vocabulary (OOV) problem, to character-level tokenization, which preserves all information but creates extremely long sequences. Modern architectures prioritize subword algorithms like Byte-Pair Encoding (BPE) or WordPiece, which iteratively merge frequent character sequences. This approach effectively balances vocabulary size with the ability to represent unseen words as combinations of known sub-units, drastically improving generalization on diverse linguistic corpora.
import torch # Simple Word-Level Tokenization Simulation text = 'Natural Language Processing is fascinating.' # Normalize and tokenize tokens = text.lower().replace('.', '').split() vocab = {token: i for i, token in enumerate(sorted(set(tokens)))} indices = [vocab[t] for t in tokens] print(f'Tokens: {tokens}\nIndices: {indices}')
Vocabulary Construction and Numerical Mapping
Building a vocabulary involves mapping every unique token to a specific integer index. This mapping is static once defined during training. The process requires a careful balance: if the vocabulary is too small, the OOV rate spikes, leading to excessive use of [UNK] tokens; if it is too large, the embedding matrix grows linearly, increasing both memory overhead and computational cost. Most practitioners define a vocabulary limit or use a fixed budget for subword merges to maintain efficiency.
Once indexed, these integers serve as lookup keys for embedding layers. In modern deep learning frameworks, these inputs are transformed into dense, continuous vector spaces of dimensionality d_model. This transformation is crucial as it allows the model to learn the relational structure between tokens, effectively capturing synonymy and semantic distance which simple integer representations lack.
import torch.nn as nn # Simulating the Embedding lookup vocab_size = 100 d_model = 16 embedding_layer = nn.Embedding(vocab_size, d_model) input_indices = torch.tensor([5, 12, 88]) # Retrieve vector representation for tokens embeddings = embedding_layer(input_indices) print(f'Embedding shape: {embeddings.shape}')
Sequence Padding and Masking
Deep learning models, specifically Transformers, require fixed-size input tensors for batch processing. Because natural language sequences vary in length, we employ padding—appending a special [PAD] token until all sequences in a batch reach the length of the longest sentence. This maintains the integrity of the data structure, allowing for efficient parallelization on GPU hardware.
However, padding introduces a potential bias: the model might learn to associate these placeholders with valid semantic information. To circumvent this, we implement attention masking. By providing a boolean or additive mask to the softmax operation within the self-attention mechanism, we instruct the model to ignore padding positions completely. This ensures that the context captured by the model reflects only genuine, non-padded token interactions.
import torch # Padding simulation seqs = [[1, 2], [3, 4, 5]] max_len = 3 padded = [s + [0]*(max_len - len(s)) for s in seqs] # Mask generation: 1 for real, 0 for padding mask = [[1 if i < len(s) else 0 for i in range(max_len)] for s in seqs] print(f'Padded Tensor: {torch.tensor(padded)}\nMask Tensor: {torch.tensor(mask)}')
Knowledge Check
Ready to test your understanding of 1. Foundations of Natural Language Processing?