词语相似度计算

在商品搜索的过程中,可以计算用户输入的关键字与数据库中商品名间的相似度,在商品数据库中找出相似度最大的商品,推荐给用户。比如“凳子”跟“椅子”的语意更相近,跟“香蕉”或“冰箱”的语意相对较远,这种相近的程度就是词语的相似度。在实际的工程开发中可以通过word2vec实现词语相似度的计算。

from sklearn.datasets import fetch_20newsgroups

news = fetch_20newsgroups(subset='all')
X, y = news.data, news.target

from bs4 import BeautifulSoup
import nltk, re


# 把段落分解成由句子组成的list(每个句子又被分解成词语)
def news_to_sentences(news):
    news_text = BeautifulSoup(news, 'lxml').get_text()
    tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
    raw_sentences = tokenizer.tokenize(news_text)

    # 对每个句子进行处理,分解成词语
    sentences = []
    for sent in raw_sentences:
        sentences.append(re.sub('[^a-zA-Z]', ' ', sent.lower().strip()).split())
    return sentences


sentences = []

for x in X:
    sentences += news_to_sentences(x)

# import numpy
# # 将预处理过的"词库"保存到文件中,便于调试
# numpy_array = numpy.array(sentences)
# numpy.save('sentences.npy', numpy_array)
#
# # 将预处理后的"词库"从文件中读出,便于调试
# numpy_array = numpy.load('sentences.npy')
# sentences = numpy_array.tolist()


from gensim.models import word2vec

model = word2vec.Word2Vec(sentences, workers=2, size=300, min_count=20, window=5,sample=1e-3)

model.init_sims(replace=True)

# 保存word2vec训练参数便于调试
# model.wv.save_word2vec_format('word2vec_model.bin', binary=True)
# model.wv.load_word2vec_format('word2vec_model.bin', binary=True)

print('词语相似度计算:')
print('morning vs morning:{0}').format(model.n_similarity('morning', 'morning'))
print('morning vs afternoon:{0}').format(model.n_similarity('morning', 'afternoon'))
print('morning vs hello:{0}').format(model.n_similarity('morning', 'hello'))
print('morning vs shell:{0}').format(model.n_similarity('morning', 'shell'))


# 运行结果
morning vs morning:1.0
morning vs afternoon:0.871482
morning vs hello:0.731609
morning vs shell:0.709714

调试技巧

在开发调试的过程中,会出现错误,需要重新运行程序。如果每次修改后,都从头开始执行,肯定会消耗很多无用的时间。比如,预处理后的文本结果和word2vec的训练参数,这些中间结果可以保持下来,当遇到问题时,就可以从文件中读取结果,而不需要每次都从头开始。

gensim库word2vec的使用详解

from gensim.models import Word2Vec 
model = Word2Vec(sentences, sg=1, size=100, window=5, min_count=5, negative=3, sample=0.001, hs=1, workers=4)

# 训练后的模型保存与加载
model.save(fname) 
model = Word2Vec.load(fname)

# 模型使用(词语相似度计算等)
model.most_similar(positive=['woman', 'king'], negative=['man']) 
#输出[('queen', 0.50882536), ...] 
  
model.doesnt_match("breakfast cereal dinner lunch".split())  # 找出不匹配的词语
#输出'cereal' 
  
model.similarity('woman', 'man')  # 两个词的相似性距离
#输出0.73723527 
  
model['computer']     # 输出单词向量
#输出array([-0.00449447, -0.00310097, 0.02421786, ...], dtype=float32)

参数解释:

1.sg=1是skip-gram算法,对低频词敏感;默认sg=0为CBOW算法。

2.size是输出词向量的维数,值太小会导致词映射因为冲突而影响结果,值太大则会耗内存并使算法计算变慢,一般值取为100到200之间。

3.window是句子中当前词与目标词之间的最大距离,3表示在目标词前看3-b个词,后面看b个词(b在0-3之间随机)。

4.min_count是对词进行过滤,频率小于min-count的单词则会被忽视,默认值为5。

5.negative和sample可根据训练结果进行微调,sample表示更高频率的词被随机下采样到所设置的阈值,默认值为1e-3。

6.hs=1表示层级softmax将会被使用,默认hs=0且negative不为0,则负采样将会被选择使用。

7.workers控制训练的并行,此参数只有在安装了Cpython后才有效,否则只能使用单核。

详细参数说明可查看word2vec源代码。