Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 1 of 12
What is an Embedding?
An embedding is a way of representing text (or any data) as a list of numbers in a way that captures its meaning. Words or sentences with similar meanings get similar numbers.
Embeddings Explained Simply
An embedding is a list of numbers (called a vector) that represents a piece of text in a mathematical space.
The key property: text with similar meaning gets similar numbers.
For example:
- 'king': [0.32, 0.15, 0.87, ...]
- 'queen': [0.30, 0.17, 0.85, ...]
- 'car': [0.91, 0.03, 0.12, ...]
The numbers for 'king' and 'queen' are close to each other because the words have related meanings. The numbers for 'car' are very different because 'car' is unrelated to royalty.
This means we can do math with text:
- We can measure how similar two pieces of text are by comparing their numbers
- We can find documents that are relevant to a query
- We can organize text by topic, sentiment, or any other property
What is an Embedding? Diagram
The Famous Word2Vec Analogy
# The classic embedding analogy that shows embeddings capture meaning
# (Simplified - real embeddings have hundreds or thousands of dimensions)
# Suppose we have a simple 2-dimensional embedding space
# where each word is represented by 2 numbers
word_embeddings = {
"king": [0.8, 0.9], # High on "royalty", high on "masculine"
"queen": [0.8, 0.1], # High on "royalty", low on "masculine"
"man": [0.1, 0.9], # Low on "royalty", high on "masculine"
"woman": [0.1, 0.1], # Low on "royalty", low on "masculine"
"car": [-0.5, 0.5], # Unrelated to royalty dimension
"vehicle":[-0.4, 0.4], # Similar to "car"
}
def compute_similarity(vec1, vec2):
"""Compute how similar two vectors are (simplified)."""
# Higher number = more similar
diff_sum = sum((a - b) ** 2 for a, b in zip(vec1, vec2))
return 1 / (1 + diff_sum)
# The famous analogy: King - Man + Woman ≈ Queen
king = word_embeddings["king"]
man = word_embeddings["man"]
woman = word_embeddings["woman"]
queen = word_embeddings["queen"]
result = [king[i] - man[i] + woman[i] for i in range(len(king))]
similarity = compute_similarity(result, queen)
print("king - man + woman =", result)
print("queen =", queen)
print(f"Similarity to 'queen': {similarity:.2f}")
print("(1.0 = identical, 0.0 = completely different)")Quick Q&A
Finished this lesson?