How does Word2Vec work?

Authors
How does Word2Vec work?

Word2Vec is a technique that turns each word into a list of numbers, in such a way that words with similar meaning get similar numbers.

In this blog, we will learn about how Word2Vec works. We will also see why we need Word2Vec, how a computer turns a word into a vector, how it learns these vectors through CBOW and Skip-gram, how word math works, what its limitations are, and where it is used in the real world.

We will cover the following:

  • What is Word2Vec?
  • Why do we need Word2Vec?
  • How does a computer represent a word?
  • The core idea: a word is known by the company it keeps
  • What is a word vector?
  • The two architectures: CBOW and Skip-gram
  • A step-by-step walk-through of Skip-gram
  • How Word2Vec learns the vectors
  • Word math (king - man + woman = queen)
  • A simple code example
  • Limitations of Word2Vec
  • Where Word2Vec is used

I am Amit Shekhar, Founder @ Outcome School, I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.

I teach AI and Machine Learning at Outcome School.

Let's get started.

What is Word2Vec?

Word2Vec is a technique that turns each word into a list of numbers, in such a way that words with similar meaning get similar numbers.

The name Word2Vec means "Word to Vector". We take a word, and we convert it to a vector. A vector is a list of numbers.

Let's say we give the word "king" a list of numbers and the word "queen" another list of numbers. With Word2Vec, these two lists will be very close, because the two words are related. The word "banana" will get a list of numbers that is very far away, because it has nothing to do with kings and queens.

Why do we need Word2Vec?

A computer does not understand words. A computer only understands numbers. So, before a computer can work with language, we must turn words into numbers.

Now, the question is: how do we turn a word into numbers?

The simplest idea is to give every word a unique number. For example, "cat" becomes 1, "dog" becomes 2, "king" becomes 3, and so on. But this has a big problem. These numbers are random. The number 1 for "cat" and the number 2 for "dog" do not tell us that a cat and a dog are both animals. The numbers carry no meaning.

So, here comes a slightly better idea called one-hot encoding.

In one-hot encoding, we make a long list with one slot for every word in our vocabulary. For a single word, we put a 1 in its own slot and 0 everywhere else.

Let's say our whole vocabulary has only four words: "cat", "dog", "king", and "queen". Then one-hot encoding looks like below:

cat    = [ 1, 0, 0, 0 ]
dog    = [ 0, 1, 0, 0 ]
king   = [ 0, 0, 1, 0 ]
queen  = [ 0, 0, 0, 1 ]

Here, we can see that each word gets its own slot. The word "cat" has a 1 in the first slot, "dog" has a 1 in the second slot, and so on.

But this still has two big problems.

Problem 1: The lists are huge. A real language has hundreds of thousands of words. So, each word becomes a list with hundreds of thousands of slots, where all of them are 0 except one. This wastes a lot of space.

Problem 2: Every word is equally far from every other word. In one-hot encoding, "king" and "queen" are just as different as "king" and "banana". The encoding does not capture any meaning. It does not know that "king" and "queen" are related.

So, here comes Word2Vec to the rescue.

Word2Vec gives each word a short list of numbers, for example 100 or 300 numbers, where the numbers actually carry meaning. Words with similar meaning get similar numbers. This is exactly what one-hot encoding could not do.

How does a computer represent a word?

Before we go deeper, we must understand what we are aiming for. We want every word to become a short list of numbers that captures its meaning.

Let's say we decide that each word will be a list of 4 numbers, just for the sake of understanding. Then a few words will look like below:

king   = [ 0.9,  0.7,  0.1,  0.8 ]
queen  = [ 0.9,  0.1,  0.1,  0.8 ]
man    = [ 0.5,  0.9,  0.2,  0.1 ]
woman  = [ 0.5,  0.2,  0.2,  0.1 ]
apple  = [ 0.1,  0.1,  0.9,  0.0 ]

Here, we can see that "king" and "queen" have very similar numbers, because they are related. "man" and "woman" also look similar to each other. But "apple" looks completely different from all of them, because it is a fruit and has nothing to do with the others.

We do not decide these numbers ourselves. Word2Vec learns them on its own from large amounts of text, and that too without being explicitly programmed.

This short list of numbers that represents a word is called a word embedding or a word vector. Both names mean the same thing.

So, our goal is clear. We want to learn a good word vector for every word. Now, let's understand the key idea that makes this possible.

The core idea: a word is known by the company it keeps

Now, let's understand the core idea behind Word2Vec. As the linguist J. R. Firth said:

You shall know a word by the company it keeps.

In simple words, the meaning of a word comes from the other words that appear around it.

Let's say we read these sentences:

  • "The cat drank the milk."
  • "The dog drank the milk."

