Sub topic 17
Using pretrained GloVe vectors
This chapter assumes you can write basic Python and NumPy, know what cosine similarity is, and have read the earlier chapters on the GloVe objective and on training word2vec with gensim. Here you learn to pick a released GloVe file, load it, check that your text matches its vocabulary, and feed it into your own code.
Why use pretrained vectors
Training GloVe on a large corpus takes a long co-occurrence pass and many epochs of optimization. The Stanford group has already done this on very large corpora and published the results. For a small task such as classifying a few thousand reviews, these vectors usually beat anything you could train on your own data. They carry information about words your data barely mentions.
The trade-off is that you inherit the choices made when the vectors were built. These are the corpus, the tokenization, the casing, the vocabulary and the dimensionality. Most problems with pretrained vectors come from a mismatch between those choices and your text.
Choosing a release
The common releases differ in corpus size, casing and dimensions.
| Release | Training text | Vocabulary | Casing | Dimensions |
|---|---|---|---|---|
| glove.6B | Wikipedia 2014 + Gigaword 5, 6B tokens | 400K | lowercased | 50, 100, 200, 300 |
| glove.42B | Common Crawl, 42B tokens | 1.9M | lowercased | 300 |
| glove.840B | Common Crawl, 840B tokens | 2.2M | cased | 300 |
| glove.twitter.27B | 2B tweets, 27B tokens | 1.2M | lowercased | 25, 50, 100, 200 |
Match the release to your text. Tweets with hashtags and misspellings suit the Twitter vectors. Encyclopedic or news text suits 6B. Mixed web text suits the Common Crawl releases. More dimensions give more capacity, but the gain flattens around 200 to 300, and a 300-dimensional table for 2 million words is several gigabytes in memory.
Loading through gensim
The simplest route is the gensim downloader. It fetches the file once, caches it on disk, and returns a KeyedVectors object.
import gensim.downloader as api
wv = api.load("glove-wiki-gigaword-50")
print(len(wv.key_to_index), wv.vector_size)
print(wv.most_similar("frog", topn=5))
print(wv.most_similar(positive=["king", "woman"], negative=["man"], topn=3))The model name glove-wiki-gigaword-50 is the 6B release at 50 dimensions, about 66 MB. The other names are glove-wiki-gigaword-100, -200, -300, and glove-twitter-25, -50, -100, -200. The most_similar call ranks all 400,000 words by cosine similarity to the query vector, so it is a linear scan and takes a noticeable moment on large tables.
Loading the raw text files
If you downloaded glove.6B.50d.txt yourself, you can parse it directly. Each line is a word followed by its components, separated by single spaces.
import numpy as np
def load_glove(path):
vectors = {}
with open(path, encoding="utf-8") as f:
for line in f:
parts = line.rstrip().split(" ")
vectors[parts[0]] = np.asarray(parts[1:], dtype=np.float32)
return vectors
# glove = load_glove("glove.6B.50d.txt")
# print(glove["king"].shape)This works for the 6B files. The 840B file contains a few tokens that include spaces, so parts[0] is wrong for those lines. A safer parser takes the last dim fields as the vector and joins the rest as the word.
For large files, prefer gensim's loader, which is faster and stores a compact array instead of a dictionary of small arrays:
from gensim.models import KeyedVectors
wv = KeyedVectors.load_word2vec_format(
"glove.6B.50d.txt", binary=False, no_header=True
)The no_header=True argument exists because GloVe files lack the first line (vocabulary size and dimension) that the word2vec text format has. This argument needs gensim 4.0 or later. Older tutorials convert the file first with glove2word2vec, which is no longer necessary.
Checking coverage before you trust the vectors
A pretrained table only helps for words it contains. Lookup of a missing word raises KeyError, so measure how much of your data is covered.
import numpy as np
import gensim.downloader as api
wv = api.load("glove-wiki-gigaword-50")
def coverage(tokens, wv):
known = [t for t in tokens if t in wv]
missing = sorted({t for t in tokens if t not in wv})
return len(known) / len(tokens), missing
tokens = "The Cat sat on the mat , tweeting #nlp lol".split()
ratio, missing = coverage(tokens, wv)
print(round(ratio, 2), missing)The capitalized The and Cat are missing because the 6B vocabulary is lowercased. The hashtag #nlp and lol may also be missing or rare. Lowercase your text first for a lowercased release, and use the same tokenizer style the release used. GloVe 6B splits punctuation into separate tokens, so "don't" appears as do and n't. A mismatch here silently turns common words into unknowns.
Using the vectors downstream
There are two common ways to use the table.
The first is a fixed-length feature. Average the vectors of the known tokens in a text and give the result to a classifier.
import numpy as np
def sentence_vector(tokens, wv):
vecs = [wv[t] for t in tokens if t in wv]
if not vecs:
return np.zeros(wv.vector_size, dtype=np.float32)
return np.mean(vecs, axis=0)
v = sentence_vector("the cat sat on the mat".split(), wv)
print(v.shape)Averaging discards word order and lets frequent function words dilute the signal. It makes a strong baseline, but not a state-of-the-art model.
The second is an initial embedding layer for a neural network. Build a matrix whose row i is the vector for the word with index i in your own vocabulary:
import numpy as np
def build_embedding_matrix(vocab, wv, seed=0):
rng = np.random.default_rng(seed)
matrix = rng.normal(0.0, 0.1, size=(len(vocab), wv.vector_size)).astype(np.float32)
hits = 0
for i, word in enumerate(vocab):
if word in wv:
matrix[i] = wv[word]
hits += 1
return matrix, hits
vocab = ["<pad>", "the", "cat", "sat", "zzyzx"]
matrix, hits = build_embedding_matrix(vocab, wv)
print(matrix.shape, hits)Words missing from GloVe keep small random vectors, so the network can still learn them. You then choose whether to freeze the matrix or let training update it. Freezing is safer with little data, because fine-tuning can overfit the words that appear in your training set and leave the others behind. Fine-tuning helps when you have plenty of labeled data and a domain that differs from the source corpus. Set the padding row to zeros if your framework does not mask it.
Common errors
- Comparing vectors from different releases. Dimensions and spaces differ, so a vector from one file means nothing in another.
- Forgetting to lowercase for a lowercased release.
- Reading the file with the wrong encoding. Use UTF-8.
- Treating
most_similaroutput as ground truth. Neighbours reflect the training corpus, including its biases. - Loading a 300-dimensional, multi-million word table when 100 dimensions would do, and running out of memory.
Exercise
You load glove-wiki-gigaword-100 and run your product reviews through it. Coverage is only 71%, and the most frequent missing tokens are "Great", "The" and "Love". What is the most likely cause, and what is the first fix?
Show answer
The 6B release is lowercased, so capitalized tokens have no entry. Lowercase the text before lookup, then recompute coverage. If many tokens are still missing, check the tokenizer, because GloVe 6B separates punctuation and contractions into their own tokens.