天天看點

Word2vec模型複現與PYTHONHASHSEED

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 +

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).[2]

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 省流助手(總結)

  1. 固定

    seed

  2. 固定

    PYTHONHASHSEED

  3. 單線程

參考資料

[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