Introduction
Humans are adept at processing language — it’s the very fabric of how we communicate. But what do we really mean by “processing language”? It’s the ability to understand both the information and the intent being conveyed. While we draw on other audio-visual cues such as tone and expression, the core of information exchange still lies in the content itself. The science of Natural Language Processing (NLP) in machines aims to mirror this human capability. The goal of NLP techniques is to convert the text and its meanings into nearest posible numerical representation for the machines to work on it.
The following are some foundational concepts traditionally used in building machine learning models that can interpret textual content — uncovering both explicit and latent information within it.
Explanation and Demonstration of some of the key foundation NLP concepts
As a start let us look at the way in which a textual paragraph in English is broken down for further processing.
Text preprocessing and Cleaning:
As part of preprocessing the text, let us start with change all text to lowercase. This ensures that the machine doesnot distinguish between "Apple" and "apple". Preprocessing reduces noise and normalizes text to make patterns easier for models to capture. Standard steps include:
- Normalization — lowercasing, punctuation handling
- Optional stemming or lemmatization
- Removal of stop words when appropriate
- Segmentation into sentences
- Tokenization into words / subwords / characters
Example — python code to lowercase
# Sample raw text
raw_text = "Dr. Smith, a renowned researcher, has been studying various computing methods."
# Convert to lowercase
lower_text = raw_text.lower()
print(f"Original: {raw_text}")
print(f"Lowercase: {lower_text}")Output:
Original: Dr. Smith, a renowned researcher, has been studying various computing methods.
Lowercase: dr. smith, a renowned researcher, has been studying various computing methods.Lowercasing reduces token sparsity and is usually a safe first normalization.
Tokenization
This means that we break down the text into smaller units which will be used for further processing. Now, when we break the text into tokens, the choice is ours to define whether a word, a character or a sentence can be considered as tokens. In some instances, tokens can be a subword (essentially taking common words as token, while for uncommon words it breaks down to smaller meaningful parts).
The choice of the tokenization strategy is guided by trade off between:
a) Size of the text,
b) Meaning captured by the token.
For a very large text, taking characters as words or sentences might be helpful, whereas for smaller size of text e.g. sequence of the DNA, words donot have any meaning, instead the sequence of characters become all the more important. Following are some of the python examples of tokenization.
Word tokenization
import nltk
nltk.download('punkt')
sentence = "Tokenization is a key step in NLP."
word_tokens = nltk.word_tokenize(sentence)
print(word_tokens) # ['Tokenization', 'is', 'a', 'key', 'step', 'in', 'NLP', '.']Output:
[nltk_data] Downloading package punkt_tab to /root/nltk_data...
[nltk_data] Unzipping tokenizers/punkt_tab.zip.
Original: 'Tokenization is a key step in NLP.'
Word Tokens: ['Tokenization', 'is', 'a', 'key', 'step', 'in', 'NLP', '.']Subword tokenizers (BPE / WordPiece) are preferable for large vocabularies and modern transformer architectures.
Sentence tokenization
import nltk
paragraph = "NLP stands for Natural Language Processing. It's a fascinating field. Dr. Smith agrees."
# Split the paragraph into sentence tokens
sentence_tokens = nltk.sent_tokenize(paragraph)
print(f"Original: '{paragraph}'")
print(f"Sentence Tokens: {sentence_tokens}")Output:
Original: 'NLP stands for Natural Language Processing. It's a fascinating field. Dr. Smith agrees.'
Sentence Tokens: ['NLP stands for Natural Language Processing.', "It's a fascinating field.", 'Dr. Smith agrees.']Character tokenization
# A sample DNA sequence
dna_sequence = "GATTACAAGTCGAT"
# Character tokenization is as simple as converting the string to a list
tokens = list(dna_sequence)
print(f"Original DNA Sequence: {dna_sequence}")
print(f"Character Tokens: {tokens}")
# Now you can easily perform analyses, like counting nucleotide frequency
adenine_count = tokens.count('A')
print(f"Count of Adenine ('A'): {adenine_count}")Output:
Original DNA Sequence: GATTACAAGTCGAT
Character Tokens: ['G', 'A', 'T', 'T', 'A', 'C', 'A', 'A', 'G', 'T', 'C', 'G', 'A', 'T']
Count of Adenine ('A'): 5Sub Word Tokenization - Splits the text into whole words and meaningful subwords ( e.g. "agent is multitasking" might be broken down to['agent', 'multi' and 'tasking']. This solves the OOV problem (OOV = Out of Vocabulary) which essentially means that the system faces a word which it would not have encountered during its training. (Think of the blank face when we ask our kids about an word unknown to him/her!!). With subwords the probability of such encounters reduces drastically and hence that is favoured in mature models like BERT and GPT.
Example of Subword tokenization
# from tokenizers import BertWordPieceTokenizer
from transformers import AutoTokenizer
# Load a pre-trained tokenizer
# tokenizer = BertWordPieceTokenizer.from_pretrained("bert-base-uncased")
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
sentence = "Subword tokenizers handle vocabularies efficiently."
## get the actual tokens
tokens = tokenizer.tokenize(sentence)
# Encode the sentence to get subword tokens
encoding = tokenizer.encode(sentence)
print(f"Original: '{sentence}'")
print(f"Subwords: {tokens}")
print(f"Tokens:{encoding}")Output:
Original: 'Subword tokenizers handle vocabularies efficiently.'
Subwords: ['sub', '##word', 'token', '##izer', '##s', 'handle', 'vo', '##ca', '##bular', '##ies', 'efficiently', '.']
Tokens:[101, 4942, 18351, 19204, 17629, 2015, 5047, 29536, 3540, 28808, 3111, 18228, 1012, 102]Stop words removal, Stemming and Lemmatization are other steps that are usually performed as part of the data preprocessing. Stop words indicate common words like prepositions or articles ['a', 'the' etc.] that are used to string words together to make coherent sentences. Since these words donot have any value on their own in terms of information, they are removed. NLTK library has a corpus of stop words which can be used to remove the ones present within the text that we are processing.
Consider the text "Finally, the studies continued". If I were to lowercase all the text, remove stop words, have words as tokens I would have ['finally,','studies', 'continued'] as a result.
The process of Stemming applies crude rules to chop of the end of the words. In the above instance the outcome would be ['final','studi','continu']. Notice how it takes out the last 2 letters from each word resulting in non meaningful words.
Lemmatization on the other hand tries to find out the actual root word. In the above example if it were applied, it would result in ['final','study','continue'], all of them correct dictionary forms.
If the chance of getting meaningless words are high during Stemming, the important question arises - Why do we then even have the need of Stemming?
Stemming is used because it is much faster (with basic rules based execution) and requires less memory than lemmatization, although it reduces accuracy. This option becomes the choice for performance-critical tasks like search engine indexing. The nature of the problem allows this trade-off on linguistic accuracy for computational speed on top of massive datasets.
Representing the processed text as numbers
Now that we have broken down a large text into smaller units, We will represent them numerically because machine learning models and computers fundamentally operate on numbers, not words. This conversion — known as vectorization or embedding — enables us to apply mathematical operation to language, and while utilizing the meaning of the text.
Let’s assume we represent the word “king” as [0, 8, 8], while “queen” is represented as [1, 2, 8]. Suppose the first element in the array captures gender (man or woman), the second represents warrior attributes, and the third reflects royalty. Each of these features contributes to the overall meaning of the word, embedding deeper nuances within the numerical representation itself.
In the following section we talk about some of the most common methods to enable this representation.
Bag of Words (BoW)
This is the simplest method of representing text numerically. It describes a document by the frequency of each word within it, completely ignoring word order and grammar. Think of it as creating a histogram of word counts for each document.
BoW example
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.feature_extraction.text import CountVectorizer
# A unique but simple corpus about celestial bodies 🔭
corpus = [
'The sun is a bright star',
'The moon is not a star',
'The earth has one moon'
]
# Initialize the CountVectorizer
vectorizer = CountVectorizer()
# Fit the vectorizer to the corpus and transform the corpus into a BoW matrix
X = vectorizer.fit_transform(corpus)
# Get the vocabulary (the unique words)
feature_names = vectorizer.get_feature_names_out()
# Create a pandas DataFrame for better visualization
bow_df = pd.DataFrame(X.toarray(), columns=feature_names)
print("--- Bag-of-Words Matrix ---")
print(bow_df)
# --- Chart Generation ---
# Sum the word counts across all documents (sentences)
word_counts = bow_df.sum(axis=0)
# Create a bar chart
plt.figure(figsize=(10, 6))
word_counts.sort_values().plot(kind='barh', color='skyblue')
plt.title('Word Frequency in Corpus (Bag-of-Words)')
plt.xlabel('Frequency (Count)')
plt.ylabel('Words')
plt.tight_layout() # Adjust layout to make room for labels
plt.show()
BoW is lightweight and interpretable, ideal for quick prototyping.
TF–IDF
TF-IDF - Term frequency and Inverse Document Frequency This is a score derived as a product of Term Frequency (how frequent a term is present in the document) and Inverse Document Frequency ( how important a word is by looking at how many documents contain it).
The TF is calculated as - Frequency of a word / Total number of words in the document.
IDF is calculated as - log( (Total number of documents / Number of documents with the term) + 1) - This measures how important a word is by looking at how many documents contain it. Common words like "the" or "is" will have a low IDF score, while rare words will have a high score.
where is the total number of documents, is the number of documents containing the term , and is the natural log.
The final TF-IDF score = TFxIDF.
Let's analyze a small collection of sentences about cooking:
Document 1: "Chicken curry is a spicy dish."
Document 2: "I love spicy chicken wings."
Document 3: "This curry recipe is simple."
This corpus has overlapping words like "chicken," "curry," and "spicy," as well as unique words like "dish," "wings," and "recipe."
TF-IDF example
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
# A new corpus of documents about food recipes
corpus = [
'Chicken curry is a spicy dish',
'I love spicy chicken wings',
'This curry recipe is simple'
]
# Initialize the TfidfVectorizer
tfidf_vectorizer = TfidfVectorizer()
# Fit the vectorizer to the corpus and transform it into a TF-IDF matrix
tfidf_matrix = tfidf_vectorizer.fit_transform(corpus)
# Get the feature names (the vocabulary)
feature_names = tfidf_vectorizer.get_feature_names_out()
# Create a pandas DataFrame for better visualization
df_tfidf = pd.DataFrame(tfidf_matrix.toarray(), columns=feature_names)
print("--- TF-IDF Matrix for Food Recipes ---")
print(df_tfidf.round(2)) # Round for cleaner outputOutput:
chicken curry dish is love recipe simple spicy this wings
0 0.42 0.42 0.55 0.42 0.00 0.00 0.00 0.42 0.00 0.00
1 0.43 0.00 0.00 0.00 0.56 0.00 0.00 0.43 0.00 0.56
2 0.00 0.37 0.00 0.37 0.00 0.49 0.49 0.00 0.49 0.00TF–IDF often yields better discriminative features for classical ML models compared to raw counts.
Note: scikit-learn's TfidfVectorizer uses a smoothed IDF, normalizes each document's vector, and drops one-letter words like "a" and "I", so its numbers differ from the formula above. The table below works the same corpus by hand with the formulas above (lowercased, punctuation removed, all words kept; Document 1 has 6 words, Documents 2 and 3 have 5 each).
| Word | Docs with term | IDF | TF-IDF Doc 1 | TF-IDF Doc 2 | TF-IDF Doc 3 |
|---|---|---|---|---|---|
| a | 1 | 1.39 | 0.23 | 0.00 | 0.00 |
| chicken | 2 | 0.92 | 0.15 | 0.18 | 0.00 |
| curry | 2 | 0.92 | 0.15 | 0.00 | 0.18 |
| dish | 1 | 1.39 | 0.23 | 0.00 | 0.00 |
| i | 1 | 1.39 | 0.00 | 0.28 | 0.00 |
| is | 2 | 0.92 | 0.15 | 0.00 | 0.18 |
| love | 1 | 1.39 | 0.00 | 0.28 | 0.00 |
| recipe | 1 | 1.39 | 0.00 | 0.00 | 0.28 |
| simple | 1 | 1.39 | 0.00 | 0.00 | 0.28 |
| spicy | 2 | 0.92 | 0.15 | 0.18 | 0.00 |
| this | 1 | 1.39 | 0.00 | 0.00 | 0.28 |
| wings | 1 | 1.39 | 0.00 | 0.28 | 0.00 |
TF is 1/6 ≈ 0.17 for every word in Document 1 and 1/5 = 0.20 for every word in Documents 2 and 3, since no word repeats within a document.
Here’s a breakdown of the results:
High-Scoring Words (High Importance):
The words "dish" (0.23 in Doc 1), "wings" (0.28 in Doc 2), and "recipe" (0.28 in Doc 3) have high scores. This is because they each appear in only one document. Their high Inverse Document Frequency (IDF) makes them powerful keywords for identifying that specific document.
Medium-Scoring Words (Shared Importance):
Look at "chicken" and "spicy." They appear in two out of the three documents. Because they are more common than words like "dish" or "wings," their IDF is lower, resulting in moderate TF-IDF scores. They are important but not unique.
Comparing a Word Across Documents:
The word "curry" has a score of 0.15 in Document 1 and 0.18 in Document 3. The slight difference is due to the Term Frequency (TF) calculation, which considers the total number of words in each document. This shows how the score is always relative to the document it's in.
In summary
A high TF-IDF score signifies that the word appears frequently within that one document (high Term Frequency) but is rare across the entire collection of documents (high Inverse Document Frequency).
Hence, higher the TF-IDF score of a word for a particular document, the more import the word carries in representating the content of the document.
Word2Vec & Embeddings
TF-IDF treats word frequency as a proxy for importance — an approach that works well for keyword extraction but falls short of understanding meaning. Word2Vec, however, operates differently. Its core idea is that a word’s meaning is shaped by the words that appear around it. It creates dense numerical vectors that capture these contextual relationships. A brief idea about Embeddings: Imagine every word you know is a point in space. Words that mean similar things — king and queen, or dog and puppy — live close together. Word embeddings are these points, learned not from dictionaries or grammar rules, but from how words appear together in real text. The most popular early methods to build these embeddings were Word2Vec (from Google) and GloVe (from Stanford). The vectors (embeddings) that are generated from these models will provide a more meaningful representation of the words and their relationships.
To summarize: for identifying similarity between words like “cat” and “kitten,” an embedding Word2Vec is a better choice than TF-IDF, which would treat them as two distinct words. They offer richer semantic meaning and contextual understanding.
In the example below, we’ll use Word2Vec from the gensim library. But before that, let’s understand how it works to generate a vector for a word such as “cat.”
Word2Vec doesn’t store a list of English words. It learns its vocabulary from scratch by scanning massive amounts of text and adjusting its internal numbers to reflect how words appear in similar contexts.
Vocabulary: The list of all words it has learned.
Vector Lookup Table (Embedding Matrix): For each word in the vocabulary, there is a corresponding dense vector — a list of numbers (often 300 long) representing its learned meaning.
You can think of it as a dictionary where the key is the word and the value is its vector representation.
a. Learning Phase: When the model encounters a new word, it first assigns it a random vector. It then reads the input text, sentence by sentence, looking at words within a small context window (e.g., a few words before and after the target word).
b. Measuring Error: Initially, predictions are poor because the vectors are random. The model compares its predictions with the actual context words and calculates an error value.
c. Adjusting the Vectors (Learning): Using this error, the model slightly adjusts the vectors involved. Two architectures drive this learning: CBOW (Continuous Bag of Words) and Skip-gram.
It’s built on two simple but powerful ideas:
CBOW (Continous Bag of words): Predicts a target word from its surrounding context. For example, given “The cat ___ on the mat,” the model uses the surrounding words to predict the missing one. It averages the vectors of the context words and compares its prediction with the actual word, minimizing error over many iterations.
Skip-gram: Works in reverse. Given a single word (say, “cat”), it predicts the surrounding words like “fluffy,” “chased,” or “mouse.” This approach often performs better for rare words, as it learns from multiple contexts.
Once training is complete, each word in the corpus has its own vector representation.
One limitation remains, though: Word2Vec assigns a single vector to each word, regardless of its meaning in different contexts. So “python” as a snake and “Python” as a programming language share the same vector — a reminder that true language understanding still lies beyond simple embeddings.
Sketch — training Word2Vec with CBOW and Skip-gram
# -------------------------------------------------------------
# 🧠 Word2Vec Explained — CBOW and Skip-Gram in Action
# -------------------------------------------------------------
# Word2Vec is an algorithm that learns to represent words
# as dense vectors based purely on how they appear together
# in a large corpus of text.
#
# The idea: "You shall know a word by the company it keeps."
# -------------------------------------------------------------
!pip install gensim
from gensim.models import Word2Vec
# -------------------------------------------------------------
# Define a small, illustrative training corpus.
#
# Each sentence is a list of words (tokens). In real-world NLP,
# you would preprocess text (lowercasing, removing punctuation,
# tokenizing with NLTK or spaCy) and train on millions of sentences.
# -------------------------------------------------------------
sentences = [
["the", "cat", "sat", "on", "the", "mat"],
["the", "dog", "barked", "at", "the", "cat"],
["dogs", "and", "cats", "are", "great", "pets"],
["the", "cat", "chased", "the", "mouse"],
["the", "dog", "chased", "the", "ball"]
]
# -------------------------------------------------------------
# Train Word2Vec using CBOW (Continuous Bag of Words)
#
# CBOW tries to predict the target word given its surrounding context.
# Example: “the cat ___ on the mat” → predict “sat”.
#
# Parameters:
# - vector_size: length of the word vector
# - window: number of context words to look at (before/after target)
# - min_count: ignore words that appear fewer times than this
# - sg: 0 for CBOW (default), 1 for Skip-Gram
# - epochs: number of training iterations over the corpus
# -------------------------------------------------------------
print("\nTraining Word2Vec (CBOW model)...")
model_cbow = Word2Vec(
sentences=sentences,
vector_size=50,
window=3,
min_count=1,
sg=0, # CBOW
epochs=100
)
print("CBOW training complete.\n")
# -------------------------------------------------------------
# Train Word2Vec using Skip-Gram
#
# Skip-Gram works the other way around — given a single word,
# it tries to predict the surrounding context words.
# Example: given “cat” → predict “sat”, “mat”, “the”, etc.
#
# Skip-Gram tends to perform better on infrequent words.
# -------------------------------------------------------------
print("Training Word2Vec (Skip-Gram model)...")
model_sg = Word2Vec(
sentences=sentences,
vector_size=50,
window=3,
min_count=1,
sg=1, # Skip-Gram
epochs=100
)
print("Skip-Gram training complete.\n")
# -------------------------------------------------------------
# Inspect the learned vocabulary
#
# Both models build an internal "dictionary" of all words they
# encountered during training. Each word now has a learned
# vector representation in a 50-dimensional space.
# -------------------------------------------------------------
print("Vocabulary (CBOW):")
print(list(model_cbow.wv.key_to_index.keys()), "\n")
# -------------------------------------------------------------
# Check semantic similarity between words
#
# Similarity is computed as cosine similarity between word vectors.
# Higher values mean the words appear in similar contexts.
# -------------------------------------------------------------
print("Similarity between 'cat' and 'dog' (CBOW):",
model_cbow.wv.similarity("cat", "dog"))
print("Similarity between 'cat' and 'mouse' (CBOW):",
model_cbow.wv.similarity("cat", "mouse"))
print()
print("Similarity between 'cat' and 'dog' (Skip-Gram):",
model_sg.wv.similarity("cat", "dog"))
print("Similarity between 'cat' and 'mouse' (Skip-Gram):",
model_sg.wv.similarity("cat", "mouse"))
print()
# -------------------------------------------------------------
# Explore "most similar" words — words with vectors close in meaning
# -------------------------------------------------------------
print("Most similar to 'cat' (CBOW):")
print(model_cbow.wv.most_similar("cat"), "\n")
print("Most similar to 'cat' (Skip-Gram):")
print(model_sg.wv.most_similar("cat"), "\n")
# -------------------------------------------------------------
# Inspect a word vector itself.
#
# Each word is represented as a list of floating-point numbers.
# These numbers capture semantic dimensions of meaning that
# the model has learned through co-occurrence patterns.
# -------------------------------------------------------------
print("Vector representation for 'cat' (first 10 values, CBOW):")
print(model_cbow.wv["cat"][:10], "\n")
# -------------------------------------------------------------
# 🧩 Summary
#
# - CBOW predicts a word from its context (faster, good for common words).
# - Skip-Gram predicts context from a word (slower, better for rare words).
# - Both models learn from patterns of word co-occurrence.
# - The resulting embeddings capture semantic relationships
# — e.g., "cat" and "dog" have similar vectors because
# they appear in similar contexts.
#
# Word2Vec doesn’t understand language; it captures statistical
# patterns of usage that *approximate* meaning.
# -------------------------------------------------------------Output:
Collecting gensim
Downloading gensim-4.4.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl.metadata (8.4 kB)
Requirement already satisfied: numpy>=1.18.5 in /usr/local/lib/python3.12/dist-packages (from gensim) (2.0.2)
Requirement already satisfied: scipy>=1.7.0 in /usr/local/lib/python3.12/dist-packages (from gensim) (1.16.2)
Requirement already satisfied: smart_open>=1.8.1 in /usr/local/lib/python3.12/dist-packages (from gensim) (7.4.0)
Requirement already satisfied: wrapt in /usr/local/lib/python3.12/dist-packages (from smart_open>=1.8.1->gensim) (2.0.0)
Downloading gensim-4.4.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl (27.9 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 27.9/27.9 MB 19.6 MB/s eta 0:00:00
▶ Training Word2Vec (CBOW model)...
✓ CBOW training complete.
▶ Training Word2Vec (Skip-Gram model)...
✓ Skip-Gram training complete.
📘 Vocabulary (CBOW):
['the', 'cat', 'chased', 'dog', 'ball', 'mouse', 'pets', 'great', 'are', 'cats',
'and', 'dogs', 'at', 'barked', 'mat', 'on', 'sat']
🔹 Similarity (CBOW)
cat ↔ dog → -0.17529058
cat ↔ mouse → 0.031076493
🔹 Similarity (Skip-Gram)
cat ↔ dog → -0.17043228
cat ↔ mouse → 0.030792557
💠 Most similar to 'cat' (CBOW):
[('sat', 0.2324), ('ball', 0.1291), ('pets', 0.0880), ('at', 0.0873),
('the', 0.0592), ('mouse', 0.0310), ('mat', 0.0301), ('chased', 0.0240),
('cats', 0.0137), ('barked', 0.0011)]
💠 Most similar to 'cat' (Skip-Gram):
[('sat', 0.2357), ('ball', 0.1305), ('pets', 0.0932), ('at', 0.0921),
('the', 0.0731), ('mat', 0.0389), ('chased', 0.0324), ('mouse', 0.0307),
('cats', 0.0202), ('barked', 0.0040)]
🧠 Vector representation for 'cat' (first 10 values, CBOW):
[-0.0165194 0.0089593 -0.0080939 0.00177217 0.01662199 -0.00919126
0.00945288 -0.0135966 -0.00766755 0.01835819]Embeddings can be used directly for similarity, clustering, or as inputs to supervised models.
GloVe (Global Vectors for Word Representation): learns word meanings by studying how often words appear together across an entire text corpus. It converts these global co-occurrence patterns into numerical vectors, so words that frequently share context — like coffee and mug — end up close together in the vector space.
Sketch — training GloVE
# -------------------------------------------------------------
# ☕ GloVe in Action — Learning Meaning from Global Co-occurrence
# -------------------------------------------------------------
# Unlike Word2Vec which predicts words from local context,
# GloVe learns from how frequently words co-occur across
# the entire text corpus. It turns co-occurrence statistics
# into rich vector representations of meaning.
# -------------------------------------------------------------
import gensim.downloader as api
print("Loading pre-trained GloVe model...")
# 'glove-wiki-gigaword-50' is trained on 6 billion tokens from
# Wikipedia + Gigaword corpus. Each word → 50-dimensional vector.
model = api.load("glove-wiki-gigaword-50")
print("Model loaded successfully!\n")
# -------------------------------------------------------------
# Let’s explore some semantic relationships captured globally.
# -------------------------------------------------------------
# 1️⃣ Word similarity — how close are meanings based on co-occurrence?
print("Similarity between 'coffee' and 'tea':", model.similarity('coffee', 'tea'))
print("Similarity between 'coffee' and 'computer':", model.similarity('coffee', 'computer'))
print()
# 2️⃣ Analogy: GloVe understands relational meaning
# 'king' is to 'man' as 'queen' is to ?
print("Analogy task — 'king' - 'man' + 'woman' ≈ ?")
print(model.most_similar(positive=['king', 'woman'], negative=['man']), "\n")
# 3️⃣ Odd-one-out: Find the word that doesn’t fit
words = ['breakfast', 'lunch', 'dinner', 'computer']
odd_one = model.doesnt_match(words)
print(f"In the list {words}, the odd one out is: '{odd_one}'\n")
# 4️⃣ Explore nearby words in the embedding space
print("Words most similar to 'coffee':")
print(model.most_similar('coffee'), "\n")
# -------------------------------------------------------------
# ✍️ Observations
# -------------------------------------------------------------
# - 'coffee' and 'tea' are close because they co-occur in similar contexts.
# - 'coffee' and 'computer' are distant — they rarely appear together.
# - The analogy test shows GloVe captures relationships between concepts,
# not just surface similarity.
#
# GloVe:
# distills global co-occurrence patterns into vectors
# that reflect the underlying structure of meaning.
# -------------------------------------------------------------Output:
▶ Loading pre-trained GloVe model...
[==================================================] 100.0% 66.0/66.0MB downloaded
✓ Model loaded successfully!
🔹 Similarities:
coffee ↔ tea → 0.8079648
coffee ↔ computer → 0.36260256
🤴 Analogy task — 'king' - 'man' + 'woman' ≈ ?
[('queen', 0.8523), ('throne', 0.7664), ('prince', 0.7592), ('daughter', 0.7473),
('elizabeth', 0.7460), ('princess', 0.7424), ('kingdom', 0.7337), ('monarch', 0.7214),
('eldest', 0.7184), ('widow', 0.7099)]
💭 In the list ['breakfast', 'lunch', 'dinner', 'computer'],
the odd one out is → 'computer'
☕ Words most similar to 'coffee':
[('drink', 0.8187), ('drinks', 0.8176), ('wine', 0.8141), ('tea', 0.8079),
('beer', 0.8042), ('food', 0.7853), ('sugar', 0.7774), ('corn', 0.7606),
('vegetable', 0.7600), ('beverage', 0.7582)]Summary
Now that we have powerful ways to turn text into numerical vectors, the next logical step is to feed these features into machine learning models to perform specific tasks. The upcoming series will explore how these representations are used in practice. We will delve into classic supervised learning algorithms like Naive Bayes and Logistic Regression for text classification tasks such as sentiment analysis or spam detection. We will also explore unsupervised methods like K-Means Clustering to automatically group similar documents together, uncovering hidden structures within our text data. This next phase will bridge the gap between text representation and building intelligent, predictive NLP applications.