🤖 AI/ML

GloVe

Global Vectors

An embedding based on a word co-occurrence matrix. Developed at Stanford.

📖 Detailed Explanation

GloVe (Global Vectors for Word Representation) is a word embedding algorithm developed by the Stanford NLP group in 2014. It converts words into fixed-length dense vectors and is trained so that semantically similar words are positioned close together in the vector space.

While Word2Vec focuses on predicting surrounding words (local context), GloVe uses word co-occurrence statistics (global co-occurrence) from the entire corpus. Thanks to this approach, it showed excellent performance on the well-known word analogy task, such as "king - man + woman = queen".

The core principle is to first build a word co-occurrence matrix, then optimize so that the dot product of two word vectors is proportional to the logarithm of their co-occurrence probability. This approach combines the advantages of Word2Vec's prediction-based method and the traditional matrix factorization method.

As of 2025, Transformer-based embeddings (BERT, OpenAI Ada) are dominant, but GloVe is still valuable. Pre-trained vectors can be downloaded for free, almost no computation is required at inference time, and its high interpretability makes it useful in academic research and resource-constrained environments.

💻 Code Example

# GloVe 임베딩 로드 및 활용 예제
import numpy as np
from scipy.spatial.distance import cosine

# 1. 사전 학습된 GloVe 벡터 로드 (Wikipedia 6B, 100차원)
# 다운로드: https://nlp.stanford.edu/projects/glove/
def load_glove(filepath):
    embeddings = {}
    with open(filepath, 'r', encoding='utf-8') as f:
        for line in f:
            values = line.split()
            word = values[0]
            vector = np.array(values[1:], dtype='float32')
            embeddings[word] = vector
    return embeddings

glove = load_glove('glove.6B.100d.txt')
print(f"로드된 단어 수: {len(glove):,}개")  # 약 40만 단어

# 2. 단어 유사도 계산
def similarity(word1, word2):
    if word1 not in glove or word2 not in glove:
        return None
    return 1 - cosine(glove[word1], glove[word2])

print(f"king - queen 유사도: {similarity('king', 'queen'):.3f}")  # ~0.65
print(f"cat - dog 유사도: {similarity('cat', 'dog'):.3f}")        # ~0.80
print(f"cat - car 유사도: {similarity('cat', 'car'):.3f}")        # ~0.30

# 3. 단어 유추 (king - man + woman = ?)
def analogy(a, b, c, topn=5):
    """a:b = c:? 형태의 유추"""
    target = glove[b] - glove[a] + glove[c]

    similarities = []
    for word, vec in glove.items():
        if word in [a, b, c]:
            continue
        sim = 1 - cosine(target, vec)
        similarities.append((word, sim))

    return sorted(similarities, key=lambda x: x[1], reverse=True)[:topn]

print(analogy('man', 'king', 'woman'))
# [('queen', 0.77), ('monarch', 0.71), ('princess', 0.69), ...]

# 4. Gensim으로 간편하게 사용
from gensim.models import KeyedVectors

# GloVe를 Word2Vec 포맷으로 변환 후 로드
glove_model = KeyedVectors.load_word2vec_format(
    'glove.6B.100d.word2vec.txt', binary=False
)
print(glove_model.most_similar('python', topn=5))
# [('perl', 0.75), ('java', 0.72), ('ruby', 0.70), ...]

🗣️ Say It Like This in Practice

💬 In a Meeting
"I'll try using GloVe to improve search quality. When a user searches for '노트북', it expands synonyms so that 'laptop' and '맥북' are matched together, and it works locally right away without API costs."
💬 In an Interview
"The key difference between GloVe and Word2Vec is the training method. Word2Vec predicts surrounding words with a sliding window, whereas GloVe factorizes the co-occurrence matrix of the entire corpus. Because GloVe uses global statistics, it is stronger at handling rare words."
💬 In a Technical Discussion
"BERT embeddings are good, but they need GPU inference every time, right? For real-time services where batch processing is difficult, a GloVe lookup table is much faster. Fetching a single 300-dimensional vector takes microseconds."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Ignoring OOV (Out-of-Vocabulary) word handling

GloVe cannot handle words that are not in the training corpus. For data with many neologisms or typos, FastText (subword-based) is more suitable.

❌
Limitations of context-agnostic embeddings

It cannot distinguish whether "bank" means a financial bank or a riverbank. For tasks with many polysemous words, use contextual embeddings such as BERT.

✅
Correct approach: choose the dimensions and corpus that fit your purpose

Use the Wikipedia-trained version (6B) for general text and the Twitter version (27B) for social media. Choose the dimensions from 100d (fast) to 300d (accurate).

🔗 Related Terms

📚 Learn More