Sub topic 14
Training word2vec with gensim
Assume you know basic Python, NumPy arrays, tokenization, vectors, and the idea of gradient descent. This chapter uses gensim to train a small word2vec model, inspect its vectors, and query similar words.
Prepare the training data
word2vec expects a corpus as a sequence of sentences. Each sentence is a list of string tokens. The model learns from nearby words, so preserve useful word boundaries and apply consistent preprocessing.
The example corpus is intentionally small. It demonstrates the API, but its results are not reliable enough for real analysis.
from gensim.models import Word2Vec
sentences = [
["the", "cat", "sits", "on", "the", "mat"],
["the", "dog", "sits", "on", "the", "rug"],
["the", "cat", "chases", "the", "mouse"],
["the", "dog", "chases", "the", "ball"],
]
model = Word2Vec(
sentences=sentences,
vector_size=50,
window=2,
min_count=1,
sg=1,
negative=5,
epochs=50,
workers=1,
seed=1,
)
print(model.wv["cat"].shape)
print(model.wv.most_similar("cat", topn=3))vector_size sets the number of dimensions in each word vector. window=2 allows words up to two positions away to provide context. min_count=1 keeps every word in this tiny corpus. For a large corpus, a higher value removes rare words and reduces memory use.
The sg parameter selects the architecture. sg=1 uses skip-gram, which predicts context words from a center word. sg=0 uses continuous bag of words (CBOW), which predicts a center word from nearby context words. Skip-gram often helps rare words, while CBOW is usually faster.
negative=5 trains with five sampled incorrect context words for each observed pair. This avoids calculating a full probability distribution over the vocabulary. epochs controls how many passes the optimizer makes over the corpus.
Understand the result
The wv attribute is a keyed-vector store containing the learned word vectors. It supports lookup and similarity operations:
cat_vector = model.wv["cat"]
print(cat_vector[:5])
print(model.wv.similarity("cat", "dog"))The similarity value is cosine similarity. Values closer to 1 indicate vectors pointing in similar directions. Do not interpret a single result as a linguistic fact. Small corpora produce unstable vectors, and training is stochastic even when a seed is supplied.
Common errors
- Passing raw strings instead of lists of tokens makes characters behave like tokens.
- Using
min_counthigher than the frequency of your test word removes that word. - Comparing models trained on different corpora without checking vocabulary and preprocessing.
- Treating nearest neighbours as proof of meaning. They reflect the training data, including its omissions and biases.
Exercise
Change the example to use CBOW, vectors with 100 dimensions, and a context window of 3. Which parameters must change?
Show answer
Set vector_size=100, window=3, and sg=0. The other parameters can remain unchanged.