LoginSignup
1
1

More than 3 years have passed since last update.

kerasで再現性の担保(2020/09/22現在)

Last updated at Posted at 2020-09-22

導入

kerasで学習の再現をするとき検索して最初に出てくる情報や公式の日本語ドキュメントが古いバージョンのやり方で,現在は方法が変わっているので記録.

バージョン

  • Python 3.7.6
  • Keras 2.3.1
  • tensorflow 2.2.0

再現性の担保

環境変数の設定

python3.2.3以降はPYTHONHASHSEEDの値を固定することでpythonのハッシュベースの操作の再現性を担保できる.

export PYTHONHASHSEED=0

また,PYTHONHASHSEEDはコード内ではなくプログラムの実行前に設定する必要がある.

$ python -c 'import os;os.environ["PYTHONHASHSEED"]="0";print(hash("keras"))'  
2834998937574676049  
$ python -c 'import os;os.environ["PYTHONHASHSEED"]="0";print(hash("keras"))'  
-1138434705774533911  
$ PYTHONHASHSEED=0 python -c 'print(hash("keras"))'  
4883664951434749476  
$ PYTHONHASHSEED=0 python -c 'print(hash("keras"))'  
4883664951434749476

他の方の記事では環境変数を設定しなくても再現できたとあるのでもしかしたら必要ないかもいれない.
https://sanshonoki.hatenablog.com/entry/2019/01/15/230054

ライブラリのシード値を固定

Kersa公式ドキュメントページから抜粋.このあたりのコードが以前のバージョンと変わっている.

import numpy as np  

import tensorflow as tf  
import random as python_random  

# The below is necessary for starting Numpy generated random numbers  
# in a well-defined initial state.  
np.random.seed(123)  

# The below is necessary for starting core Python generated random numbers  
# in a well-defined state.  
python_random.seed(123)  

# The below set_seed() will make random number generation  
# in the TensorFlow backend have a well-defined initial state.  
# For further details, see:  
# https://www.tensorflow.org/api_docs/python/tf/random/set_seed  
tf.random.set_seed(1234)  

# Rest of code follows ...

最後に

ちゃんとドキュメントが最新バージョンのものに更新されているか確認する.(戒め)

参考ページ

Keras FAQ: How can I obtain reproducible results using Keras during development?(2020/09/22閲覧)

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1