Concepts / Word Embedding Techniques

Word Embedding Techniques

Word2Vec is a trained neural network architecture that generates word embeddings by predicting the context of a word given the target word, or the reverse.

  • Programming

Why a Computer Needs Numbers for Words

A computer cannot read a word the way a person does. To use words in a calculation, we first have to turn each word into a numerical form. A common form is a vector: a list of numbers that stands for the word. Such vectors are called word embeddings. Several algorithms and frameworks have been built to produce them, and Word2Vec is one of the earlier and most widely known.

This article follows one question through: if a method only reads text, how can it end up placing related words near one another? Keep that question in mind, because the answer is built from a simple observation about where words appear, and that observation explains nearly every later choice in Word2Vec.

The Shared-Neighbour Idea

The central idea behind Word2Vec is simple to state: words that appear in similar contexts tend to have similar meanings. The context of a word is the set of words around it. If two different words keep showing up next to the same neighbours, the method treats that shared neighbourhood as evidence that the two words are related in meaning.

The method never needs a dictionary. It only needs running text and the patterns of which words travel together. A learner who sees a word in isolation has very little to go on, but a learner who sees the words that regularly appear beside it can start to infer what kind of word it is.

Worked example

Inferring a word from its surroundings

Suppose the only evidence is that the word appears in sentences like 'the ___ fell from the sky' and 'we walked through the ___ to school'. No definition of the word is given. What can be inferred?

  1. 1
    Look at the shared neighbours

    The word keeps appearing near words like 'fell', 'sky', and 'walked'. Those neighbours describe weather and outdoor settings.

  2. 2
    Compare with other words in the same neighbourhoods

    If another word such as 'snow' also keeps appearing next to the same neighbours, the method treats the two words as related in meaning.

  3. 3
    Conclude without a definition

    No definition of the word was consulted. The inference comes only from the surrounding words, which is exactly the kind of inference the principle licenses.

Result

The word is inferred to be a weather-related term, because of the neighbours it keeps, even though nothing defined it.

Sliding a Window Across a Sentence

Word2Vec does not study a whole document at once. It moves a window across the text. At each position, one word is the target and the words around it form its context. Each position therefore yields one training example. Follow the sentence 'the cat sat on the mat' with a window that reaches one word to each side of the target. The diagram below shows three of the steps.

catcontext: the, satsatcontext: cat, ononcontext: sat, thewindow moves one word rightwindow moves one word right
As the window moves one word at a time, each new target word is paired with the words beside it, and each step produces a new training example.

Notice what changes at each step. The target moves forward by one word, and the context shifts with it. The word 'sat' is a neighbour of 'cat' in one step and the target in the next. Across the whole sentence, every word gets a turn as the target, and every word gets a turn as a member of someone else's context. That repeated pattern of pairings is the raw material the network learns from.

What do you think happens?

With the same one-word window on each side of 'the cat sat on the mat', which words form the context when the target is 'on'?

  • cat and mat

  • sat and the

  • the and mat

  • cat and sat

Reveal answer
Answer:

sat and the

'on' is the fourth word. Its immediate neighbours are 'sat' on the left and 'the' on the right, so those two words form its context for this step.

Two Directions for the Same Bet

Word2Vec is a trained neural network architecture. Its job is to produce word embeddings by learning to predict context. Training can run in either of two directions. In the first, the network is given a target word and is trained to predict the words around it. In the second, the network is given the surrounding words and is trained to predict the target word. The phrase 'or vice versa' in the definition captures exactly this reversal.

target wordinputsurrounding wordsinputsurrounding wordsoutput to predicttarget wordoutput to predictpredict contextpredict target
The two setups use the same window of words. They differ in which side is supplied as input and which side the network must predict as output.

Take the target 'sat' from the sentence above. In the target-to-context direction, 'sat' goes in and the network must predict its neighbours, 'cat' and 'on'. In the context-to-target direction, 'cat' and 'on' go in and the network must predict 'sat'. The window of text is identical in both cases. Only the arrow of the task is reversed, and both directions rest on the same bet about context.

