Sub topic 15
Using pretrained GloVe vectors
Assume you know Python, NumPy arrays, dot products, cosine similarity, and basic tokenization. This chapter shows how to load pretrained GloVe embeddings, query them, and handle results critically.
What pretrained vectors contain
GloVe, or Global Vectors, learns one dense vector for each word from word–context co-occurrence counts. A pretrained model has already been trained on a large corpus such as Wikipedia or Common Crawl. You reuse its vectors instead of training on your own text.
A vector captures patterns from the training corpus. Words used in similar contexts tend to have nearby vectors. The vectors are not definitions, and they do not guarantee that two nearby words are interchangeable.
The glove-wiki-gigaword-50 model contains 50-dimensional vectors trained from Wikipedia text. Gensim can download and cache this model:
import gensim.downloader as api
wv = api.load("glove-wiki-gigaword-50")
print(wv.vector_size)
print(wv["computer"].shape)
print(wv.most_similar("frog", topn=5))
analogy = wv.most_similar(
positive=["king", "woman"],
negative=["man"],
topn=3,
)
print(analogy)The KeyedVectors object wv stores vectors and provides lookup methods. wv["computer"] returns a NumPy array. most_similar ranks words by cosine similarity. The analogy query searches for a vector close to:
vector("king") + vector("woman") - vector("man")
The result may contain queen, but the exact ranking depends on the corpus, vocabulary, and model version.
Loading a text file directly
Pretrained GloVe releases are also distributed as text files. Each line contains a word followed by its vector components:
king 0.50451 -0.06488 ...A simple loader creates a dictionary:
import numpy as np
def load_glove(path):
vectors = {}
with open(path, encoding="utf-8") as file:
for line in file:
parts = line.rstrip().split(" ")
word = parts[0]
vectors[word] = np.asarray(parts[1:], dtype=np.float32)
return vectors
# vectors = load_glove("glove.6B.50d.txt")
# print(vectors["king"].shape)This approach gives direct access to arrays, but it does not provide Gensim's similarity and analogy helpers.
Choosing and checking a model
| Decision | Question to ask |
|---|---|
| Corpus | Does the training text resemble your application? |
| Dimension | Is the vector size large enough for the task and memory budget? |
| Vocabulary | Does it include domain terms and common variants? |
| Bias | Could its historical or social associations affect predictions? |
For production use, decide on an OOV policy, such as an unknown vector, subword features, or a different embedding model. Do not silently discard unknown words when they carry important information.
Exercise
Why can a pretrained GloVe vector be useful without being a reliable definition of a word?
Show answer
It encodes usage patterns learned from contexts, so it captures associations and similarity rather than a complete, context-specific meaning.