Natural Language Processing
Natural Language Processing (NLP) focuses on translating text sequences into mathematical representations that algorithms can learn from.
Statistical Representation: TF-IDF
TF-IDF (Term Frequency-Inverse Document Frequency) measures how important a word is to a document in a corpus:
While effective for classification, TF-IDF ignores word order and semantic similarity.
Sequence Modeling: RNNs and Attention
To handle sequential context, Recurrent Neural Networks (RNNs) maintain a hidden state vector that updates at each step:
The Bottleneck of RNNs
RNNs struggle with long-term dependencies because gradients vanish over long sequence lengths. While LSTM (Long Short-Term Memory) and GRU (Gated Recurrent Unit) architectures use gating mechanisms to help, they still process tokens sequentially, which limits parallel training.
Self-Attention and the Transformer
The Transformer architecture replaces recurrent loops with Self-Attention. For queries , keys , and values , attention weights are computed in parallel:
where is the dimension of the key vectors. This allows the model to capture relationships between words regardless of their distance in the sequence. Positional encodings are added to the input embeddings to represent sequence order. Transformers process the entire sequence in parallel via multi-head attention, capturing complex relationships between distant words. This represents a significant advancement over sequential RNN processing.
Example: TF-IDF Vectorization
The following example demonstrates tokenizing and vectorizing text using TF-IDF:
Interactive Lab
Tokenize and vectorize a small text corpus using Term Frequency-Inverse Document Frequency (TF-IDF) in scikit-learn.
Exercise
Validate your understanding of text vectorization properties: