Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python - Nhúng từ (Word Embedding) với Word2Vec


Word Embedding là kỹ thuật mô hình ngôn ngữ ánh xạ từ thành vector số thực. Biểu diễn từ/cụm từ trong không gian vector nhiều chiều. Có thể tạo bằng mạng nơ-ron, ma trận đồng xuất hiện, mô hình xác suất, v.v.

Word2Vec (gensim) bao gồm các mô hình tạo word embedding: CBOW (Continuous Bag of Words) và Skip-gram. Đều là mạng nơ-ron nông 2 lớp (input, hidden, output).

Ví dụ: Huấn luyện và tính độ tương đồng cosine

from nltk.tokenize import sent_tokenize, word_tokenize
import warnings
warnings.filterwarnings(action='ignore')
import gensim
from gensim.models import Word2Vec

# Đọc file văn bản
with open(r"C:\Users\Vishesh\Desktop\alice.txt", "r", encoding="utf-8") as f:
    text = f.read().replace("\n", " ")

# Tiền xử lý: tách câu, tách từ, lowercase
data = []
for sent in sent_tokenize(text):
    tokens = [w.lower() for w in word_tokenize(sent)]
    data.append(tokens)

# CBOW model (sg=0 mặc định)
model1 = Word2Vec(data, min_count=1, vector_size=100, window=5)
print("CBOW - alice vs wonderland:", model1.wv.similarity('alice', 'wonderland'))
print("CBOW - alice vs machines:", model1.wv.similarity('alice', 'machines'))

# Skip-gram model (sg=1)
model2 = Word2Vec(data, min_count=1, vector_size=100, window=5, sg=1)
print("Skip-gram - alice vs wonderland:", model2.wv.similarity('alice', 'wonderland'))
print("Skip-gram - alice vs machines:", model2.wv.similarity('alice', 'machines'))

Tham số quan trọng

  • vector_size: chiều vector nhúng (mặc định 100).
  • window: kích thước cửa sổ ngữ cảnh.
  • min_count: bỏ qua từ xuất hiện ít hơn ngưỡng.
  • sg: 0=CBOW, 1=Skip-gram.