Word Embedding เป็นเทคนิคการสร้างแบบจำลองภาษาที่ใช้สำหรับการจับคู่คำกับเวกเตอร์ของจำนวนจริง มันแสดงถึงคำหรือวลีในพื้นที่เวกเตอร์ที่มีหลายมิติ การฝังคำสามารถสร้างขึ้นได้โดยใช้วิธีการต่างๆ เช่น โครงข่ายประสาทเทียม เมทริกซ์การเกิดขึ้นร่วม แบบจำลองความน่าจะเป็น เป็นต้น
Word2Vec ประกอบด้วยแบบจำลองสำหรับสร้างการฝังคำ โมเดลเหล่านี้เป็นโครงข่ายประสาทเทียมแบบตื้น 2 ชั้นที่มีชั้นอินพุต 1 เลเยอร์ เลเยอร์ที่ซ่อนอยู่ 1 เลเยอร์ และเอาต์พุต 1 เลเยอร์
ตัวอย่าง
# importing all necessary modules
from nltk.tokenize import sent_tokenize, word_tokenize
import warnings
warnings.filterwarnings(action = 'ignore')
import gensim
from gensim.models import Word2Vec
# Reads ‘alice.txt’ file
sample = open("C:\\Users\\Vishesh\\Desktop\\alice.txt", "r")
s = sample.read()
# Replaces escape character with space
f = s.replace("\n", " ")
data = []
# iterate through each sentence in the file
for i in sent_tokenize(f):
temp = []
# tokenize the sentence into words
for j in word_tokenize(i):
temp.append(j.lower())
data.append(temp)
# Create CBOW model
model1 = gensim.models.Word2Vec(data, min_count = 1, size = 100, window = 5)
# Print results
print("Cosine similarity between 'alice' " + "and 'wonderland' - CBOW : ", model1.similarity('alice', 'wonderland'))
print("Cosine similarity between 'alice' " + "and 'machines' - CBOW : ", model1.similarity('alice', 'machines'))
# Create Skip Gram model
model2 = gensim.models.Word2Vec(data, min_count = 1, size = 100, window =5, sg = 1)
# Print results
print("Cosine similarity between 'alice' " + "and 'wonderland' - Skip Gram : ", model2.similarity('alice', 'wonderland'))
print("Cosine similarity between 'alice' " + "and 'machines' - Skip Gram : ", model2.similarity('alice', 'machines'))