Word Embeddings Explained: First GloVe Example in Python
In this article
- Background: Why Dense Vectors?
- How GloVe Works
- First GloVe Example in Python
- Convert GloVe format to Word2Vec format (only once)
- Load the vectors
- Get the vector for 'coffee'
- Find most similar words
- Solve analogy: king - man + woman = ?
- How to Choose the Right GloVe Model
- Common Problems and How to Fix Them
- GloVe vs. Word2Vec vs. fastText
- Costs and Considerations
- Safety and Ethical Use
- Frequently Asked Questions
Word embeddings are a way to represent words as dense vectors of numbers so that computers can understand semantic relationships, and GloVe (Global Vectors for Word Representation) is a popular method for creating them. This article explains how GloVe works and walks through a complete first Python example using pre-trained vectors.
Background: Why Dense Vectors?
Early natural language processing (NLP) used one-hot encoding, where each word is a vector with a single 1 and all other entries 0. That approach is simple but has two major problems: the vectors are huge (the size of the vocabulary), and they carry no semantic information—"cat" and "dog" are as different as "cat" and "quantum".
Word embeddings solve this by mapping each word to a fixed-size vector (say, 100 or 300 dimensions) where words with similar meanings end up close together. For example, the vector for "king" minus "man" plus "woman" is famously close to the vector for "queen". These vectors are learned from large text corpora, and they capture both syntactic and semantic patterns.
GloVe, introduced by Jeffrey Pennington, Richard Socher, and Christopher Manning in 2014, is one of the most widely used embedding methods, alongside Word2Vec and fastText. Its key idea is to use global word-word co-occurrence statistics from the entire corpus, rather than just local context windows.
How GloVe Works
GloVe builds a co-occurrence matrix X, where Xij counts how often word j appears in the context of word i across the whole corpus. The context is typically defined as a window of a few words around the target word.
The training objective is to learn word vectors wi and context vectors w̃j such that:
wi · w̃j + bi + b̃j ≈ log(Xij)
Here, bi and b̃j are bias terms. The dot product of the two vectors approximates the logarithm of their co-occurrence count. This is a weighted least-squares regression problem, where the loss function gives less weight to very rare and very frequent co-occurrences.
The result is that the vector space encodes ratios of co-occurrence probabilities. For instance, the ratio P(k|ice)/P(k|steam) is large for words like "solid" and small for "gas", which is how the model captures analogies.
First GloVe Example in Python
To use GloVe in Python, you typically download pre-trained vectors from the Stanford GloVe page (or use the gensim library). Here's a minimal example using gensim to load and explore vectors:
from gensim.scripts.glove2word2vec import glove2word2vec
from gensim.models import KeyedVectors
Convert GloVe format to Word2Vec format (only once)
glove2word2vec('glove.6B.100d.txt', 'glove.6B.100d.word2vec.txt')
Load the vectors
model = KeyedVectors.load_word2vec_format('glove.6B.100d.word2vec.txt', binary=False)
Get the vector for 'coffee'
vec = model['coffee']
print(vec[:5]) # first 5 dimensions
Find most similar words
print(model.most_similar('coffee', topn=5))
Solve analogy: king - man + woman = ?
result = model.most_similar(positive=['king', 'woman'], negative=['man'], topn=1)
print(result)This code loads 100-dimensional vectors trained on 6 billion tokens. The first line converts the file format because gensim expects Word2Vec's format. The output shows the vector values and the top similar words to "coffee", which typically include "tea", "caffeinated", and "espresso".
How to Choose the Right GloVe Model
Pre-trained GloVe vectors come in several sizes. The most common are:
- glove.6B: trained on 6 billion tokens, with 400,000 words, available in 50, 100, 200, and 300 dimensions.
- glove.42B.300d: trained on 42 billion tokens, 300 dimensions.
- glove.840B.300d: trained on 840 billion tokens, 300 dimensions.
For most projects, the 6B 100d or 300d versions are a good starting point. Higher dimensions capture more nuance but require more memory. The 840B version is the most comprehensive but also the largest file (over 2 GB).
If you are working with domain-specific text (e.g., biomedical or legal), you may want to train your own GloVe vectors on your corpus. The original implementation is available on the Stanford GloVe GitHub repository, and it requires compiling C code. For Python-only training, you can use libraries like torchtext or gensim (though gensim's GloVe implementation is not officially supported, it has a wrapper).
Common Problems and How to Fix Them
One frequent issue is memory: loading a large GloVe file can consume several gigabytes of RAM. To mitigate this, you can load only the words you need by using the limit parameter in gensim, or use a smaller dimension (50d instead of 300d).
Another problem is that pre-trained vectors may not contain out-of-vocabulary words. If you encounter a word not in the vocabulary, you have a few options:
- Use a fallback like a random vector (not recommended).
- Use subword information from fastText, which handles unknown words better.
- Train your own embeddings on your corpus.
Also, note that GloVe vectors are not case-sensitive in the 6B model; "Apple" and "apple" are treated as the same token. This can be an issue for named entities.
GloVe vs. Word2Vec vs. fastText
GloVe and Word2Vec are both popular, but they differ in training approach. Word2Vec (specifically the skip-gram model) predicts the context words given a target word, using a local window. GloVe uses global co-occurrence counts, which some argue gives it a better balance of local and global statistics.
fastText extends Word2Vec by treating each word as a bag of character n-grams. This allows it to generate vectors for unseen words by summing the n-gram vectors. fastText is therefore better for morphologically rich languages or when you have many rare words.
In practice, all three perform similarly on many tasks, and the choice often comes down to availability of pre-trained models and specific needs. For analogy tasks, GloVe and Word2Vec both work well; for handling rare words, fastText is superior.
Costs and Considerations
Using pre-trained GloVe vectors is free and requires no training time. The only cost is disk space and memory. For example, the 6B 300d file is about 1.2 GB on disk, and loading it into memory takes roughly 1.5 GB of RAM.
If you train your own GloVe model, you need a large corpus and considerable CPU/GPU time. Training on a few billion tokens can take hours or days, depending on hardware. However, for most applications, pre-trained vectors are sufficient and far more practical.
One more consideration: the vocabulary size. The 6B model has 400,000 words, which covers most common English words but not every technical term or proper noun. For specialized domains, you might need to supplement with your own embeddings.
Safety and Ethical Use
Word embeddings can encode societal biases present in the training text. For example, gender stereotypes may appear in the vector space (e.g., "nurse" closer to "woman" than to "man"). When using embeddings in applications like hiring or content moderation, be aware of these biases and consider debiasing techniques, such as the ones proposed by Bolukbasi et al. (2016).
Also, be cautious when using embeddings for sensitive predictions. The vectors are just numbers; they don't contain inherently harmful information, but the downstream models can amplify biases. Always evaluate your system for fairness.
Frequently Asked Questions
What is the difference between GloVe and Word2Vec?
GloVe uses global co-occurrence statistics to train vectors, while Word2Vec uses local context windows (either predicting context from word or word from context). GloVe tends to be faster to train on smaller corpora and often performs better on analogy tasks, but both produce similar quality embeddings.
Can I use GloVe vectors for non-English languages?
Yes, pre-trained GloVe vectors are available for many languages, including French, German, Spanish, and Chinese, from the Stanford GloVe page. For other languages, you can train your own using the original C code or Python implementations.
How do I visualize word embeddings?
Since embeddings are high-dimensional, you need to reduce them to 2D or 3D using techniques like PCA, t-SNE, or UMAP. In Python, you can use scikit-learn's PCA or the tsnecuda library to project the vectors and then plot them with matplotlib.
What is the best dimension size for embeddings?
There is no single best size; it depends on your task and data size. For small datasets, 50-100 dimensions are often enough. For large corpora, 300 dimensions are common. Higher dimensions capture more fine-grained relationships but require more data to train effectively and more memory to use.
How do I handle out-of-vocabulary words?
If a word is not in the pre-trained vocabulary, you can either use a random vector (with caution), use fastText which can generate vectors for unseen words, or train your own embeddings that include your domain vocabulary. For many applications, the simplest is to map unknown words to a special