๐Ÿค– AI/ML

Word2Vec

Word2Vec

An embedding technique that represents words as vectors. CBOW and Skip-gram methods. The foundation of modern NLP.

๐Ÿ“– Detailed Explanation

Word2Vec is a word embedding technique published by Tomas Mikolov of Google in 2013, which represents words as fixed-dimensional dense vectors (Dense Vector). Based on the distributional hypothesis that "words that appear in similar contexts have similar meanings," it learns semantic relationships between words from large text corpora.

Before Word2Vec, One-Hot Encoding was mainly used. However, a one-hot vector has a dimensionality equal to the vocabulary size and cannot express similarity between words. Word2Vec represents words as vectors of several hundred dimensions and can capture semantic relationships through vector arithmetic, as in "king - man + woman = queen."

Word2Vec offers two training methods. CBOW (Continuous Bag of Words) predicts the center word from its surrounding words, while Skip-gram predicts the surrounding words from the center word. Skip-gram is strong on rare words, and CBOW trains faster. Negative Sampling improves training efficiency, and hundreds of millions of words can be trained on a CPU.

In practice, Word2Vec performs worse than contextual embeddings such as BERT and GPT, so direct use has declined, but it remains conceptually very important. FastText (subword processing) and GloVe (use of global statistics) built on Word2Vec and became the foundation of modern embeddings. It is still used for educational purposes and lightweight projects.

๐Ÿ’ป Code Example

from gensim.models import Word2Vec
from gensim.models import KeyedVectors
import numpy as np

# 1. ์ƒ˜ํ”Œ ๋ฐ์ดํ„ฐ (ํ† ํฐํ™”๋œ ๋ฌธ์žฅ ๋ฆฌ์ŠคํŠธ)
sentences = [
    ["์ธ๊ณต์ง€๋Šฅ", "๋จธ์‹ ๋Ÿฌ๋‹", "๋”ฅ๋Ÿฌ๋‹", "์—ฐ๊ตฌ"],
    ["์ž์—ฐ์–ด", "์ฒ˜๋ฆฌ", "NLP", "ํ…์ŠคํŠธ", "๋ถ„์„"],
    ["๋จธ์‹ ๋Ÿฌ๋‹", "์•Œ๊ณ ๋ฆฌ์ฆ˜", "ํ•™์Šต", "๋ฐ์ดํ„ฐ"],
    ["๋”ฅ๋Ÿฌ๋‹", "์‹ ๊ฒฝ๋ง", "GPU", "ํ•™์Šต"],
    ["์ธ๊ณต์ง€๋Šฅ", "์ž์—ฐ์–ด", "์ฒ˜๋ฆฌ", "์ฑ—๋ด‡"],
]

# 2. Word2Vec ๋ชจ๋ธ ํ•™์Šต
model = Word2Vec(
    sentences,
    vector_size=100,    # ์ž„๋ฒ ๋”ฉ ์ฐจ์›
    window=5,           # ์ปจํ…์ŠคํŠธ ์œˆ๋„์šฐ ํฌ๊ธฐ
    min_count=1,        # ์ตœ์†Œ ์ถœํ˜„ ๋นˆ๋„
    sg=1,               # 1=Skip-gram, 0=CBOW
    workers=4,          # ๋ณ‘๋ ฌ ์Šค๋ ˆ๋“œ ์ˆ˜
    epochs=100          # ํ•™์Šต ์—ํฌํฌ
)

# 3. ๋‹จ์–ด ๋ฒกํ„ฐ ํ™•์ธ
vector = model.wv["์ธ๊ณต์ง€๋Šฅ"]
print(f"'์ธ๊ณต์ง€๋Šฅ' ๋ฒกํ„ฐ ์ฐจ์›: {vector.shape}")
print(f"๋ฒกํ„ฐ (์ฒ˜์Œ 10๊ฐœ): {vector[:10]}")

# 4. ์œ ์‚ฌ ๋‹จ์–ด ๊ฒ€์ƒ‰
similar = model.wv.most_similar("๋จธ์‹ ๋Ÿฌ๋‹", topn=5)
print("\n'๋จธ์‹ ๋Ÿฌ๋‹'๊ณผ ์œ ์‚ฌํ•œ ๋‹จ์–ด:")
for word, score in similar:
    print(f"  {word}: {score:.4f}")

