1. Home
  2. Explore
  3. Computer Science
  4. Word Embedding

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Word Embedding

Word Embedding

From 1-of-N Encoding to Word Embedding

Representing words as vectors is a fundamental challenge in natural language processing. The simplest approach is 1-of-N encoding, where each word corresponds to a vector the size of the vocabulary. For a vocabulary of 100,000 words, each word gets a 100,000-dimensional vector with a single 1 at its index and 0s everywhere else.

Problem with 1-of-N encoding: These vectors carry no semantic information. Every word vector is different from every other, making it impossible to infer relationships. For instance, the vectors for "cat" and "dog" — both animals — are as different as "cat" and "apple." The model cannot learn that some words share properties.

Word Class

One improvement is Word Class, which clusters words with similar properties into groups:

  • dog, cat, bird → Class 1 (animals)

  • ran, jumped, walk → Class 2 (actions)

  • flower, tree, apple → Class 3 (plants)

Limitation of Word Clustering: Clustering alone loses information about relationships between classes. Animals (Class 1) can perform actions (Class 2), but plants (Class 3) cannot. This hierarchical relationship between classes cannot be captured with simple clustering — it treats each class as a separate, unrelated category.

What is Word Embedding?

Word Embedding projects each word into a high-dimensional space that is much lower than 1-of-N encoding. Instead of 100,000 dimensions, word embeddings typically use 50-100 dimensions. This is a dimensionality reduction process from the sparse 1-of-N encoding to a dense, lower-dimensional vector.

In this embedding space:

  • Words with similar semantics are close together

  • Each dimension may carry a specific meaning (e.g., living vs. non-living, animate vs. inanimate, action-related vs. static)

  • The vector captures latent semantic features that distinguish words in meaningful ways

Unsupervised Learning for Word Embedding

Word embedding is an unsupervised learning problem:

  • Input: A word (1-of-N encoding)

  • Output: The word's embedding vector

  • Training data: Large amounts of text (only input available, no target output)

The machine learns word meanings by reading massive amounts of text. The core principle: the meaning of a word is determined by its context. If words appear in similar contexts, they likely have related meanings.

Why Auto-encoder won't work: Using 1-of-N encoding as input, each word is independent. An auto-encoder trained on such vectors cannot learn informative embeddings because there is no relationship among inputs to reconstruct — it would simply learn the identity mapping.

Count-based Methods

Count-based methods rely on word co-occurrence statistics. If two words wiw_iwi​ and wjw_jwj​ frequently appear together in documents, their word vectors V(wi)V(w_i)V(wi​) and V(wj)V(w_j)V(wj​) should be close.

GloVe (Global Vectors for Word Representation)

The principle: Given vectors V(wi)V(w_i)V(wi​) for wiw_iwi​ and V(wj)V(w_j)V(wj​) for wjw_jwj​, compute their inner product V(wi)⋅V(wj)V(w_i) \cdot V(w_j)V(wi​)⋅V(wj​). Let NijN_{ij}Nij​ be the number of times wiw_iwi​ and wjw_jwj​ co-occur in documents. The goal is to make the inner product approximate the co-occurrence count:

V(wi)⋅V(wj)≈NijV(w_i) \cdot V(w_j) \approx N_{ij}V(wi​)⋅V(wj​)≈Nij​

This is essentially matrix factorization, similar to Latent Semantic Analysis (LSA). The count-based approach finds vectors such that the dot product between word vectors reflects how often those words co-occur.

Prediction-based Methods

Prediction-based methods learn a neural network that predicts a word given its context. The hidden layer's output serves as the word embedding.

Basic Model: Predict Next Word

The simplest prediction model: given the previous word wi−1w_{i-1}wi−1​, predict the next word wiw_iwi​.

  • Input: 1-of-N encoding of wi−1w_{i-1}wi−1​ (vocabulary size dimensions)

  • Output: Probability distribution over all words for wiw_iwi​ (vocabulary size dimensions)

  • Architecture: Multi-layer perceptron (deep neural network)

