如何从经过训练的 world2vec 模型 gensim 中取回超参数?

问题描述

我有一个经过训练的 word2vec 模型,我需要用更多数据进一步训练。我也想使用在为新模型训练模型时使用的相同超参数。但我不想对其进行硬编码。有没有一种方法可以用来获取训练现有模型时使用的超参数。 我正在使用 Gensim word2vec。

解决方法

使用 saveload 方法

模型训练好后,将模型保存到磁盘。对于重新训练,请加载保存的模型,如果新的训练数据中有任何未见过的单词,则更新词汇表,然后重新开始训练。查看官方文档 here

工作示例(内联注释)

from gensim.models import Word2Vec
import numpy as np

# Stage 1
sentences = ["an apple on the tree".split(),"a cat on the table".split()]

model = Word2Vec(min_count=1)
model.build_vocab(sentences)  # prepare the model vocabulary
model.train(sentences,total_examples=model.corpus_count,epochs=2) # Train 
model.save("word2vec.model") # Save the model
s1 = np.sum(model.wv.vectors[0]) # Get the vector sum of 'a' for testing
print (model.wv.vocab)
print ("\n")

# Stage 2
sentences = ["sky is high".split(),"ocean is blue".split()] 

model = Word2Vec.load("word2vec.model") # Load the last saved model
model.build_vocab(sentences,update=True)  # prepare the model vocabulary
model.train(sentences,epochs=2) # Train
# since 'a' is not in new train data its vector(word2vec)) should remain same
assert s1 == np.sum(model.wv.vectors[0]) 
print (model.wv.vocab)

输出:

{'a': <gensim.models.keyedvectors.Vocab at 0x7fd378f84e10>,'an': <gensim.models.keyedvectors.Vocab at 0x7fd378fb7810>,'apple': <gensim.models.keyedvectors.Vocab at 0x7fd378fb7e90>,'cat': <gensim.models.keyedvectors.Vocab at 0x7fd378f84b10>,'on': <gensim.models.keyedvectors.Vocab at 0x7fd3764695d0>,'table': <gensim.models.keyedvectors.Vocab at 0x7fd378f84950>,'the': <gensim.models.keyedvectors.Vocab at 0x7fd376469490>,'tree': <gensim.models.keyedvectors.Vocab at 0x7fd376469b50>}

{'a': <gensim.models.keyedvectors.Vocab at 0x7fd3797f3850>,'an': <gensim.models.keyedvectors.Vocab at 0x7fd376469fd0>,'apple': <gensim.models.keyedvectors.Vocab at 0x7fd375b8efd0>,'blue': <gensim.models.keyedvectors.Vocab at 0x7fd37649a9d0>,'cat': <gensim.models.keyedvectors.Vocab at 0x7fd37649a450>,'high': <gensim.models.keyedvectors.Vocab at 0x7fd37649afd0>,'is': <gensim.models.keyedvectors.Vocab at 0x7fd37649aa90>,'ocean': <gensim.models.keyedvectors.Vocab at 0x7fd37649a7d0>,'on': <gensim.models.keyedvectors.Vocab at 0x7fd375b8ef50>,'sky': <gensim.models.keyedvectors.Vocab at 0x7fd378f79ed0>,'table': <gensim.models.keyedvectors.Vocab at 0x7fd37649a850>,'the': <gensim.models.keyedvectors.Vocab at 0x7fd375b8eed0>,'tree': <gensim.models.keyedvectors.Vocab at 0x7fd378e3c190>}
,

任何完整的 Word2Vec 模型都在其对象属性的某处具有初始创建时提供的每个元参数。

它几乎总是在模型本身上,使用与构造函数参数完全相同的名称。因此,model.window 将返回 window 等 - 因此您可以创建一个新模型,从旧模型中提取每个值。

请注意,在已经训练过的模型上继续训练涉及许多棘手的权衡。

例如,现有模型上的 .build_vocab(...,update=True) 不会对来自所有先前调用的所有单词总数一致地应用 min_count,而是仅针对最新“批次”中的单词总数。

增量更新的正确学习率(alphamin_alpha 值)并未由理论或经验法则明确定义。如果新文本中的词汇和词平衡主要训练一些单词,而不是全部,那么这些最近更新的单词可以任意拉出与没有得到更多训练的早期单词的强可比性对齐。 (mdoel 优化的基础方法,随机梯度下降,当所有训练文本都被给予同等的训练注意力时是最好的基础,没有任何子集在后面开始密集训练。)