Search Knowledge

© 2026 LIBREUNI PROJECT

Machine Learning / Deep Learning

Natural Language Processing

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:

TF-IDF(t,d,D)=TF(t,d)×log(D1+{dD:td})\text{TF-IDF}(t, d, D) = \text{TF}(t, d) \times \log\left(\frac{|D|}{1 + |\{d \in D : t \in d\}|}\right)

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 hth_t that updates at each step:

ht=tanh(Whhht1+Wxhxt+bh)h_t = \tanh(W_{hh} h_{t-1} + W_{xh} x_t + b_h)

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 QQ, keys KK, and values VV, attention weights are computed in parallel:

Attention(Q,K,V)=Softmax(QKTdk)V\text{Attention}(Q, K, V) = \text{Softmax}\left(\frac{Q K^T}{\sqrt{d_k}}\right) V

where dkd_k 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:

python

Interactive Lab

Tokenize and vectorize a small text corpus using Term Frequency-Inverse Document Frequency (TF-IDF) in scikit-learn.

Step 1
Inspect the idea
Step 2
Edit the program
Step 3
Run and compare

Exercise

Validate your understanding of text vectorization properties:

Why does TF-IDF generally perform better than simple term count vectorization for keyword search tasks?

References & Further Reading