Natural Language Processing
A complete guide to Natural Language Processing (NLP): tokenization (BPE), text normalization, TF-IDF, Word2Vec semantic embeddings, sentiment analysis, and modern transformers.
Human language is rich, expressive, and full of ambiguity. Consider this everyday sentence: 'I saw the man on the hill with the telescope.' Who has the telescope? Are you looking through a telescope at a man standing on a hill? Is the man on the hill holding a telescope? Or is there an observatory telescope sitting on top of the hill? Now consider sarcasm: 'Oh wonderful, another flat tire!' A computer program looking strictly at the word 'wonderful' might conclude this is great news. Computers do not natively understand words, grammar, or cultural context. They work strictly with numbers and matrix algebra. How do we take nuanced human speech and writing and translate it into mathematical vectors that a machine can analyze, translate, summarize, and answer? That is the goal of Natural Language Processing (NLP). NLP bridges the gap between human language and computational algorithms, powering translation tools, voice assistants, search engines, and modern Large Language Models.
Definition
Natural Language Processing (NLP) is an interdisciplinary field of computer science, artificial intelligence, and linguistics focused on enabling computers to understand, interpret, generate, and manipulate human language in written and spoken forms.
Why It Matters
A huge portion of human knowledge exists as unstructured text: contracts, medical records, support conversations, emails, and research publications. Without NLP, this information is difficult to search and analyze at scale. NLP makes this text searchable and actionable: it helps legal teams review multi-page agreements in seconds, assists financial analysts in tracking market sentiment across thousands of news feeds, and enables real-time communication across dozens of languages.
How It Works
Let us examine how NLP translates raw text into semantic vectors and contextual representations: 1. Preparing Text (The Preprocessing Pipeline): Before a model can process text, the words need standard preparation: • Lowercasing: Converting characters to lowercase so 'Book' and 'book' match. • Removing Stopwords: Filtering out common grammatical words like 'the', 'is', and 'at' when performing keyword-based search. • Stemming and Lemmatization: Reducing words to their base forms. Stemming chops word endings based on rules ('running' becomes 'run'). Lemmatization uses dictionary rules to find the true root ('better' becomes 'good'). 2. Tokenization (Splitting Text into Pieces): • Word Tokenization: Splitting text on spaces. This struggles with compound words, typos, and languages without spaces like Chinese. • Subword Tokenization (Byte-Pair Encoding and WordPiece): The foundation of modern language models like GPT and BERT. Common words stay whole ('cat'), while uncommon words are split into meaningful pieces ('unprecedented' becomes 'un', 'precedent', and 'ed'). This solves the unknown word problem cleanly. 3. Classical Vectorization (Turning Words into Numbers): • Bag of Words (BoW): Counts how often each word appears in a document, ignoring order ('dog bites man' looks identical to 'man bites dog'). • TF-IDF (Term Frequency - Inverse Document Frequency): Gives higher weight to words that appear often in one document but rarely across the wider collection, highlighting distinctive topic keywords: $$TF\text{-}IDF(t, d, D) = TF(t, d) \times \ln\left(\frac{N}{DF(t)}\right)$$ 4. Dense Semantic Embeddings (Word2Vec and GloVe): TF-IDF vectors are long and mostly filled with zeros, and they do not reflect word meaning: 'happy' and 'joyful' are treated as completely separate dimensions. • Distributional Hypothesis: Words that appear in similar settings tend to share similar meanings. • Word2Vec: Trains a simple neural network to predict words from their context (CBOW) or predict context words from a central word (Skip-Gram). • Semantic Space: Words become continuous numerical vectors (often 300 dimensions) where distance reflects meaning. In this space, vector math works intuitively: $\vec{King} - \vec{Man} + \vec{Woman} \approx \vec{Queen}$. 5. Modern Contextual Transformers (BERT and GPT): Word2Vec gives each word a single fixed vector. However, the word 'bank' means something different in 'river bank' than in 'investment bank'. Modern Transformers use Self-Attention to calculate contextual embeddings, meaning a word's mathematical representation adapts to the other words in the sentence.
From Raw Human Text to Semantic Vector Space (NLP Pipeline)
Key Points
- NLP translates unstructured human language into quantitative mathematical vectors.
- Subword tokenization like Byte-Pair Encoding handles compound words and prevents out-of-vocabulary failures.
- TF-IDF highlights important terms by balancing document frequency against rarity across the corpus.
- Word embeddings map words into continuous geometric spaces where distance reflects conceptual similarity.
- Transformers create contextual embeddings where the representation of a word shifts based on surrounding words.
Steps
Select Tokenizer Matching Model Architecture
Always use the exact tokenizer paired with your pre-trained model (for instance, GPT models use BPE tokenizers while BERT uses WordPiece). Mismatched tokenizers result in garbled input IDs.
Vectorize Text
For fast keyword search or simple baselines, build TF-IDF matrices. For deeper semantic understanding, extract dense embeddings from a transformer model.
Compute Semantic Similarity (Cosine Similarity)
Measure the angle between vectors using Cosine Similarity: $\cos(\theta) = \frac{\mathbf{u} \cdot \mathbf{v}}{\|\mathbf{u}\| \|\mathbf{v}\|}$. A score of 1.0 indicates matching orientation and meaning.
Fine-Tune on Domain Data
Take a pre-trained language model and adapt it to your domain data, such as medical notes or customer support transcripts.
Deploy with Vector Databases
Save document embeddings into a vector database (such as Pinecone, Qdrant, or Milvus) to support fast semantic search in Retrieval-Augmented Generation (RAG) applications.
Formula
TF-IDF Term Weighting:
\text{TF-IDF}(t, d, D) = \text{TF}(t, d) \times \log\left(\frac{|D|}{1 + |\{d \in D : t \in d\}|}\right)
Cosine Similarity Between Dense Embeddings:
\text{CosineSimilarity}(\mathbf{u}, \mathbf{v}) = \frac{\mathbf{u} \cdot \mathbf{v}}{\|\mathbf{u}\|_2 \|\mathbf{v}\|_2} = \frac{\sum_{i=1}^d u_i v_i}{\sqrt{\sum_{i=1}^d u_i^2} \sqrt{\sum_{i=1}^d v_i^2}}
Word2Vec Skip-gram with Negative Sampling Objective:
\mathcal{L}_{SGNS} = \sum_{t=1}^T \left[ \log \sigma(\mathbf{v}'_{w_{t+j}} \cdot \mathbf{v}_{w_t}) + \sum_{k=1}^K \mathbb{E}_{w_{n,k} \sim P_n(w)} \left[ \log \sigma(-\mathbf{v}'_{w_{n,k}} \cdot \mathbf{v}_{w_t}) \right] \right]Examples
Vector Math with Word Embeddings
In a trained Word2Vec space: taking the vector for 'Paris', subtracting 'France', and adding 'Japan' lands closest to the vector for 'Tokyo', capturing the capital-city relationship mathematically.
Named Entity Recognition (NER)
An NLP model reads: 'Satya Nadella visited Microsoft headquarters in Redmond yesterday.' The system tags: [Satya Nadella: Person], [Microsoft: Organization], [Redmond: Location], and [yesterday: Date].
Real-World Examples
Financial Sentiment Analysis
Financial institutions use domain-trained NLP models to parse news releases, earnings calls, and filings in milliseconds. The models evaluate whether announcements carry positive or negative market sentiment, helping inform algorithmic trading strategies.
Personalized Language Learning Apps
Language learning platforms use NLP models to analyze student practice responses. The model identifies specific grammar mistakes, such as incorrect verb conjugation or gender agreement, and serves targeted practice exercises to help the student improve.
Technical Examples
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
# Collection of documents (Corpus)
corpus = [
"Machine learning models learn patterns from empirical training data.",
"Deep neural networks require substantial training data and GPUs.",
"A delicious recipe for homemade Italian pasta with marinara sauce."
]
# 1. Initialize TF-IDF Vectorizer (removes standard English stopwords)
vectorizer = TfidfVectorizer(stop_words='english')
tfidf_matrix = vectorizer.fit_transform(corpus)
# 2. Query search: "How does deep learning train on data?"
query = ["How does deep learning train on data?"]
query_vec = vectorizer.transform(query)
# 3. Compute Cosine Similarity between Query and All Documents
similarity_scores = cosine_similarity(query_vec, tfidf_matrix).ravel()
print("Search Query:", query[0])
print("\nDocument Relevance Scores:")
for i, score in enumerate(similarity_scores):
print(f" Doc {i+1} Score: {score:.4f} -> '{corpus[i]}'")
# Notice: Doc 1 & 2 have high scores; Doc 3 (pasta recipe) scores 0.000!Bag-of-Words / TF-IDF vs Transformer Embeddings (BERT / GPT)
| Aspect | Bag-of-Words / TF-IDF | Transformer Embeddings (BERT / GPT) |
|---|---|---|
| Representation | Sparse, high-dimensional vector with mostly zeros | Dense, continuous vector (such as 768 to 4,096 dimensions) |
| Word Order Sensitivity | None: 'dog bites man' produces the exact same vector as 'man bites dog' | High: positional encodings track word order and sentence grammar |
| Context Sensitivity | Static word counts regardless of sentence meaning | Dynamic contextual embeddings that adapt to surrounding words |
| Semantic Similarity | Cannot recognize synonyms: 'car' and 'automobile' share no overlap | Vectors that are close in space share related conceptual meaning |
| Compute & Memory Cost | Lightweight and runs quickly on standard CPUs | Computationally heavier, benefiting from GPU acceleration for batches |
Subword Tokenization Mechanics: BPE vs WordPiece vs SentencePiece
The Architectural Evolution: From Recurrent LSTMs to Self-Attention
Advantages
- Unlocks insights from large collections of unstructured text.
- Automates routine reading, summarization, and translation tasks.
- Modern embeddings capture subtle nuances, tone, and relationships across languages.
- Enables natural, conversational software interfaces.
Limitations
- Human language is context-dependent, figurative, and sometimes sarcastic.
- Models can reflect societal biases present in internet training text.
- Large transformer models require substantial memory and compute for inference.
Interview Questions
Explain the architectural difference between Continuous Bag of Words (CBOW) and Skip-Gram in Word2Vec.
Both are shallow neural architectures used to learn word embeddings: 1) CBOW (Continuous Bag of Words): Takes surrounding context words as input and predicts the target center word. It trains faster and works well for frequent words; 2) Skip-Gram: Takes the target center word as input and predicts the surrounding context words. Skip-Gram is slower, but tends to perform better on rare words and smaller datasets because each context-target pair provides a distinct training example.
How does the Self-Attention mechanism in Transformers solve the long-range dependency problem of Recurrent Neural Networks (RNNs)?
In RNNs and LSTMs, words are processed sequentially one by one, passing hidden states forward. For long documents, earlier information can get diluted or lost over many steps, and computation cannot be parallelized across tokens. Self-Attention computes direct relationships between all token pairs simultaneously using Query ($Q$), Key ($K$), and Value ($V$) matrices: $\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V$. The effective path length between any two tokens is a single step, allowing the model to capture long-range dependencies while computing efficiently across GPU cores.
Practice Questions
- Calculate the TF-IDF score for the word 'quantum' in a document where it appears 5 times out of 100 total words, given a corpus of 1,000 documents where 'quantum' appears in only 10 documents.
- Explain how you would build a spam detection pipeline using subword tokenization and a pre-trained BERT classification head.
