python3下如何使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的环境变量。

    接下来就是设置PYTHONHASHSEED的环境变量。在设置环境变量时,在python程序内通过os.environ好像并不能起到作用,必须把PYTHONHASHSEED设置到环境变量中。

右击计算机(我的电脑)-》选择属性-》在弹出的面板中选择高级系统设置-》选择环境变量

在用户变量哪里新建一个用户变量,添加PYTHONHASHSEED,并随机设置一个整数值就可以了。

python3下如何使Word2Vec每次运行结果一致_第1张图片

然后确定退出,重新运行python程序,发现每次跑出结果一致,问题解决。


你可能感兴趣的:(python,Data)