Word2Vec, GloVe and FastText
Count words, weight them with TF-IDF, train dense vectors and split rare words into subwords. Python from the lessons.
- Concepts and terms
- Tasks and commands
- Annotated code
- Diagrams
- Defaults and numbers
- Troubleshooting
- Questions and tips
Skip-gram with negative sampling#
From Lesson 05.03
One training step: train_pair#
Tasks in code#
| Task | Code |
|---|---|
| Count matrix | bag_of_words(docs, |
| Unit-length TF-IDF rows | l2_normalize(tfidf(bow)) |
| Train skip-gram from scratch | train(docs, |
| Analogy query | analogy(vocab, |
| Co-occurrence counts | build_cooccurrence(docs, |
| Train GloVe | glove_train(vocab, |
| FastText n-grams | char_ngrams(word, |
| Learn and apply BPE | apply_bpe("lowest", |
Libraries in production#
tfidf = TfidfVectorizer().fit_transform(docs)IDF weights plus L2 normmodel = Word2Vec(sentences, vector_size=100, window=5, min_count=1, sg=1, negative=5, workers=4, epochs=30)model.wv.most_similar("cat", topn=3)nearest neighboursfasttext.util.download_model("en", if_exists="ignore")ft = fasttext.load_model("cc.en.300.bin")ft.get_word_vector("zoomerapproved")OOV word still gets a vectortok = AutoTokenizer.from_pretrained("gpt2")tok.tokenize("unbelievably tokenized")Ġ marks a word boundaryFrom Lesson 05.02, Lesson 05.03, Lesson 05.04
Formulas#
- TF-IDF
- \frac{\mathrm{count}(w \text{ in } d)}{|d|} \cdot \log\frac{N}{\mathrm{df}(w)}
- Smoothed IDF
- \log\frac{n+1}{d+1} + 1. A word in every doc keeps IDF 1.
- Cosine
- dot product of L2-normalized rows. 1 is identical, 0 is orthogonal.
- GloVe fit
- v_i \cdot v_j + b_i + b_j \approx \log X_{ij}
- GloVe weight
- f(x) = (x / x_{max})^{\alpha} below
x_max, else 1.0. - GloVe output
W + W_tilde. The sum beats one table alone.- FastText vector
- the sum of the vectors of the word's character n-grams.
- BPE vocabulary
k + 256tokens afterkmerges.
From Lesson 05.02, Lesson 05.04
Vectorizer knobs#
| Command | What it does |
|---|---|
ngram_range= | Adds bigrams. Usually helps classification |
min_df= | Drops words in fewer than 2 docs |
max_df= | Drops words in more than 95% of docs |
stop_words= | Built-in stopword list. Not for sentiment |
sublinear_tf= | Uses 1 + log(tf) for repeated terms |
get_feature_names_out | Lists the vocabulary columns |
From Lesson 05.02
Tips#
- Under 500 labeled examples, start with a TF-IDF baseline.
- Below about 50k labels, try TF-IDF weighted embeddings.
- Do not judge embeddings on analogy accuracy alone. Add a downstream test.
- Download pretrained vectors. You almost never train Word2Vec yourself.
- GPT, BERT and T5 tokenizers learn 30k-100k merges.
From Lesson 05.02, Lesson 05.03, Lesson 05.04
Defaults and numbers#
| Setting | Default | Note |
|---|---|---|
gensim vector_size | 100 | Dense vectors are typically 100-300 |
gensim window | 5 | The from-scratch code uses 2 |
negative, k_neg | 5 | Negatives for each positive pair |
sg | 1 | Skip-gram. Better for rare words |
| Init std | 0.1 | rng.normal(0, |
GloVe x_max | 100 | Pairs at or above it get weight 1.0 |
GloVe alpha | 0.75 | Downweights frequent pairs |
| FastText n-gram length | 3 to 6 | Characters, with < and > marks |
From Lesson 05.03, Lesson 05.04
Troubleshooting#
| Symptom | Cause | Fix |
|---|---|---|
| "not good" and "excellent" look alike | BoW drops word order | Add bigrams or use embeddings |
Zoomer-approved has no vector | OOV in BoW and Word2Vec | Use FastText or BPE |
bank has one vector for two senses | Static embedding | Use contextual embeddings |
| Long docs dominate similarity | Rows not normalized | Apply l2_normalize |
| Negation signal lost | Stopword removal | Keep stopwords for sentiment |
| Norm below 0.01 or above 100 | Training bug | Flag the model |
| Silent bad production output | Tokenizer and model mismatch | Use the tokenizer the model shipped with |
| Dense 100k-doc matrix does not fit | Dense conversion too early | Stay sparse |
From Lesson 05.02, Lesson 05.03, Lesson 05.04
Abbreviations#
- BoW
- Bag of Words. Counts of vocabulary words. Order is lost.
- TF / DF
- term frequency in a doc, and the count of docs with the word.
- IDF
- inverse document frequency. Downweights words that occur everywhere.
- CBOW
- Continuous Bag of Words. Predict the center from its context.
- Skip-gram
- predict the context from the center. The default.
- GloVe
- Global Vectors. Factorizes the co-occurrence matrix.
- OOV
- Out of vocabulary. Word2Vec and GloVe fail on it.
- BPE
- Byte-Pair Encoding. Merge the most frequent adjacent pair, repeat.
From Lesson 05.02, Lesson 05.03, Lesson 05.04
Questions#
- When does TF-IDF still win?
- Spam, topics, logs, low data, tight latency, explainable output.
- Why negative sampling?
- Softmax over 100k words is too slow. A binary task replaces it.
- Why does an analogy work?
(king - man)holds a "royal" direction. Add it towoman.- GloVe or FastText?
- FastText for misspellings, new words and rich morphology.
- Train a tokenizer for fine-tuning?
- No. Use the tokenizer of the pretrained model.
From Lesson 05.02, Lesson 05.03, Lesson 05.04