#imports
from nltk.corpus import brown
import numpy as np
from gensim.models import Word2Vec
#Using brown corpus (category news) from nltk. Replace by your corpus with suitable words/sentences
sentences =brown.sents(categories = 'news')
#initialize and train model
model = Word2Vec(min_count=1)
model.build_vocab(sentences)
model.train(sentences, total_examples=model.corpus_count, epochs=model.iter)
# find similarity between two words
model.wv.similarity('good','well')
为此,您需要定义某种方法来查找一组单词之间的相似性。一种方法是生成单词嵌入的Word2Vec。 Gensim很好地实现了word2vec,请阅读以下内容:
https://radimrehurek.com/gensim/models/word2vec.html
对于word2Vec,您需要corpora来训练模型,然后为给定的单词集进行向量嵌入。然后使用任何距离函数(例如余弦)找到最接近它的单词
下面是一个示例代码:
注:这里,我比较两个词,你也可以用其他方法,从语料库中找出最相似的词。注意语料库中没有的单词。在
在这里我使用概率的概念,那些单词在列表中出现概率较高的单词是列表中相似度最高的单词。在
试试这个代码!我还附上了输出的截图。在
相关问题 更多 >
编程相关推荐