gpt4 book ai didi

nlp - 寻找有效的 NLP Phrase Embedding 模型

转载 作者:行者123 更新时间:2023-12-04 08:55:46 36 4
gpt4 key购买 nike

我想要实现的目标是找到一个好的 word_and_phrase 嵌入模型,它可以做到:(1) 对于我感兴趣的词和短语,它们有嵌入。(2) 我可以使用嵌入来比较两个事物(可以是单词或短语)之间的相似度

到目前为止我已经尝试了两条路:

1:一些Gensim加载的预训练模型,例如:

from gensim.models.word2vec import Word2Vec
import gensim.downloader as api
# download the model and return as object ready for use
model_glove_twitter = api.load("fasttext-wiki-news-subwords-300")
model_glove_twitter.similarity('computer-science', 'machine-learning')

这个路径的问题是我不知道一个短语是否有嵌入。对于这个例子,我得到了这个错误:

KeyError: "word 'computer-science' not in vocabulary"

我将不得不尝试不同的预训练模型,例如 word2vec-google-news-300、glove-wiki-gigaword-300、glove-twitter-200 等。结果相似,总有感兴趣的短语没有嵌入。

  1. 然后我尝试使用一些基于 BERT 的句子嵌入方法:https://github.com/UKPLab/sentence-transformers .
from sentence_transformers import SentenceTransformer
model = SentenceTransformer('distilbert-base-nli-mean-tokens')

from scipy.spatial.distance import cosine

def cosine_similarity(embedding_1, embedding_2):
# Calculate the cosine similarity of the two embeddings.
sim = 1 - cosine(embedding_1, embedding_2)
print('Cosine similarity: {:.2}'.format(sim))

phrase_1 = 'baby girl'
phrase_2 = 'annual report'
embedding_1 = model.encode(phrase_1)
embedding_2 = model.encode(phrase_2)
cosine_similarity(embedding_1[0], embedding_2[0])

使用这种方法,我能够为我的短语获得嵌入,但相似度得分为 0.93,这似乎不太合理。

那么我还能尝试什么来实现上述两个目标呢?

最佳答案

第一个路径的问题是您正在加载像 word2vec 嵌入这样的 fastText 嵌入,而 word2vec 无法处理 Out Of Vocabulary 单词

好处是 fastText 可以管理 OOV 词。您可以使用 Facebook 原始实现(pip install fasttext)或 Gensim 实现。

例如,使用 Facebook 实现,您可以:

import fasttext
import fasttext.util

# download an english model
fasttext.util.download_model('en', if_exists='ignore') # English
model = fasttext.load_model('cc.en.300.bin')

# get word embeddings
# (if instead you want sentence embeddings, use get_sentence_vector method)
word_1='computer-science'
word_2='machine-learning'
embedding_1=model.get_word_vector(word_1)
embedding_2=model.get_word_vector(word_2)

# compare the embeddings
cosine_similarity(embedding_1, embedding_2)

关于nlp - 寻找有效的 NLP Phrase Embedding 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63843793/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com