1 Word2vec模型复现问题
1.1 问题描述
我在对word2vec模型(基于
gensim.models.Word2Vec
)进行实验的时候发现,在设置了random和numpy的种子后,结果依旧无法复现。
主要表现在生成的词向量是随机的。所以我猜测问题出在是word2vec模型生成部分。
1.2 解决
Seed for the random number generator. Initial vectors for each word are seeded with a hash of the concatenation of word +. Note that for a fully deterministically-reproducible run, you must also limit the model to a single worker thread (
str(seed)
), to eliminate ordering jitter from OS thread scheduling. (In Python 3, reproducibility between interpreter launches also requires use of the
workers=1
environment variable to control hash randomization).[2]
PYTHONHASHSEED
在
gensim.models.Word2Vec
的初始化部分,对于可选参数
seed
有以上的描述。里面提供了解决我问题的答案:
首先word2vec模型对词向量的初始化是对“词+str(seed)”进行hash运算。因此要复现模型需要保证seed和python环境变量中的hash种子(
PYTHONHASHSEED
)固定。另外提到,为了消除多线程的影响,还要将算法设为单线程(
workers=1
)。以上三点保证word2vec模型结果的可复现性。
2 PYTHONHASHSEED的设置问题
2.1 问题描述
word2vec模型复现的问题找到了,设置环境变量
应该可以复现了吧。
发现还是不行,在python代码里设置环境变量
PYTHONHASHSEED
不起作用。
2.2 解决
一些环境变量是在python解释器开启前处理,无法在程序中动态修改[3,4]。
因此只能通过命令行进行设置。
# 正确的设置方式——by 命令行
PYTHONHASHSEED=0 python mycode.py
3 省流助手(总结)
- 固定
seed
- 固定
PYTHONHASHSEED
- 单线程
参考资料
[1] Ensure the gensim generate the same Word2Vec model for different runs on the same data - Stackoverflow
[2] gensim/models/word2vec: seed - Github
[3] Can-os-environpythonhashseed-be-set-dynamically-from-within-an-application - Stackoverflow
[4] Environment variables - Python Docs