From One-Hot to Contextual: A Practical Guide to Text Embeddings

Text embeddings are the foundation of modern NLP. They transform human language into numerical vectors that machines can process. Understanding this evolution — from sparse representations to dense contextual vectors — is essential for any practitioner building production systems.

The Evolution: Three Generations of Embeddings

Bag-of-Words (BoW) represents the simplest approach: count word frequencies, ignore order. A 50,000-word vocabulary yields a 50,000-dimensional sparse vector. Implement it in five lines with CountVectorizer, but watch memory blow up as documents grow. BoW treats "good" and "great" as independent features — missing semantic relationships entirely.

TF-IDF improves on BoW by weighting terms based on their importance. Words appearing in many documents get penalized; rare but informative words get boosted. This simple change dramatically improves retrieval performance. Implement it with TfidfVectorizer and you'll see better results on most classification tasks.

Word2Vec represents a paradigm shift. Using the Skip-gram architecture, it learns dense 300-dimensional vectors where semantically similar words cluster together. "King - man + woman ≈ queen" became the iconic demonstration. The key insight: words appearing in similar contexts have similar meanings.

Contextual Embeddings finally arrived with BERT in 2018. Unlike Word2Vec's static vectors, BERT generates different representations for the same word depending on its context. "Bank" in "river bank" differs from "bank" in "financial bank" — a distinction static embeddings can never capture.

Hands-On Implementation

Loading pretrained embeddings is straightforward. For GloVe, download the 300D vectors and build a simple lookup dictionary. For FastText, use fasttext.load_model() to get subword information that handles out-of-vocabulary words gracefully.

import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from gensim.models import KeyedVectors

# Load GloVe
glove = KeyedVectors.load_word2vec_format('glove.6B.300d.txt', binary=False, no_header=True)

# Load FastText for OOV handling
import fasttext
ft_model = fasttext.load_model('cc.en.300.bin')

Building a sentiment classifier using embeddings is educational: average the word vectors in each document and train a logistic regression classifier on top. You'll see GloVe outperform TF-IDF on semantic tasks but struggle with domain-specific terms.

Visualizing Embedding Spaces

t-SNE projection reveals the structure: semantically related words cluster together, dimensions capture surprisingly interpretable features, and visualization immediately validates whether your embeddings learned meaningful relationships.

from sklearn.manifold import TSNE
import matplotlib.pyplot as plt

tsne = TSNE(n_components=2, random_state=42)
embeddings_2d = tsne.fit_transform(word_vectors)

The Research Gap

Static embeddings are solved. But the open-source vs. proprietary embedding debate remains unsettled. Commercial models like OpenAI's text-embedding-3-small and text-embedding-3-large consistently outperform open alternatives on MTEB benchmarks, but at significant cost. The trade-off isn't just accuracy — it's about data privacy, latency requirements, and fine-tuning capabilities.

When should you pay for proprietary embeddings versus hosting open models? Production experience suggests: use proprietary for customer-facing applications where accuracy directly impacts revenue, and open-source for internal tools where cost scales with query volume. But systematic guidance is lacking.

← Back to all articles