赞
踩
首先要分词成词组成的句子。
1、训练 模型代码 :
word2vec.Word2Vec(sens_list, min_count=5, iter=20, sg=1,workers=int(mp.cpu_count()*0.7))
也可以是
- from gensim.models import Word2Vec
- sentences = [["cat", "say", "meow"], ["dog", "say", "woof"]]
- model = Word2Vec(min_count=1)
- model.build_vocab(sentences) # prepare the model vocabulary
- model.train(sentences, total_examples=model.corpus_count, epochs=model.iter) # train word vectors
- (1, 30)
2、模型保存
model.save('corpus.model')
corpus.model是自己命名的模型名。注意:这 三个文件在一起才是模型。
corpus.model corpus.model.wv.vectors.npy corpus.model.trainables.syn1neg.npy
3、如果有 大量语料 ,就 自己训练吧。但是一般没有大量语料,要更新训练update_model
- gensim.models.Word2Vec.load('corpus.model') #模型三个文件都在不然报错
- model.build_vocab(sens_list, update=True) # 更新词汇表
- model.train(sens_list, total_examples=len(sens_list),
- epochs=5) # epoch=iter语料库的迭代次数;(默认为5) total_examples:句子数。
这里有个注意:腾讯开源的word2vec是没有以上三个文件组成的预训练模型的。他开源的一个个结果文件,也就是说每个词语对应的 向量的字典。
4、使用模型
- model.most_similar('微信')
-
- model.wv['微信']
分词提供一个多进程分词的代码
- def segment(text):
- text = text.strip()
- text = unicodedata.normalize('NFC',text)
- text = jieba.cut(text)
- return text
-
-
- # 多进程处理文本
- def multiprocess_wenlp(data_file):
- with codecs.open(data_file,'r',encoding='utf-8') as f:
- lines = f.readlines()
- f.close()
- pool = Pool(processes=int(mp.cpu_count()*0.7))
- t1 = time.time()
- res = pool.map(segment,lines)
- pool.close() # 进程池关闭
- pool.join() # 等待子进程关闭
- print("并行处理花费时间{t}s".format(t=time.time()-t1))
- out_temp_file = os.path.splitext(data_file)[0] + '_temp.txt'
- out_file = os.path.splitext(data_file)[0]+'_clean.txt'
- with open(out_temp_file,'w',encoding='utf-8') as f:
- for line in res:
- if len(line) > 0:
- line = line.strip()
- f.write(line+'\n')
-
- cmd = "sort -n %s| uniq > %s"%(out_temp_file,out_file)
- os.system(cmd)
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。