利用word2vec,对短文本做文本相似

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_39672386/article/details/82189923

最近,刚接触NLP,看了不少大佬们的文章,很受启发,在此记录一下,来作备忘。有错误的地方,还请不吝赐教,毕竟我是萌新一枚。

需要工具:jieba,gensim

  下面直接开始正文:

第一步:准备语料

我的文本都是短文本,比如“昨天配电运维二班有多少人在线?”,整理好以后保存到train_data.json.

# 第一步,制作语料(训练数据)
corpus=[]
with open(r'F:\pycode\RasaNluDemo\Rasa_NLU_Chi\recommen\training_data.json', 'r', encoding='utf-8')as load_f:
    load_dict = json.load(load_f)
    for i in range(len(load_dict)):
        corpus.append(load_dict[i])

第二步:分词

分词这里用的是jieba分词,还有就是去掉常用的停用词。将分词好的语料保存在corpus.txt中。

with open('corpus.txt', 'a', encoding='utf-8') as f:

    for i in range(len(corpus)):
        words = jieba.cut(corpus[i])
    #print("words", words)
        for word in words:
            if word not in stopwords:
                f.write(word + ' ')
        f.write('\n')

第三步:word2vec模型训练

在这一步中我直接引用gensim库中模型来训练。关于gensim的用法可自行百度。将训练好的模型保存到“./model/w2v.mod”

#引入gensim
from gensim.models.word2vec import LineSentence, Word2Vec
#模型训练
sentences = LineSentence("corpus.txt")
model = Word2Vec(sentences, min_count=1, iter=1000)
model.save("./model/w2v.mod")

第四步:求输入文本与语料中相似的文本

输入文本为:昨天抄核收三班有多少人查看菜单?

遍历语料库,如果score>0.8,则认为文本相似。

target = "./corpus.txt"  #语料
model = "./model/w2v.mod" # word2vec模型
model_w2v = Word2Vec.load(model)
candidates = []
with open(target, encoding='utf-8')as f:
    for line in f:
        candidates.append(line.strip().split()) #将语料放到列表中便于操作
text = "昨天抄核收三班有多少人查看菜单?" #待匹配文本
words = list(jieba.cut(text.strip())) #分词
flag = False
word = []
for w in words:
    if w not in model_w2v.wv.vocab:
        print("input word %s not in dict. skip this turn" % w)
    else:
        word.append(w)
# 文本匹配
res = []
index = 0
for candidate in candidates:
    #print("candidate", candidate)
    for c in candidate:
        if c not in model_w2v.wv.vocab:
            print("candidate word %s not in dict. skip this turn" % c)
            flag = True
    if flag:
        break
    score = model_w2v.n_similarity(word, candidate)
    resultInfo = {'id': index, "score": score, "text": " ".join(candidate)}
    res.append(resultInfo)
    index += 1
res.sort(key=lambda x: x['score'], reverse=True) #进行排序

# k = 0
result = [] #存放最终结果
for i in range(len(res)):
   if res[i]['score'] > 0.80:  # 认为文本相似
        dict_temp = {res[i]['id']: res[i]['text'], "score": res[i]['score']}
        result.append(dict_temp)

最终结果为:

#最终结果
result=[{293: '昨天 抄 核收 班有 人 查看 菜单', 'score': 0.900805}, 
{13: '昨天 抄 核收 二班 人 查看 菜单', 'score': 0.89326227}, 
{292: '昨天 抄 核收 班有 人 在线', 'score': 0.8441039}, 
{12: '昨天 抄 核收 二班 人 在线', 'score': 0.8358532}, 
{23: '昨天 急修 班有 人 查看 菜单', 'score': 0.820235}]

猜你喜欢

转载自blog.csdn.net/weixin_39672386/article/details/82189923