The embedding is taken from the first hidden layer — the vector ZZZ that represents the input word after the first transformation. This ZZZ serves as the word's embedding.

Why this works: During training, if "Tsai Ing-wen" and "Ma Ying-jeou" both precede "inauguration", the network must produce similar outputs for both inputs. To achieve this, the hidden layer learns to project these different words to similar positions in the embedding space — because if the embeddings were different, the output probabilities for "inauguration" would differ.

Extending to Multiple Context Words

Using a single previous word is weak — too many possible next words. The model extends naturally to multiple context words:

Given wi−2w_{i-2}wi−2​ and wi−1w_{i-1}wi−1​, predict wiw_iwi​. In practice, at least 10 context words are typically used for reasonable results.

Weight Tying

When using multiple context words as input, the weight matrices for each position must be tied together (shared). This means:

  • The weights connecting wi−2w_{i-2}wi−2​'s first dimension to hidden layer neurons must equal the weights connecting wi−1w_{i-1}wi−1​'s first dimension to those same neurons

  • Without weight tying, the same word at different positions would get different embeddings

Mathematically: Let Xi−2X_{i-2}Xi−2​ and Xi−1X_{i-1}Xi−1​ be the 1-of-N encodings. The hidden layer input ZZZ is:

Z=Xi−2⋅W1+Xi−1⋅W2Z = X_{i-2} \cdot W_1 + X_{i-1} \cdot W_2Z=Xi−2​⋅W1​+Xi−1​⋅W2​

Weight tying forces W1=W2=WW_1 = W_2 = WW1​=W2​=W, so:

Z=(Xi−2+Xi−1)⋅WZ = (X_{i-2} + X_{i-1}) \cdot WZ=(Xi−2​+Xi−1​)⋅W

This also reduces parameters — vitally important given the large vocabulary size (e.g., 100,000 dimensions).

Training with Tied Weights

To keep weights identical during training:

  1. Initialize tied weights to the same values

  2. Compute gradients for each weight

  3. Update each weight using the sum of all tied weights' gradients

    • wiw_iwi​ update uses gradient of wiw_iwi​ + gradient of wjw_jwj​

    • wjw_jwj​ update uses gradient of wjw_jwj​ + gradient of wiw_iwi​

This ensures tied weights remain equal throughout training. This technique is also used in training CNN architectures.

Training Procedure

The network is trained unsupervised on large text corpora:

For a sentence "The tide receded, knew who didn't wear pants":

  • Input: "tide" + "receded" → Target output: "knew"

  • Input: "receded" + "knew" → Target output: "who"

  • Input: "knew" + "who" → Target output: "didn't"

Each training pair minimizes the cross-entropy between the network's output and the target word's 1-of-N encoding.

Variations of Prediction-based Models

CBOW (Continuous Bag of Words)

CBOW predicts the middle word from its surrounding context:

  • Input: wi−1w_{i-1}wi−1​ and wi+1w_{i+1}wi+1​

  • Output: wiw_iwi​

The model takes the context words (both before and after) and tries to predict the word in the center.

Skip-gram

Skip-gram does the reverse — predicts the context from the center word:

  • Input: wiw_iwi​

  • Output: wi−1w_{i-1}wi−1​ and wi+1w_{i+1}wi+1​

Given a word, the model tries to predict which words appear around it. Skip-gram tends to work better with smaller datasets and captures more semantic relationships.

Why Word Vector Models Are Not Deep

The standard word vector network has only one hidden layer — it is not deep. The reasons (from Tomas Mikolov, creator of word2vec):

  1. Historical context: Previous attempts used deep networks but were computationally impractical. Mikolov's contribution was showing that a shallow network with good engineering could achieve superior results without the computational overhead of deep architectures.

  2. Computational efficiency: Removing depth dramatically reduces computation, enabling training on massive datasets. The shallow architecture allows processing billions of words efficiently.

  3. Engineering tricks: The toolkit's success comes from numerous implementation optimizations and heuristics that are difficult to replicate independently.

Properties of Word Embeddings

