最近在学习使用gensim.models.word2vec.Word2Vec时发现一个奇怪的问题,那就是每次运行出来的结果不一致,这使得程序复现带来了很多麻烦。下面说一下我的解决方案。
#### Word2Vec的官方文档,在seed参数哪里可以发现这样的解释:
seed (int) – Seed for the random number generator. Initial vectors for each word are seeded with a hash of the concatenation of word + str(seed). Note that for a fully deterministically-reproducible run, you must also limit the model to a single worker thread (workers=1), to eliminate ordering jitter from OS thread scheduling. (In Python 3, reproducibility between interpreter launches also requires use of the PYTHONHASHSEED environment variable to control hash randomization)
也就是说在python2中想要使Word2Vec每次运行结果一致,只要设置seed并且将workers设为1就可以了,但是在python3中还要设置PYTHONHASHSEED的环境变量。
from gensim.models.word2vec import Word2Vec
model = Word2Vec(sentences, vector_size=200, window=5, min_count=1, workers=1, seed=1)
接下来就是设置PYTHONHASHSEED的环境变量。在设置环境变量时,在python程序内通过os.environ好像并不能起到作用,必须把PYTHONHASHSEED设置到环境变量中。
右击计算机(我的电脑)-》选择属性-》在弹出的面板中选择高级系统设置-》选择环境变量
在用户变量哪里新建一个用户变量,添加PYTHONHASHSEED,并随机设置一个整数值就可以了
然后确定退出,重新运行python程序,发现每次跑出结果一致,问题解决。