# 5. ๋‹จ์–ด ๊ฐ„ ์œ ์‚ฌ๋„
similarity = model.wv.similarity("๋”ฅ๋Ÿฌ๋‹", "์‹ ๊ฒฝ๋ง")
print(f"\n๋”ฅ๋Ÿฌ๋‹ - ์‹ ๊ฒฝ๋ง ์œ ์‚ฌ๋„: {similarity:.4f}")

# 6. ๋ฒกํ„ฐ ์—ฐ์‚ฐ (Word Analogy)
# A:B = C:? -> ? = B - A + C
try:
    result = model.wv.most_similar(
        positive=["๋”ฅ๋Ÿฌ๋‹", "์ž์—ฐ์–ด"],
        negative=["๋จธ์‹ ๋Ÿฌ๋‹"],
        topn=3
    )
    print("\n๋”ฅ๋Ÿฌ๋‹ - ๋จธ์‹ ๋Ÿฌ๋‹ + ์ž์—ฐ์–ด =")
    for word, score in result:
        print(f"  {word}: {score:.4f}")
except KeyError as e:
    print(f"๋‹จ์–ด ์—†์Œ: {e}")

# 7. ๋ชจ๋ธ ์ €์žฅ & ๋กœ๋“œ
model.save("word2vec.model")
loaded_model = Word2Vec.load("word2vec.model")

# ๋ฒกํ„ฐ๋งŒ ์ €์žฅ (๊ฒฝ๋Ÿ‰)
model.wv.save_word2vec_format("word2vec.txt", binary=False)


# === ์‚ฌ์ „ํ•™์Šต ๋ชจ๋ธ ์‚ฌ์šฉ (์‹ค๋ฌด ๊ถŒ์žฅ) ===
# Google News 300์ฐจ์› (์•ฝ 3GB)
# https://drive.google.com/file/d/0B7XkCwpI5KDYNlNUTTlSS21pQmM

# pretrained = KeyedVectors.load_word2vec_format(
#     "GoogleNews-vectors-negative300.bin", binary=True
# )
# print(pretrained.most_similar("king"))


# === ํ•œ๊ตญ์–ด: FastText ์‚ฌ์šฉ ๊ถŒ์žฅ ===
# from gensim.models import FastText
#
# model_ko = FastText(
#     sentences,
#     vector_size=100,
#     window=5,
#     min_count=1,
#     sg=1
# )
# # FastText๋Š” OOV(๋ฏธ๋“ฑ๋ก ๋‹จ์–ด)๋„ ์ฒ˜๋ฆฌ ๊ฐ€๋Šฅ

๐Ÿ—ฃ๏ธ Say It Like This in Practice

๐Ÿ’ฌ In a Meeting

"Shall we apply Word2Vec-based synonym expansion to improve search? When a user searches for 'laptop,' 'notebook' and 'computer' would be searched together. That said, sentence embeddings like Sentence-BERT are more accurate these days."

๐Ÿ’ฌ In an Interview

"What is the difference between Word2Vec and BERT embeddings?" - "Word2Vec assigns a single fixed vector to each word. 'bank' gets the same vector whether it means a financial institution or a riverbank. BERT, on the other hand, is a contextual embedding that generates different vectors depending on context, so it can distinguish homonyms too."

๐Ÿ’ฌ In a Technical Discussion

"The 'king - man + woman = queen' operation in Word2Vec is actually not always accurate. Data bias is reflected, so unintended results can sometimes appear. Still, the very idea of representing word meaning in a vector space was groundbreaking."

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

โš ๏ธ Common Mistakes & Cautions

โŒ
Training on a small corpus

Word2Vec requires a large corpus of millions to billions of words. Training on small data yields low quality. Use pretrained models such as Google News or Wiki, or continue training on a domain corpus (Continual Training).

โŒ
Ignoring OOV (out-of-vocabulary) words

Word2Vec cannot handle words that were not in its training data. Even variants such as "์ธ๊ณต์ง€๋Šฅ๋“ค" are treated as separate words. For languages with diverse morphology like Korean, FastText (which supports subword processing) is more suitable.

โœ…
Use contextual embeddings in modern projects

In real NLP projects, use contextual embeddings such as BERT and Sentence-BERT. Word2Vec is suitable for educational/research purposes or environments with extremely limited resources.

๐Ÿ”— Related Terms

๐Ÿ“š Learn More