问题描述
在 Gensim documentation 中,它指出
TL;DR:主要区别在于 KeyedVectors 不支持进一步训练。另一方面,通过去除训练所需的内部数据结构,KeyedVectors 提供了更小的 RAM 占用空间和更简单的界面。
将 KeyedVectors 保存到文件中,然后修改它们,然后将它们加载回模型并继续如下训练是否安全?
class MyCallback(CallbackAny2Vec):
def on_epoch_end(self,model):
model.wv.save(temp_out_filepath)
# for Now,do nothing (eventually I want to modify these vectors slightly)
model.wv = KeyedVectors.load(temp_out_filepath,mmap="r")
当我尝试此操作时,在重新加载后恢复训练时出现分段错误。但是,我不确定为什么按照文档这样做是不安全的,因为底层模型保持不变。
对于 MVE,请考虑以下代码:
from gensim.models import Word2Vec
from gensim.models.callbacks import CallbackAny2Vec
from gensim.models.keyedvectors import KeyedVectors
from gensim.models.word2vec import Linesentence
corpus_filepath = "corpus.txt"
temp_out_filepath = "temp_out.vectors"
out_filepath = "gensimw2v_baseline.txt"
class MyCallback(CallbackAny2Vec):
def on_epoch_end(self,model):
print("Saving vectors and reloading vectors for fun...")
model.wv.save(temp_out_filepath)
model.wv = KeyedVectors.load(temp_out_filepath,mmap="r")
print("Done reloading,continuing!")
callback = MyCallback()
model = Word2Vec(size=300,window=5,min_count=25,workers=64)
with open(corpus_filepath,"r") as corpus_file:
sentences = Linesentence(corpus_file)
print("Building vocab...")
model.build_vocab(sentences=sentences)
print("Beginning training...")
model.train(
sentences=sentences,epochs=5,total_words=model.corpus_total_words,callbacks=[callback],)
print("Saving word vectors...")
model.wv.save_word2vec_format(out_filepath)
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)