使用 Gensim 预训练 GloVe 处理超出词汇量的单词
Deal with Out of vocabulary word with Gensim pretrained GloVe
我正在处理 NLP 作业并加载了 Gensim 提供的 GloVe 向量:
import gensim.downloader
glove_vectors = gensim.downloader.load('glove-twitter-25')
我正在尝试为句子中的每个单词获取词嵌入,但其中一些不在词汇表中。
使用 Gensim 处理它的最佳方法是什么 API?
谢谢!
加载 model:
import gensim.downloader as api
model = api.load("glove-twitter-25") # load glove vectors
# model.most_similar("cat") # show words that similar to word 'cat'
有一种非常简单的方法可以查明这些词是否存在于模型的词汇表中。
result = print('Word exists') if word in model.wv.vocab else print('Word does not exist")
除此之外,我还使用以下逻辑创建带有 N 个标记的句子嵌入(25 dim):
from __future__ import print_function, division
import os
import re
import sys
import regex
import numpy as np
from functools import partial
from fuzzywuzzy import process
from Levenshtein import ratio as lev_ratio
import gensim
import tempfile
def vocab_check(model, word):
similar_words = model.most_similar(word)
match_ratio = 0.
match_word = ''
for sim_word, sim_score in similar_words:
ratio = lev_ratio(word, sim_word)
if ratio > match_ratio:
match_word = sim_word
if match_word == '':
return similar_words[0][1]
return model.similarity(word, match_word)
def sentence2vector(model, sent, dim=25):
words = sent.split(' ')
emb = [model[w.strip()] for w in words]
weights = [1. if w in model.wv.vocab else vocab_check(model, w) for w in words]
if len(emb) == 0:
sent_vec = np.zeros(dim, dtype=np.float16)
else:
sent_vec = np.dot(weights, emb)
sent_vec = sent_vec.astype("float16")
return sent_vec
我正在处理 NLP 作业并加载了 Gensim 提供的 GloVe 向量:
import gensim.downloader
glove_vectors = gensim.downloader.load('glove-twitter-25')
我正在尝试为句子中的每个单词获取词嵌入,但其中一些不在词汇表中。
使用 Gensim 处理它的最佳方法是什么 API?
谢谢!
加载 model:
import gensim.downloader as api
model = api.load("glove-twitter-25") # load glove vectors
# model.most_similar("cat") # show words that similar to word 'cat'
有一种非常简单的方法可以查明这些词是否存在于模型的词汇表中。
result = print('Word exists') if word in model.wv.vocab else print('Word does not exist")
除此之外,我还使用以下逻辑创建带有 N 个标记的句子嵌入(25 dim):
from __future__ import print_function, division
import os
import re
import sys
import regex
import numpy as np
from functools import partial
from fuzzywuzzy import process
from Levenshtein import ratio as lev_ratio
import gensim
import tempfile
def vocab_check(model, word):
similar_words = model.most_similar(word)
match_ratio = 0.
match_word = ''
for sim_word, sim_score in similar_words:
ratio = lev_ratio(word, sim_word)
if ratio > match_ratio:
match_word = sim_word
if match_word == '':
return similar_words[0][1]
return model.similarity(word, match_word)
def sentence2vector(model, sent, dim=25):
words = sent.split(' ')
emb = [model[w.strip()] for w in words]
weights = [1. if w in model.wv.vocab else vocab_check(model, w) for w in words]
if len(emb) == 0:
sent_vec = np.zeros(dim, dtype=np.float16)
else:
sent_vec = np.dot(weights, emb)
sent_vec = sent_vec.astype("float16")
return sent_vec