使用genism训练词向量【转载】

转自:https://blog.csdn.net/qq_16912257/article/details/79099581

https://blog.csdn.net/thriving_fcl/article/details/51406780

1.简单使用

from gensim.models import word2vec

sents = [
'I am a good student'.split(),
'Good good study day day up'.split()
]
model = word2vec.Word2Vec(sents, size=100, window=5, min_count=2, workers=10)
# 打印单词'good'的词向量
print(model.wv.word_vec('good'))
# 打印和'good'相似的前2个单词
print(model.wv.most_similar('good', topn=2))
# 保存模型到文件
model.save('w2v.model')

参数:

  • size:词向量输出维度
  • window:上下文窗口
  • min_count:忽略词频小于此阈值的单词
  • workers:使用的线程数

2.增量训练

def retrain(data_file, old_model_file, new_model_file):
    sents = XXX
    model = word2vec.Word2Vec.load(old_model_file)
    model.build_vocab(sents, update=True)
    model.train(sents, total_examples=model.corpus_count, epochs=model.iter)
    model.save(new_model_file)

3.大语料库输入

将语料都转换为一个python的list作为输入是很方便,但是如果输入的语料特别大,大到内存都装不下,就不能采用这种方式。gensim的API并不要求sentences必须是list对象,只要输入的sentences是iterable的就行,那我们只要一次载入一个句子,训练完之后再将其丢弃,内存就不会因为语料过大而不够了。我们通过下面的代码就可以生成一个iterator。事先已经将训练语料分词,词与词之间采用空格分开,并保存在一个文档里。

class sentences_generator():
    def __init__(self, filename):
        self.filename = filename

    def __iter__(self):
        for line in open(self.filename):
            sentence = line.rstrip().split(' ')
            yield sentence

猜你喜欢

转载自www.cnblogs.com/BlueBlueSea/p/10732160.html