developer tip

케 라스에서 재현 가능한 결과를 얻는 방법

optionbox 2020. 12. 2. 08:29
반응형

케 라스에서 재현 가능한 결과를 얻는 방법


나는 다른 결과 (테스트 정확도) 내가 실행할 때마다 얻을 imdb_lstm.pyKeras 프레임 워크 (에서 예를 https://github.com/fchollet/keras/blob/master/examples/imdb_lstm.py ) 코드가 포함되어 np.random.seed(1337)있는 keras 전에, 상단에서을 수입. 매 실행마다 다른 숫자를 생성하는 것을 방지해야합니다. 내가 무엇을 놓치고 있습니까?

업데이트 : 재현 방법 :

  1. Keras 설치 ( http://keras.io/ )
  2. https://github.com/fchollet/keras/blob/master/examples/imdb_lstm.py 를 몇 번 실행합니다 . 모델을 훈련시키고 테스트 정확도를 출력합니다.
    예상 결과 : 테스트 정확도는 모든 실행에서 동일합니다.
    실제 결과 : 테스트 정확도는 매 실행마다 다릅니다.

업데이트 2 : MinGW / msys, 모듈 버전 :
theano 0.7.0
numpy 1.8.1
scipy 0.14.0c1을 사용 하여 Windows 8.1에서 실행 중입니다.

UPDATE3 : 문제를 조금 좁혔습니다. GPU로 예제를 실행하면 (set theano flag device = gpu0) 매번 다른 테스트 정확도를 얻지 만 CPU에서 실행하면 모든 것이 예상대로 작동합니다. 내 그래픽 카드 : NVIDIA GeForce GT 635)


Keras 문서에서 답을 찾을 수 있습니다 : https://keras.io/getting-started/faq/#how-can-i-obtain-reproducible-results-using-keras-during-development .

간단히 말해서, 한 컴퓨터 / 노트북의 CPU에서 Python 스크립트로 재현 가능한 결과를 얻을 수 있도록 하려면 다음을 수행해야합니다.

  1. PYTHONHASHSEED고정 값으로 환경 변수 설정
  2. 설정 python고정 된 값에 내장 된 의사 난수 생성기를
  3. 설정된 numpy고정 값으로 의사 난수 생성기를
  4. 설정된 tensorflow고정 값으로 의사 난수 생성기를
  5. 새 글로벌 tensorflow세션 구성

Keras맨 위에 있는 링크를 따라 내가 사용중인 소스 코드는 다음과 같습니다.

# Seed value
# Apparently you may use different seed values at each stage
seed_value= 0

# 1. Set the `PYTHONHASHSEED` environment variable at a fixed value
import os
os.environ['PYTHONHASHSEED']=str(seed_value)

# 2. Set the `python` built-in pseudo-random generator at a fixed value
import random
random.seed(seed_value)

# 3. Set the `numpy` pseudo-random generator at a fixed value
import numpy as np
np.random.seed(seed_value)

# 4. Set the `tensorflow` pseudo-random generator at a fixed value
import tensorflow as tf
tf.set_random_seed(seed_value)

# 5. Configure a new global `tensorflow` session
from keras import backend as K
session_conf = tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)
sess = tf.Session(graph=tf.get_default_graph(), config=session_conf)
K.set_session(sess)

당신이 어떤 지정하지 않아도 물론이다 seed또는 random_state상기 numpy, scikit-learn또는 tensorflow/ keras당신이 있기 때문에 우리는 고정 된 값으로 전 세계적으로 자신의 의사 난수 발생기를 설정 위의 소스 코드를 정확히 파이썬 스크립트에서 사용되는 기능.


Theano의 문서 는 랜덤 변수 시드의 어려움과 왜 각 그래프 인스턴스에 자체 난수 생성기를 시드하는지에 대해 설명합니다.

서로 다른 {{{RandomOp}}} 인스턴스간에 난수 생성기를 공유하면 그래프의 다른 작업에 관계없이 동일한 스트림을 생성하고 {{{RandomOps}}}를 격리하기가 어렵습니다. 따라서 그래프의 각 {{{RandomOp}}} 인스턴스에는 자체 난수 생성기가 있습니다. 이 난수 생성기는 함수에 대한 입력입니다. 일반적인 사용에서는 함수 입력의 새로운 기능 ({{{value}}}, {{{update}}})을 사용하여 각 {{{RandomOp}}}에 대한 rng를 전달하고 업데이트합니다. RNG를 입력으로 전달하면 함수 입력에 액세스하는 일반적인 방법을 사용하여 각 {{{RandomOp}}}의 rng에 액세스 할 수 있습니다. 이 접근 방식에서는 전체 그래프의 결합 된 난수 상태로 작업 할 수있는 기존 메커니즘이 없습니다.

They also provide examples on how to seed all the random number generators.

You can also seed all of the random variables allocated by a RandomStreams object by that object’s seed method. This seed will be used to seed a temporary random number generator, that will in turn generate seeds for each of the random variables.

>>> srng.seed(902340)  # seeds rv_u and rv_n with different seeds each

I finally got reproducible results with my code. It's a combination of answers I saw around the web. The first thing is doing what @alex says:

  1. Set numpy.random.seed;
  2. Use PYTHONHASHSEED=0 for Python 3.

Then you have to solve the issue noted by @user2805751 regarding cuDNN by calling your Keras code with the following additional THEANO_FLAGS:

  1. dnn.conv.algo_bwd_filter=deterministic,dnn.conv.algo_bwd_data=deterministic

And finally, you have to patch your Theano installation as per this comment, which basically consists in:

  1. replacing all calls to *_dev20 operator by its regular version in theano/sandbox/cuda/opt.py.

This should get you the same results for the same seed.

Note that there might be a slowdown. I saw a running time increase of about 10%.


I would like to add something to the previous answers. If you use python 3 and you want to get reproducible results for every run, you have to

  1. set numpy.random.seed in the beginning of your code
  2. give PYTHONHASHSEED=0 as a parameter to the python interpreter

I have trained and tested Sequential() kind of neural networks using Keras. I performed non linear regression on noisy speech data. I used the following code to generate random seed :

import numpy as np
seed = 7
np.random.seed(seed)

I get the exact same results of val_loss each time I train and test on the same data.


This works for me:

SEED = 123456
import os
import random as rn
import numpy as np
from tensorflow import set_random_seed

os.environ['PYTHONHASHSEED']=str(SEED)
np.random.seed(SEED)
set_random_seed(SEED)
rn.seed(SEED)

I agree with the previous comment, but reproducible results sometimes needs the same environment(e.g. installed packages, machine characteristics and so on). So that, I recommend to copy your environment to other place in case to have reproducible results. Try to use one of the next technologies:

  1. Docker. If you have a Linux this very easy to move your environment to other place. Also you can try to use DockerHub.
  2. Binder. This is a cloud platform for reproducing scientific experiments.
  3. Everware. This is yet another cloud platform for "reusable science". See the project repository on Github.

참고URL : https://stackoverflow.com/questions/32419510/how-to-get-reproducible-results-in-keras

반응형