Here, both "cat" and "dog" appear in very similar surroundings. Both of them "drank the milk". Because they keep similar company, we can guess that "cat" and "dog" must be similar kinds of things.

Now consider another example. The words "coffee" and "tea" often appear near words like "drink", "hot", "cup", and "morning". Because they share so much company, Word2Vec learns that "coffee" and "tea" are similar.

So, if two words appear in similar contexts, they often have similar meanings. Word2Vec uses exactly this rule. It looks at millions of sentences and learns which words tend to appear together. From this, it figures out which words are similar.

We can picture the idea of a context window like below:

Sentence:       The quick brown fox jumps over the dog

Left context:   quick, brown
Target word:    fox
Right context:  jumps, over

Here, we can see that the target word is "fox". The words around it, like "quick", "brown", "jumps", and "over", are called the context. The group of words we look at around the target is called the context window. In this picture, the window covers two words on the left and two words on the right of the target. This is how Word2Vec learns meaning, by studying the company each word keeps.

Planning your move into AI?

No matter which tech domain you work in today, with your effort, you can transition to these roles:

  • AI Engineer
  • Forward Deployed Engineer
  • AI Agent Engineer
  • Harness Engineer
  • Voice AI Engineer
  • AI Architect
  • LLM Engineer
  • LLM Inference Engineer
  • Gen AI Engineer
  • MLOps Engineer
  • ML Engineer
  • Deep Learning Engineer

Our AI and Machine Learning Program at Outcome School takes you there.

What is a word vector?

Now, let's understand the word vector in more detail.

A word vector is a list of numbers that represents a word as a point in space.

Let's keep it very simple. Suppose each word has only 2 numbers. Then we can draw every word as a point on a flat sheet of paper. The first number is the position from left to right, and the second number is the position from bottom to top.

Let's say we plot a few words like below:

        ^
        |                  queen *      * king
        |
        |
        |        woman *      * man
        |
        |
        |   apple *   * banana
        |
        +-------------------------------------->

Here, we can see that the related words sit close together. "king" and "queen" are near each other in the top area. "man" and "woman" are near each other in the middle. "apple" and "banana", both fruits, sit together at the bottom.

So, a word vector turns each word into a point in space. Words with similar meaning end up close together, and words with different meaning end up far apart.

In real Word2Vec, we do not use 2 numbers. We use many more, often 100 or 300 numbers per word. We cannot draw 300 numbers on paper, but the idea stays exactly the same. Similar words sit close together in that space.

This closeness is what lets a computer understand that "king" and "queen" are related. We have a detailed blog on Cosine Similarity that explains how we measure how close two vectors are.

The two architectures: CBOW and Skip-gram

Now, let's learn how Word2Vec actually learns these vectors. Word2Vec has two ways of doing it, and we call them two architectures. An architecture is the structure of the small network we use for learning.

The two architectures are CBOW and Skip-gram. Let's understand both.

CBOW stands for Continuous Bag of Words. In CBOW, we take the context words around a target word, and we try to predict the target word in the middle.

CBOW looks at the neighbors and guesses the missing word. For example, given "The ___ drank the milk", CBOW tries to predict that the missing word is "cat".

Skip-gram does the exact opposite. In Skip-gram, we take one target word, and we try to predict the context words around it.

Skip-gram looks at one word and guesses its neighbors. For example, given the word "cat", Skip-gram tries to predict that words like "drank" and "milk" appear around it.

We can picture the difference between the two like below:

CBOW (predict the middle word)        Skip-gram (predict the neighbors)
-------------------------------       ---------------------------------

   the   ---\                                 /---> the
   quick ----\                               /----> quick
              ---> [ FOX ]              [ FOX ] ----> jumps
   jumps ----/                               \----> over
   over  ---/                                 \---> ...

  context words -> target word         target word -> context words

Here, we can see the difference. CBOW takes many context words and predicts the one target word in the middle. Skip-gram takes the one target word and predicts the many context words around it.

Both architectures learn good word vectors. CBOW is faster and works well for frequent words. Skip-gram is slower but works better for rare words and is often the more popular choice. We pick one based on our use case.

Now, let's understand one of them step by step. We will use Skip-gram, because it makes the idea very clear.

A step-by-step walk-through of Skip-gram

Now, let's take a small example to make Skip-gram concrete.

Suppose we have this single sentence:

"The cat drank the milk"

Let's say our target word is "drank". We will use a context window of size 1, which means we look at one word on the left and one word on the right of the target.

Step 1: We pick the target word and find its context words.

The   cat   drank   the   milk
      left  TARGET  right

Here, the target word is "drank". The word on its left is "cat" and the word on its right is "the". So, our context words are "cat" and "the".

