Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python - Word2Vec을 사용한 워드 임베딩

<시간/>

Word Embedding은 단어를 실수 벡터에 매핑하는 데 사용되는 언어 모델링 기술입니다. 여러 차원의 벡터 공간에서 단어나 구를 나타냅니다. 단어 임베딩은 신경망, 동시 발생 행렬, 확률 모델 등과 같은 다양한 방법을 사용하여 생성할 수 있습니다.

Word2Vec은 단어 임베딩을 생성하기 위한 모델로 구성됩니다. 이 모델은 하나의 입력 레이어, 하나의 은닉 레이어 및 하나의 출력 레이어가 있는 얕은 2층 신경망입니다.

# 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'))