Sub topic 16
Training word2vec with gensim
This chapter shows how to train a word2vec model with gensim 4, how each major parameter changes the result, and which mistakes cause the most wasted runs. It assumes you know the skip-gram and CBOW objectives, negative sampling and subsampling from the earlier chapters. You should also be comfortable with Python iterators.
What gensim does when you call Word2Vec
The Word2Vec class runs two phases. First it scans the corpus once to build a vocabulary, counting words and dropping rare ones. Then it makes epochs passes over the corpus, sliding a window over each sentence and updating the vectors by stochastic gradient descent. Worker threads run the inner loop in optimized C code.
The input format is the most common source of trouble. The corpus must be an iterable of sentences, and each sentence must be a list of string tokens. Gensim does not tokenize for you.
A streaming corpus
Real corpora often do not fit in memory. Gensim iterates over the corpus twice (once for the vocabulary, then once per epoch), so you need an object that can be iterated repeatedly. A class with an __iter__ method does this.
import logging
from pathlib import Path
from gensim.models import Word2Vec
from gensim.utils import simple_preprocess
logging.basicConfig(
format="%(asctime)s %(levelname)s %(message)s", level=logging.INFO
)
class Corpus:
"""Yields one list of lowercase tokens per line of a text file."""
def __init__(self, path):
self.path = path
def __iter__(self):
with open(self.path, encoding="utf-8") as f:
for line in f:
tokens = simple_preprocess(line)
if tokens:
yield tokens
Path("tiny.txt").write_text(
"The cat sits on the mat.\n"
"The dog sits on the rug.\n"
"The cat chases the mouse.\n"
"The dog chases the cat.\n",
encoding="utf-8",
)
model = Word2Vec(
sentences=Corpus("tiny.txt"),
vector_size=50,
window=2,
min_count=1,
sg=1,
negative=5,
epochs=50,
workers=1,
seed=1,
)
print(len(model.wv))
print(model.wv["cat"].shape)
print(model.wv.most_similar("cat", topn=3))With the logging line in place, gensim reports the vocabulary size, how many words min_count dropped, the effective sample rate and the progress of each epoch. Read these messages on a first run. They tell you whether the vocabulary is the size you expected.
Parameters that matter
| Parameter | Default | Effect |
|---|---|---|
| `vector_size` | 100 | Embedding dimension. 100 to 300 is typical. Larger values need more data. |
| `window` | 5 | Maximum distance between a word and its context word. gensim samples the actual window size per target word, so nearer words are seen more often. |
| `min_count` | 5 | Ignore words rarer than this. Rare words get poor vectors and cost memory. |
| `sg` | 0 | 1 selects skip-gram. 0 selects CBOW. |
| `negative` | 5 | Number of noise words per positive pair. 0 disables negative sampling. |
| `hs` | 0 | 1 enables hierarchical softmax. It can be combined with negative sampling. |
| `sample` | 1e-3 | Subsampling threshold for frequent words. 0 disables subsampling. |
| `alpha`, `min_alpha` | 0.025, 0.0001 | Learning rate at the start and end. It decays linearly across training. |
| `epochs` | 5 | Passes over the corpus. Small corpora benefit from 20 or more. |
| `ns_exponent` | 0.75 | Exponent that flattens the unigram distribution for noise words. |
| `workers` | 3 | Training threads. |
A few practical rules follow from the earlier theory:
- Skip-gram is slower than CBOW but gives better vectors for rare words. CBOW averages the context vectors, so it trains faster and suits large corpora and frequent words.
- Window size changes what the vectors capture. Small windows (2 to 5) favor syntactic, interchangeable-word similarity. Large windows (10 or more) favor topical relatedness.
- Raising
negativeto 10 to 20 helps on small corpora. On large corpora 2 to 5 is enough. min_countandsampleinteract with corpus size. On a toy corpus, setmin_count=1and expectsampleto remove nothing useful. On a billion-token corpus, keep the defaults or lowersampleto around 1e-5.
Reproducibility
Two runs with the same seed can still differ. Thread scheduling changes the order of updates, so results are exactly repeatable only with workers=1. Gensim also hashes words to seed their initial vectors, so set the environment variable PYTHONHASHSEED as well if you need identical runs across processes. Even then, treat small differences in neighbour order as normal. Judge a configuration by evaluation scores, not by one run.
Saving, loading and continuing training
Save the whole model if you may train more later. Save only the KeyedVectors if you just need lookups. The vectors-only file is smaller, and it cannot be trained further.
from gensim.models import KeyedVectors, Word2Vec
model.save("w2v.model")
wv_only = model.wv
wv_only.save("w2v.kv")
reloaded = KeyedVectors.load("w2v.kv")
print("cat" in reloaded)
print("elephant" in reloaded)
# Continue training the full model on new sentences.
model = Word2Vec.load("w2v.model")
more = [["the", "cat", "sits", "on", "the", "rug"]]
model.build_vocab(more, update=True)
model.train(more, total_examples=len(more), epochs=model.epochs)Updating the vocabulary this way adds new words, but the learning rate schedule restarts, and old words drift toward the new data. For a serious domain change, retrain from scratch.
Common errors
- A vocabulary of single characters. You passed a list of strings, such as
["the cat sits"], instead of a list of token lists. Gensim iterates over each string and treats every character as a token. KeyError: "Key 'x' not present". The word was never seen, ormin_countdropped it. Checkword in model.wvfirst. The word2vec model has no vector for unknown words.- Old gensim 3 names.
sizeis nowvector_size,iteris nowepochs, andmodel.wv.vocabis replaced bymodel.wv.key_to_indexandmodel.wv.index_to_key. - Poor neighbours on a small corpus. Four sentences cannot give meaningful vectors. The output above only confirms that the pipeline runs. Use at least several hundred thousand tokens for results worth reading.
- Training that seems stuck. Check that
workersis more than 1 and that the corpus iterator is not the bottleneck. Reading and tokenizing in the main thread can starve the workers.
Exercise
A colleague trains Word2Vec with sentences=["the cat sat", "the dog sat"] and then finds that model.wv.most_similar("cat") raises a KeyError. What went wrong, and how do you fix it?
Show answer
Each sentence is a plain string, so gensim iterates over its characters and the vocabulary contains letters such as "t" and "h", not words. The word "cat" is never in the vocabulary, hence the KeyError. Tokenize first, for example [["the", "cat", "sat"], ["the", "dog", "sat"]], or use a corpus class that yields token lists. Also set min_count=1 for a toy corpus, because the default of 5 would drop every word.