Because the training signal comes from predictions, the numbers that end up in each embedding are shaped by how well the network predicts. Words that keep sharing neighbours receive similar pressure during training, which is how the shared-neighbour idea gets written into the numbers.

Reading a Two-Dimensional Plot

An embedding is usually a list of many numbers, and a list of many numbers cannot be drawn directly. To look at the structure, the embeddings are projected into two dimensions for visualization. When this is done, terms with similar meanings tend to land close together on the plot, forming groups. Reading the plot is a way to check whether the learned representations place related words in related regions.

doganimal groupcatanimal groupcarvehicle grouptruckvehicle groupclose togetherclose together
Words that were close in the full embedding space tend to appear close together on the page. The animal words form one group and the vehicle words form another.

In the illustration, the two animal words sit together and the two vehicle words sit together. The grouping is the lesson. Closeness on the page is a rough guide to similarity. It is evidence of relatedness to be read carefully, not a statement of exact synonymy, and it is not a faithful map of the full space, because a flattened view inevitably loses some of the structure of the original.

The same logic applies to the rain and snow example. The reasoning that puts them near each other used only the surrounding words. No definition of rain or snow was consulted, and none was needed.

Misreadings of Embeddings and Plots

The plot is persuasive, which makes it easy to over-read. The table below lists common assumptions and the more careful reading that the source supports.

AssumptionWhy it is incorrectBetter reading
Words close on the plot are exact synonymsCloseness is evidence of relatedness from shared contexts, not exact synonymyClose terms are related in the way their contexts overlap
The plot is the embeddingA two-dimensional projection is a visualization of the embedding, not the embedding itselfTreat the plot as a summary that discards structure
Distances on the page are exact measurements of meaningFlattening loses part of the structure of the original high-dimensional spaceUse distances as a rough guide, not a precise ruler
The network stores a dictionary definition for each wordThe method never needs a dictionary or glossary; it learns from predictions about contextMeaning is inferred from patterns of neighbours in running text
Any two words that share a neighbour are interchangeableThe principle is a tendency, not a guarantee, and shared context does not prove identical meaningShared neighbours suggest relatedness that still needs checking

Common misreadings of what Word2Vec learns and what its plots show

Choosing How Many Dimensions

Each embedding is a list of values, and the number of values is called its dimensionality. The source describes embeddings whose dimensionality can range from one to thousands. The number is a design decision, and it carries a trade-off. Higher dimensionality may capture more nuanced relationships between words, but this comes at a cost in computational efficiency. Lower dimensionality is cheaper to work with, though it has less room to express subtle differences.

AspectLow dimensionalityHigh dimensionality
What it can captureCoarser differences between wordsMore nuanced relationships between words
Computational costCheaper to work withCosts more in computational efficiency
Room for subtle differencesLimitedMore room to express subtle differences

The trade-off in choosing the number of embedding dimensions

The projection to two dimensions is a separate matter. Whatever dimensionality the embeddings were trained with, a two-dimensional plot is only a view that makes groups easier to see. Choosing a dimensionality for training and choosing a two-dimensional view for inspection answer different questions.

Trace the Windows Yourself

EASY

Use the sentence 'we walked to school today' with a window that reaches one word to each side of the target. List every target word, its context, and the direction-to-target pairing for the target 'to' in both training directions.

Hints
  • Number the words first: we (1), walked (2), to (3), school (4), today (5).
  • The target 'to' is word 3, so its neighbours are word 2 and word 4.
  • In the target-to-context direction, 'to' is the input. In the context-to-target direction, the neighbours are the input and 'to' is the output.

Key Takeaways

  • Word2Vec rests on the principle that words appearing in similar contexts tend to have similar meanings, and the context of a word is the set of words around it.
  • A sliding window over text turns each position into a training example, with one word as the target and its neighbours as context.
  • Word2Vec can be trained in two directions: predicting context from a target word, or predicting the target word from its context.
  • A two-dimensional projection shows similar terms clustered together, but it is a visualization of the embedding, not the embedding itself, and closeness is evidence of relatedness rather than exact synonymy.
  • Embedding dimensionality trades nuance against computational cost, with higher values capturing more subtle relationships at greater expense.

Related concepts

More concepts starting with W