当前位置:   article > 正文

gensim 训练Word2vec终极使用_# 训练模型 model.train(sentences, total_examples=model

# 训练模型 model.train(sentences, total_examples=model.corpus_count, epochs=

首先要分词成词组成的句子。

1、训练 模型代码 :

word2vec.Word2Vec(sens_list, min_count=5, iter=20, sg=1,workers=int(mp.cpu_count()*0.7))

也可以是

  1. from gensim.models import Word2Vec
  2. sentences = [["cat", "say", "meow"], ["dog", "say", "woof"]]
  3. model = Word2Vec(min_count=1)
  4. model.build_vocab(sentences) # prepare the model vocabulary
  5. model.train(sentences, total_examples=model.corpus_count, epochs=model.iter) # train word vectors
  6. (1, 30)

2、模型保存 

model.save('corpus.model')

corpus.model是自己命名的模型名。注意:这 三个文件在一起才是模型。

corpus.model   
corpus.model.wv.vectors.npy   
corpus.model.trainables.syn1neg.npy  

3、如果有 大量语料 ,就 自己训练吧。但是一般没有大量语料,要更新训练update_model

  1. gensim.models.Word2Vec.load('corpus.model') #模型三个文件都在不然报错
  2. model.build_vocab(sens_list, update=True) # 更新词汇表
  3. model.train(sens_list, total_examples=len(sens_list),
  4. epochs=5) # epoch=iter语料库的迭代次数;(默认为5) total_examples:句子数。

这里有个注意:腾讯开源的word2vec是没有以上三个文件组成的预训练模型的。他开源的一个个结果文件,也就是说每个词语对应的 向量的字典。

4、使用模型
 

  1. model.most_similar('微信')
  2. model.wv['微信']

分词提供一个多进程分词的代码

  1. def segment(text):
  2. text = text.strip()
  3. text = unicodedata.normalize('NFC',text)
  4. text = jieba.cut(text)
  5. return text
  6. # 多进程处理文本
  7. def multiprocess_wenlp(data_file):
  8. with codecs.open(data_file,'r',encoding='utf-8') as f:
  9. lines = f.readlines()
  10. f.close()
  11. pool = Pool(processes=int(mp.cpu_count()*0.7))
  12. t1 = time.time()
  13. res = pool.map(segment,lines)
  14. pool.close() # 进程池关闭
  15. pool.join() # 等待子进程关闭
  16. print("并行处理花费时间{t}s".format(t=time.time()-t1))
  17. out_temp_file = os.path.splitext(data_file)[0] + '_temp.txt'
  18. out_file = os.path.splitext(data_file)[0]+'_clean.txt'
  19. with open(out_temp_file,'w',encoding='utf-8') as f:
  20. for line in res:
  21. if len(line) > 0:
  22. line = line.strip()
  23. f.write(line+'\n')
  24. cmd = "sort -n %s| uniq > %s"%(out_temp_file,out_file)
  25. os.system(cmd)

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/351871
推荐阅读
相关标签
  

闽ICP备14008679号