Skip to content
E
Educatum

Word Embeddings

Curated by Educatum AI teamLast updated:
NLP
Direct Answer

Word embeddings are dense, low-dimensional vector representations of words learned from text corpora so that semantically and syntactically similar words lie close together in vector space. Grounded in the distributional hypothesis, methods like Word2Vec, GloVe, and FastText replace sparse, orthogonal one-hot vectors with continuous representations that support similarity search and analogical reasoning. Unlike static embeddings that assign one fixed vector per word, modern Transformers produce contextualized embeddings that vary with surrounding words.

Study Card: Word Embeddings

Direct Answer

Word embeddings map discrete words from a vocabulary VV into continuous, low-dimensional vectors in Rd\mathbb{R}^d (typically d≈50–1024≪∣V∣d \approx 50\text{--}1024 \ll |V|). Grounded in the distributional hypothesis (“words that appear in similar contexts tend to have similar meanings”), embeddings place related words nearby in geometric space—measured via cosine similarity or inner product.

Compared with sparse one-hot encoding (dimension ∣V∣|V|, where every pair of distinct words is orthogonal with dot product 00), dense embeddings drastically lower dimensionality, share statistical strength across related words, and capture syntactic and semantic relationships. Classic static methods include Word2Vec (predicting local context via CBOW or Skip-gram), GloVe (factorizing global log co-occurrence counts), and FastText (summing character nn-gram embeddings to handle rare and out-of-vocabulary words). Modern Transformer models (BERT, GPT) extend this further via contextualized embeddings, where a word’s representation adapts dynamically to sentence context.

Key Terms

  • Distributional Hypothesis: Linguistic principle that meaning can be inferred from co-occurrence statistics across large corpora.
  • One-Hot Encoding: Sparse ∣V∣|V|-dimensional indicator vector with zero geometric similarity between distinct words.
  • Word2Vec (CBOW / Skip-gram): Predicts a target word from surrounding context words (CBOW) or context words from a target word (Skip-gram), often trained with negative sampling.
  • GloVe: Learns embeddings so dot products approximate log pairwise word co-occurrence probabilities across the full corpus.
  • Static vs. Contextualized Embeddings: Static embeddings assign one vector per vocabulary entry (struggling with polysemy like "river bank" vs. "bank account"), whereas contextualized embeddings compute context-dependent token vectors.

Example

In a trained embedding space, "king" might map near [0.2, 0.5, -0.1, 0.7] and "queen" near [0.3, 0.6, -0.2, 0.8], sharing high cosine similarity, whereas "table" points in an unrelated direction. Linear vector offsets can encode semantic relations such as v⃗king−v⃗man+v⃗woman≈v⃗queen\vec{v}_{\text{king}} - \vec{v}_{\text{man}} + \vec{v}_{\text{woman}} \approx \vec{v}_{\text{queen}}, and downstream classifiers benefit because knowing "excellent" is positive transfers immediately to neighboring words like "superb".

Code Implementation

import numpy as np
from gensim.models import Word2Vec

# Small toy corpus with shared contexts
sentences = [
    ["cat", "sat", "on", "the", "warm", "mat"],
    ["dog", "sat", "on", "the", "soft", "rug"],
    ["cat", "chased", "the", "small", "mouse"],
    ["dog", "chased", "the", "red", "ball"],
    ["cat", "played", "with", "yarn"],
    ["dog", "played", "with", "stick"],
]

# Train deterministic Skip-gram / CBOW Word2Vec model (workers=1 with seed)
model = Word2Vec(
    sentences,
    vector_size=50,
    window=2,
    min_count=1,
    sg=1,
    epochs=200,
    workers=1,
    seed=42,
)

cat_vec = model.wv["cat"]
dog_vec = model.wv["dog"]
cosine_sim = np.dot(cat_vec, dog_vec) / (np.linalg.norm(cat_vec) * np.linalg.norm(dog_vec))

print(f"Embedding shape for 'cat': {cat_vec.shape}")
print(f"Cosine similarity('cat', 'dog'): {cosine_sim:.3f}")
print("\nMost similar words to 'cat':")
for word, score in model.wv.most_similar("cat", topn=3):
    print(f"  {word}: {score:.3f}")
  • Cosine Similarity: Normalized dot product u⋅v∥u∥∥v∥\frac{\mathbf{u} \cdot \mathbf{v}}{\|\mathbf{u}\|\|\mathbf{v}\|} measuring directional alignment independent of vector length.
  • Subword Tokenization & FastText: Composes words from character nn-grams (or BPE subwords in LLMs) to eliminate out-of-vocabulary failures and model morphology.
  • Polysemy & Contextualized Embeddings (BERT / GPT): Transformer hidden states resolve ambiguous words dynamically based on surrounding tokens.
  • Sentence & Document Embeddings: Pooling or contrastive training (e.g., Sentence-BERT, bi-encoders) extends word vectors to full passages for semantic search and RAG.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.