Vector Embeddings
In this section of the course, we’ll explore what embeddings are and why they are useful.
This Lesson Will Cover
- 🔢 Vector embeddings and their importance in AI/ML
- 📏 What vectors are and their key properties
- 🏛️ Traditional word embeddings like Word2Vec
- 🤖 Modern contextual embeddings (BERT, GPT)
- 🌍 Real-world applications of embeddings
What is a Vector?
Mathematically, vectors are ordered lists of numbers, where each component represents the projection along a coordinate axis. For instance, a 3-dimensional vector might be written as , representing its , , and components.
Vectors have specific mathematical properties that make them useful for embeddings:
- They have a magnitude (length) and a direction
- They can be added together, multiplied, or projected
- They can be compared (e.g., cosine similarity)
What are Vector Embeddings?
Vector embeddings are numerical representations of data that capture meaning and relationships in a way that computers can process efficiently. Or, to put it simply, they are lists of numbers - typically very large lists of continuous numbers.
By transforming complicated information (e.g., words, sentences, images) into numerical vectors, embeddings enable machines to process it effectively, while preserving (we hope) the essential characteristics and relationships of the original data.
These representations are critical for modern NLP and information retrieval systems. We’ve already encountered embeddings multiple times in this course in the context of LLMs.
Key Characteristics of Modern Embeddings
- Compact Representation: Data is encoded into fixed-size vectors, regardless of its original size.
- Semantic Meaning: Similarity in the embedding space reflects semantic similarity (e.g., “king” and “queen” will have similar embeddings).
- Learnable: Embeddings can be trained and optimized for specific tasks or domains.
- Transferable: Pre-trained embeddings can be reused across different applications.
Simple Word Embeddings
Word embeddings were among the first widely used embedding techniques. They map individual words to vectors based on their meaning, context, or usage in a corpus.
Word2Vec
Word2Vec is a model that learns embeddings by predicting words based on their context and predicting the context given a word. It uses two main approaches:
-
Skip-gram: This method predicts the surrounding context words given a target word. For example, given the word “dog” in the sentence “The dog barks loudly”, it tries to predict “The”, “barks”, and “loudly”.
-
Continuous Bag of Words (CBOW): This method does the opposite—it predicts a target word given its context words. Using the same example, given the words “The”, “barks”, and “loudly”, it tries to predict “dog”.
Through this training process, words that appear in similar contexts end up with similar vector representations, capturing semantic relationships. For instance, “dog” and “cat” will have similar vectors because they often appear near words like “pet”, “food”, “house”, etc.
We can demonstrate this using a pre-trained Word2Vec model:
from gensim.downloader import load
import numpy as np
# Load pre-trained Word2Vec embeddings trained on news data
model = load('word2vec-google-news-300')
# Get the embeddings for 'cat' and 'dog'
cat_vector = model.get_vector('cat')
dog_vector = model.get_vector('dog')
# Calculate cosine similarity between the vectors
similarity = np.dot(cat_vector, dog_vector) / (np.linalg.norm(cat_vector) * np.linalg.norm(dog_vector))
print(f"Cosine similarity between 'cat' and 'dog': {similarity:.4f}")
# Let's also find some of the most similar words to 'dog'
similar_words = model.most_similar('dog', topn=5)
print("\nMost similar words to 'dog':")
for word, score in similar_words:
print(f"{word}: {score:.4f}")
# Output:
# [==================================================] 100.0% 1662.8/1662.8MB downloaded
# Cosine similarity between 'cat' and 'dog': 0.7609
#
# Most similar words to 'dog':
# dogs: 0.8680
# puppy: 0.8106
# pit_bull: 0.7804
# pooch: 0.7627
# cat: 0.7609
Contextual Embeddings
Contextual embeddings consider the surrounding context of a word, enabling dynamic representations that differ based on usage.
BERT (Bidirectional Encoder Representations from Transformers)
BERT generates embeddings where the representation of a word depends on the entire sentence.
In the example below, we look at the tokens and embeddings generated for the sentence “BERT is a transformer model”[1]:
from transformers import AutoTokenizer, AutoModel
import torch
import torch.nn.functional as F
# Load model and tokenizer
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
model = AutoModel.from_pretrained('bert-base-uncased')
sentence = "BERT is a transformer model"
ids = tokenizer(sentence, return_tensors="pt")
with torch.no_grad():
out = model(**ids)
print(f"Output shape: {out.last_hidden_state.shape}")
print(
"\nBelow are the embedding heads "
f"(showing the first 5 of {out.last_hidden_state.shape[2]} elements)\n"
"for each token in the sentence:"
)
for idx, token in enumerate(tokenizer.convert_ids_to_tokens(ids['input_ids'][0])):
print(f"{token:10} -> {out.last_hidden_state[0, idx][:5]}")
# Output shape: torch.Size([1, 8, 768])
#
# Below are the embeddings (showing only the first 5 of 768 elements)
# for each token in the sentence:
# [CLS] -> tensor([-0.4994, -0.1460, 0.2324, -0.2227, -0.5588])
# bert -> tensor([ 0.2104, -0.4734, 0.4245, 0.0959, -0.2992])
# is -> tensor([-0.9013, -0.3535, 0.3307, -0.2989, -0.1515])
# a -> tensor([-1.1629, -0.5650, 0.7632, -0.2052, -0.4762])
# transform -> tensor([ 0.3928, -1.9051, 0.9071, 0.0394, -0.0808])
# ##er -> tensor([-0.9884, -1.2302, 0.6494, -0.2260, -0.4220])
# model -> tensor([-0.2906, -0.3994, -0.2763, -0.1006, -0.4947])
# [SEP] -> tensor([ 0.4423, -0.0803, -0.3327, 0.6473, -0.6220])
Here we are specifically looking at the final hidden state of the neural network in order to assign embeddings to each token.
Notice how BERT has attached tokens to represent the start and end of the sequence: [CLS] and [SEP].
Also, the word “transformer” has been split into two tokens with separate embeddings: transform + ##er, where the ## has been added to signal “this continues the previous token”.
GPT (Generative Pre-trained Transformer)
GPT models also produce contextual embeddings, but with a key difference in how they process context—they use a masked self-attention mechanism that prevents tokens from attending to future positions during pre-training and inference, unlike BERT, which uses bidirectional attention.
Here’s an example comparing the word “bank” in the context of a “river bank” and a “financial bank”, using GPT-2:
from transformers import AutoTokenizer, AutoModel
import torch
import torch.nn.functional as F
# Load GPT-2 model and tokenizer
tokenizer = AutoTokenizer.from_pretrained('gpt2')
model = AutoModel.from_pretrained('gpt2')
def get_word_embedding(sentence, word):
# Tokenize the sentence and find the position of our target word
inputs = tokenizer(sentence, return_tensors="pt", add_special_tokens=False)
sentence_tokens = tokenizer.tokenize(sentence)
# GPT-2 uses space prefixes (Ġ) for words after whitespace in BPE tokenization
word_tokens = tokenizer.tokenize(" " + word) # Ensure correct BPE tokenization
# Find position of the first token of the word in the tokenized sentence
word_start = None
for i in range(len(sentence_tokens) - len(word_tokens) + 1):
if sentence_tokens[i:i + len(word_tokens)] == word_tokens:
word_start = i
break
if word_start is None:
raise ValueError(f"Word '{word}' not found in tokenized sentence.")
# Get model output
with torch.no_grad():
outputs = model(**inputs)
# Extract embedding for the first token of the target word
word_embedding = outputs.last_hidden_state[0, word_start]
return F.normalize(word_embedding, p=2, dim=0) # Normalize the vector
# Get embeddings for 'bank' in different contexts
river_bank_emb = get_word_embedding("The river bank was muddy", "bank")
financial_bank_emb_1 = get_word_embedding("The financial bank was closed", "bank")
financial_bank_emb_2 = get_word_embedding("The financial bank was open", "bank")
print("Printing the first 5 embedding dimensions")
print(f"bank (river context): {river_bank_emb[:5]}")
print(f"bank (finance context): {financial_bank_emb_1[:5]}")
print(f"bank (finance context): {financial_bank_emb_2[:5]}")
# Printing the first 5 embedding dimensions
# bank (river context): tensor([-0.0034, 0.0017, -0.0055, 0.0025, 0.0011])
# bank (finance context): tensor([-1.5110e-03, 1.7304e-05, -4.1355e-03, 1.4719e-03, 2.1846e-03])
# bank (finance context): tensor([-1.5110e-03, 1.7304e-05, -4.1355e-03, 1.4719e-03, 2.1846e-03])
Have a look at the outputs from the two financial bank embedding examples. Do you notice how they are the same - even though the sentences are different? This is due to the masked self-attention that we mentioned earlier.
Real-World Applications of Vector Embeddings
Vector embeddings have become integral to many AI systems across the tech industry. Here are some of the most prominent examples:
- Search Engines: Google and Bing use embeddings to understand user queries and retrieve relevant results.
- Recommendation Systems: Platforms like Netflix and Spotify recommend items based on the similarity of embeddings.
- Sentiment Analysis: Companies analyze customer feedback by embedding text and clustering similar opinions.
- Language Translation: Embeddings are used to map words and phrases from different languages into a shared vector space, facilitating neural machine translation.
Conclusion
It’s common to hear that an embedding “captures the semantic meaning” of the text that it represents. It’s important to understand that the degree to which this semantic meaning is actually captured depends on the language model that’s used to create the embeddings.
I made a video to explore this and teach embeddings with a hands-on python demo, building up from the “dumbest” form of embeddings model (One-Hot Encoding) to a highly performant embedding model (GPT).[2]
Key Takeaways
🔢 Vector embeddings are numerical representations that capture meaning and relationships in data.
🏷️ Traditional word embeddings like Word2Vec map individual words to vectors based on context.
🧠 Modern contextual embeddings from models like BERT and GPT generate dynamic representations based on full context.
⚡ Embeddings enable efficient computation while preserving semantic relationships.
🌍 Real-world applications include search, recommendations, sentiment analysis, and translation.
Next: Embedding Search
In the next lesson, we’ll take these concepts further by exploring embedding search - how we compare embeddings and do retrieval at scale.
Footnotes
I updated the BERT example significantly (August 2025) and the audio may still reflect the previous version. ↩︎
Text Embeddings with Python 15 minute hands-on python tutorial on YouTube. ↩︎
Comments (0)
No comments yet.