So, from this one position, we create training pairs like below:

( drank, cat )
( drank, the )

Here, we can see that each pair says: "when the target word is drank, a context word is cat", and "when the target word is drank, a context word is the".

Step 2: We slide the window forward and repeat. Now the target becomes "the", and we collect its neighbors. We keep doing this for every word in every sentence, across millions of sentences. In the end, we get a huge list of these word pairs.

Step 3: We feed these pairs into a small network. The network takes the target word as input and tries to predict its context words as output.

So, the whole flow of Skip-gram is as below:

Target word: "drank"
        ↓
Small network (learns the vectors)
        ↓
Predicted context words: "cat", "the"

Here, we can see that we give the network a word, and it learns to predict the words that usually surround it. While doing this prediction task again and again, the network slowly adjusts the numbers inside the word vectors.

We do not actually care about the prediction itself. What we really want are the word vectors that the network learns along the way.

This is how Skip-gram sets up the learning.

A quick note for you

No matter which tech domain you work in, get familiar with these topics:

  • LLM
  • RAG
  • MCP
  • Agent
  • Fine-tuning
  • Quantization

We put it all together in one video:

AI Engineering Explained: LLM, RAG, MCP, Agent, Fine-Tuning, and Quantization

No need to stop reading - bookmark it and watch later when you get time. Future you will thank you.

Now, let's get back to the topic.

How Word2Vec learns the vectors

Now, let's understand how the actual numbers inside the vectors get learned. The process is called training, and it works step by step.

Step 1: In the very beginning, every word gets a vector full of random numbers. So at the start, the vectors are meaningless. "king" and "queen" are not close yet, because everything is random.

Step 2: We take a training pair, for example ("drank", "cat"). We feed the target word "drank" into the network. The network uses the current vector of "drank" to predict which words appear around it.

Step 3: Since the vectors are still random, the first prediction is mostly wrong. We measure how wrong the prediction is. This measure of wrongness is called the loss, also called the error. A big loss means the network is very wrong.

Step 4: Now comes the important part. The network uses a method called backpropagation together with gradient descent. The network looks at its error and nudges the numbers inside the word vectors a tiny bit, in the direction that makes the prediction better next time.

Step 5: We repeat Steps 2 to 4 millions of times, for all the word pairs. With each round, the loss gets a little smaller, and the vectors get a little better. Slowly, the random vectors turn into meaningful vectors, where similar words sit close together.

We can picture this learning loop like below:

Pick a word pair          <------+
        ↓                        |
Predict the context words        |
        ↓                        |
Measure the loss                 |
        ↓                        |
Nudge the vectors        --------+

Here, we can see that the network repeats this loop millions of times. Each time, the word vectors improve a little. After enough training, words that keep similar company end up with similar vectors. This is how Word2Vec learns the meaning of words on its own.

Note: Real Word2Vec uses a few speed tricks, such as negative sampling, to make this training fast on huge amounts of text. These tricks help the network train quickly without checking every single word every time.

If we want to go deep into Backpropagation, Gradient Descent, and Loss Functions, and even build a Neural Network from scratch, we cover all of it in our AI and Machine Learning Program at Outcome School.

Word math (king - man + woman = queen)

Now, let's see the most famous result of Word2Vec. After training, the word vectors capture meaning so well that we can do actual math with words.

The most famous example is below:

king - man + woman = queen

Let's understand what this means in plain words. We take the vector of "king", we subtract the vector of "man", and then we add the vector of "woman". The result lands very close to the vector of "queen".

Why does this happen? Because Word2Vec learned that the difference between "king" and "man" is roughly the idea of "royalty". When we remove "man" from "king" and add "woman" instead, we get "the royal version of woman", which is "queen".

We can picture this like below:

        ^
        |          king *--------------* queen
        |              |               |
        |       (same direction = royalty difference)
        |              |               |
        |          man *--------------* woman
        |
        +--------------------------------------->

Here, we can see that the arrow from "man" to "king" points in the same direction and length as the arrow from "woman" to "queen". This is why the word math works. The relationship between words became a direction in space.

Here are a few more examples that Word2Vec captures:

  • "Paris" is to "France" as "Tokyo" is to "Japan", because the capital-to-country relationship becomes a direction.
  • "walking" is to "walked" as "swimming" is to "swam", because the present-to-past relationship becomes a direction.

So, Word2Vec did not just store words as numbers. It captured the relationships between words as directions in space.

Stay updated: Subscribe to our newsletter to get our latest AI and Machine Learning blogs straight to your inbox.

A simple code example

Now, let's see how to use Word2Vec in code. We will use Python with a library called Gensim. The code is as below:

from gensim.models import Word2Vec