Word embeddings exhibit analogical reasoning capabilities. The vector space captures relational patterns:

Example: Capital-Country Relationship

V(Rome)−V(Italy)+V(Germany)≈V(Berlin)V(\text{Rome}) - V(\text{Italy}) + V(\text{Germany}) \approx V(\text{Berlin})V(Rome)−V(Italy)+V(Germany)≈V(Berlin)

Similarly:

  • V(Berlin)−V(Germany)≈V(Rome)−V(Italy)V(\text{Berlin}) - V(\text{Germany}) \approx V(\text{Rome}) - V(\text{Italy})V(Berlin)−V(Germany)≈V(Rome)−V(Italy)

  • The vector differences are parallel, indicating the same relationship

Example: Verb Tenses

V(bigger)−V(big)≈V(hotter)−V(hot)V(\text{bigger}) - V(\text{big}) \approx V(\text{hotter}) - V(\text{hot})V(bigger)−V(big)≈V(hotter)−V(hot)

Example: Gender Relationships

V(King)−V(Queen)≈V(uncle)−V(aunt)V(\text{King}) - V(\text{Queen}) \approx V(\text{uncle}) - V(\text{aunt})V(King)−V(Queen)≈V(uncle)−V(aunt)

Subset Relationships

When subtracting word vectors for a subcategory from its parent category, the resulting vector falls in a consistent region:

  • dolphin - white-sided dolphin

  • actor - protagonist

  • worker - salesman

  • sheep - ram

These vector differences cluster together, indicating that the embedding space captures hierarchical and subset relationships.

Answering Analogy Questions

To answer "Rome is to Italy as Berlin is to ___":

  1. Compute: V(Berlin)−V(Rome)+V(Italy)V(\text{Berlin}) - V(\text{Rome}) + V(\text{Italy})V(Berlin)−V(Rome)+V(Italy)

  2. Find the word whose vector is closest to this result

  3. Answer: Germany

Cross-lingual Word Embedding

Word embeddings trained on different languages independently do not align — there is no relationship between Chinese and English embedding dimensions. Without bilingual texts, the model cannot learn cross-lingual relationships.

Solution: Given a small set of known translation pairs (e.g., "enlarge" ↔ "加大", "fall" ↔ "下跌"):

  1. Train separate embedding spaces for each language

  2. Learn a projection that maps corresponding words to the same point

  3. Apply this projection to new words

  4. Unknown translations ("reduce" ↔ "降低") automatically map to nearby positions

This enables automatic translation-like behavior without parallel corpora — just a small bilingual dictionary.

Image Embedding and Zero-shot Learning

Word embeddings can connect vision and language. The process:

  1. Pre-train word vectors (e.g., for dog, horse, car, cat)

  2. Learn a model that maps images to vectors in the same space

  3. Known images (labeled as dog, horse, car) project near their corresponding word vectors

  4. New images of unseen categories (e.g., cat not in training) project near the correct word vector — the machine can name what it has never seen

Advantage over traditional classification: Normal classifiers (like in homework 3) can only classify into pre-defined categories. If a new object appears outside the training classes, the classifier is helpless. With embedding-based approaches, the machine:

  • Reads text to understand word meanings and relationships

  • Maps images to the semantic space

  • Can identify unseen objects by proximity to word vectors

This enables zero-shot learning — recognizing categories never seen during training.

Document Embedding

Beyond individual words, entire documents can be represented as vectors. The simplest approach uses bag-of-words with Auto-encoders, but this loses crucial word order information.

Example of word order importance:

  • "White blood cells destroying an infection" → positive meaning

  • "An infection destroying white blood cells" → negative meaning

Both sentences have identical bag-of-words representations (same words, different order) but opposite meanings. Word order carries essential semantic information that bag-of-words models discard.

Approaches to Document Embedding

Unsupervised methods:

  • Various neural architectures that consider word order and context

  • Learn document vectors from raw text without labels

Supervised methods:

  • Require additional labels for each document (not the embedding itself, but other task-specific labels)

  • Learn document representations that are useful for specific tasks

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent