Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python - Word Embedding ด้วย Word2Vec (gensim)

Word Embedding เป็นเทคนิคจำลองภาษา แมปคำเป็นเวกเตอร์จำนวนจริง แสดงคำ/วลีในพื้นที่เวกเตอร์หลายมิติ สร้างได้จาก Neural Networks, Co-occurrence Matrix, Probabilistic Models ฯลฯ

Word2Vec ประกอบด้วยโมเดลสำหรับสร้าง embedding: CBOW (Continuous Bag of Words) และ Skip-gram เป็น Neural Network 2 ชั้น (input, hidden, output)

ตัวอย่าง: ฝึก Word2Vec กับข้อความ alice.txt

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

# อ่านไฟล์
with open(r"C:\Users\Vishesh\Desktop\alice.txt", "r", encoding="utf-8") as f:
    text = f.read().replace('\n', ' ')

# Tokenize ประโยคและคำ แปลงเป็น lowercase
data = []
for sent in sent_tokenize(text):
    tokens = [w.lower() for w in word_tokenize(sent)]
    data.append(tokens)

# โมเดล CBOW (sg=0 เป็นค่าเริ่มต้น)
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 (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'))

คำอธิบาย

  • min_count=1 นับคำที่ปรากฏอย่างน้อย 1 ครั้ง
  • vector_size (เดิม size) ขนาดเวกเตอร์
  • window ขนาดบริบทรอบคำเป้าหมาย
  • sg=0 CBOW, sg=1 Skip-gram
  • model.wv.similarity() คำนวณ Cosine Similarity ระหว่างสองคำ