# Our training data: a list of sentences, each split into words
sentences = [
    ["the", "cat", "drank", "the", "milk"],
    ["the", "dog", "drank", "the", "milk"],
    ["the", "king", "ruled", "the", "land"],
    ["the", "queen", "ruled", "the", "land"]
]

# Train the Word2Vec model
model = Word2Vec(sentences, vector_size=100, window=2, min_count=1, sg=1)

# Get the vector for the word "king"
king_vector = model.wv["king"]

# Find the words most similar to "king"
similar_words = model.wv.most_similar("king")

Here, we have trained a small Word2Vec model.

  • sentences is our training data. It is a list of sentences, where each sentence is split into a list of words.
  • Word2Vec(...) trains the model. Here, vector_size=100 means each word will become a list of 100 numbers. window=2 means the context window looks at 2 words on each side. min_count=1 keeps every word, even if it appears only once, which we need for our tiny data. sg=1 means we use the Skip-gram architecture. If we set sg=0, it would use CBOW instead.
  • model.wv["king"] gives us the learned vector of 100 numbers for the word "king".
  • model.wv.most_similar("king") finds the words whose vectors are closest to "king".

The library handles all the training, backpropagation, and gradient descent behind the scenes. We just provide the sentences and let it learn.

Note: With only four sentences, the vectors will not be meaningful. In practice, we train on millions of sentences.

Limitations of Word2Vec

Word2Vec was a huge step forward, but it is not perfect. Now, let's understand its main limitations.

One vector per word. Word2Vec gives each word exactly one vector. But many words have more than one meaning. Consider the word "bank". It can mean a river bank or a money bank. Word2Vec mixes both meanings into a single vector, so it cannot tell them apart.

It ignores the sentence around the word. The vector for "bank" is always the same, no matter the sentence. A word's meaning often depends on its full sentence, but plain Word2Vec does not look at the sentence at prediction time.

It cannot handle new words. If a word was not in the training data, Word2Vec has no vector for it at all. It simply does not know that word.

So, here come newer methods to the rescue. Modern systems use contextual embeddings, where the vector of a word changes based on the full sentence around it. These come from models built on the Transformer architecture, which is also used in today's LLMs (Large Language Models). In these models, the word "bank" gets a different vector in "river bank" than in "money bank", because the model reads the whole sentence first.

Note: Even today, Word2Vec is still used, because it is simple, fast, and works very well for many tasks. The newer methods build on the same core idea that Word2Vec introduced, which is representing words as meaningful vectors.

To learn Embeddings, Transformer Architecture, and Large Language Models (LLMs) in depth, check out our AI and Machine Learning Program at Outcome School.

Where Word2Vec is used

Now, let's see where Word2Vec is used in the real world.

  • Search engines: When we search for "cheap phone", a search engine can also find pages about an "affordable mobile", because the word vectors of these words are close.
  • Recommendations: When a shopping app suggests similar products, it can use word vectors to understand which items are related.
  • Spam detection: Word vectors help a system understand the meaning of an email, so it can better catch spam.
  • Translation: Word vectors help map words from one language to another by matching their meanings.
  • Text grouping: Word2Vec helps group similar articles, reviews, or documents together based on their meaning.

Now we must have understood how Word2Vec works.

Frequently Asked Questions

Should we use CBOW or Skip-gram?

It depends on our use case. Both architectures learn good word vectors. CBOW is faster and works well for frequent words. Skip-gram is slower, but it works better for rare words, and it is often the more popular choice. In Gensim, we pick Skip-gram with sg=1 and CBOW with sg=0.

How many numbers are there in a Word2Vec word vector?

Usually 100 or 300 numbers. Word2Vec gives each word a short list of numbers, unlike one-hot encoding, which needs one slot for every word in the vocabulary. In Gensim, we set this size with the vector_size parameter, for example vector_size=100.

Can Word2Vec handle a word it has never seen?

No. If a word was not in the training data, Word2Vec has no vector for it at all. It simply does not know that word. This is one of the main limitations of Word2Vec, along with giving each word exactly one vector.

What is the difference between Word2Vec and contextual embeddings?

Word2Vec gives each word one fixed vector, no matter the sentence. Contextual embeddings change the vector of a word based on the full sentence around it. So, the word "bank" gets a different vector in "river bank" than in "money bank", because the model reads the whole sentence first.

Is Word2Vec still used today?

Yes. Word2Vec is still used, because it is simple, fast, and works very well for many tasks. Even the newer methods build on the same core idea that Word2Vec introduced, which is representing words as meaningful vectors.

That's it for now.

Thanks

Amit Shekhar
Founder @ Outcome School

You can connect with me on:

Follow Outcome School on:

Read all of our high-quality blogs here.