2017-10-19 3 views
4

Keras 및 ThensorFlow로 결과를 재현 할 수 없다는 문제가 있습니다.결과가 Python에서 Keras 및 TensorFlow로 재현되지 않습니다.

최근에이 문제에 대한 에 해결 방법이 게시 된 것처럼 보이지만 어쨌든 그것은 나를 위해 작동하지 않습니다.

내가 뭘 잘못하고 있니?

나는 MBP 망막 (엔비디아 GPU 제외)에서 주피터 노트를 사용하고 있습니다.

# ** Workaround from Keras Documentation ** 

import numpy as np 
import tensorflow as tf 
import random as rn 

# The below is necessary in Python 3.2.3 onwards to 
# have reproducible behavior for certain hash-based operations. 
# See these references for further details: 
# https://docs.python.org/3.4/using/cmdline.html#envvar-PYTHONHASHSEED 
# https://github.com/fchollet/keras/issues/2280#issuecomment-306959926 

import os 
os.environ['PYTHONHASHSEED'] = '0' 

# The below is necessary for starting Numpy generated random numbers 
# in a well-defined initial state. 

np.random.seed(42) 

# The below is necessary for starting core Python generated random numbers 
# in a well-defined state. 

rn.seed(12345) 

# Force TensorFlow to use single thread. 
# Multiple threads are a potential source of 
# non-reproducible results. 
# For further details, see: https://stackoverflow.com/questions/42022950/which-seeds-have-to-be-set-where-to-realize-100-reproducibility-of-training-res 

session_conf = tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1) 

from keras import backend as K 

# The below tf.set_random_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/set_random_seed 

tf.set_random_seed(1234) 

sess = tf.Session(graph=tf.get_default_graph(), config=session_conf) 
K.set_session(sess) 


# ** Workaround end ** 

# ** Start of my code ** 


# LSTM and CNN for sequence classification in the IMDB dataset 
from keras.models import Sequential 
from keras.layers import Dense 
from keras.layers import LSTM 
from keras.layers.embeddings import Embedding 
from keras.preprocessing import sequence 
from sklearn import metrics 
# fix random seed for reproducibility 
#np.random.seed(7) 

# ... importing data and so on ... 

# create the model 
embedding_vecor_length = 32 
neurons = 91 
epochs = 1 
model = Sequential() 
model.add(Embedding(top_words, embedding_vecor_length, input_length=max_review_length)) 
model.add(LSTM(neurons)) 
model.add(Dense(1, activation='sigmoid')) 
model.compile(loss='mean_squared_logarithmic_error', optimizer='adam', metrics=['accuracy']) 
print(model.summary()) 
model.fit(X_train, y_train, epochs=epochs, batch_size=64) 
# Final evaluation of the model 
scores = model.evaluate(X_test, y_test, verbose=0) 
print("Accuracy: %.2f%%" % (scores[1]*100)) 

파이썬 3.6.3 Anaconda custom (x86_64) | (기본값, Oct 6 2017, 12:04:38) [GCC 4.2.1 호환되는 Clang 4.0.1 (tags/RELEASE_401/final)]

해결 방법은 이미 효과가없는 코드에 포함되어 있습니다.

매번 제가 훈련 부분을 할 때마다 결과가 달라집니다.

Jupyter Notebook의 커널을 재설정 할 때 첫 번째 시간은 첫 번째 시간과 두 번째 시간이 두 번째 시간과 일치합니다.

그래서 난 항상 두 번째 실행 등

그러나에, 첫 번째 실행에서 예를 0.7782에 대해 0.7732을 얻을 것이다 재설정 한 후 커널 재설정없이 결과는 내가 그것을 실행할 때마다 항상 다르다.

나는 어떤 제안에도 도움이 될 것입니다!

+0

출력에'np.random.get_state()'와'rn.getstate()'를 추가 할 수 있습니까? GPU 또는 CPU를 사용합니까? 'python'으로 스크립트를 사용해 볼 수 있습니까? – Maxim

답변

1

정확히 동일한 문제가 있었으며 모델을 실행할 때마다 tensorflow 세션을 닫고 다시 시작하여 문제를 해결할 수있었습니다. 귀하의 경우는 다음과 같아야합니다

#START A NEW TF SESSION 
np.random.seed(0) 
tf.set_random_seed(0) 
sess = tf.Session(graph=tf.get_default_graph()) 
K.set_session(sess) 

embedding_vecor_length = 32 
neurons = 91 
epochs = 1 
model = Sequential() 
model.add(Embedding(top_words, embedding_vecor_length, input_length=max_review_length)) 
model.add(LSTM(neurons)) 
model.add(Dense(1, activation='sigmoid')) 
model.compile(loss='mean_squared_logarithmic_error', optimizer='adam', metrics=['accuracy']) 
print(model.summary()) 
model.fit(X_train, y_train, epochs=epochs, batch_size=64) 
# Final evaluation of the model 
scores = model.evaluate(X_test, y_test, verbose=0) 
print("Accuracy: %.2f%%" % (scores[1]*100)) 

#CLOSE TF SESSION 
K.clear_session() 

는 다음 코드를 실행하고 GPU와 tensorflow 백엔드 사용하여 재현 가능한 결과했다 :

print datetime.now() 
for i in range(10): 
    np.random.seed(0) 
    tf.set_random_seed(0) 
    sess = tf.Session(graph=tf.get_default_graph()) 
    K.set_session(sess) 

    n_classes = 3 
    n_epochs = 20 
    batch_size = 128 

    task = Input(shape = x.shape[1:]) 
    h = Dense(100, activation='relu', name='shared')(task) 
    h1= Dense(100, activation='relu', name='single1')(h) 
    output1 = Dense(n_classes, activation='softmax')(h1) 

    model = Model(task, output1) 
    model.compile(loss='categorical_crossentropy', optimizer='Adam') 
    model.fit(x_train, y_train_onehot, batch_size = batch_size, epochs=n_epochs, verbose=0) 
print(model.evaluate(x=x_test, y=y_test_onehot, batch_size=batch_size, verbose=0)) 
K.clear_session() 

을 그리고이 출력을 얻을 :

2017-10-23 11:27:14.494482 
0.489712882132 
0.489712893813 
0.489712892765 
0.489712854426 
0.489712882132 
0.489712864011 
0.486303713004 
0.489712903398 
0.489712892765 
0.489712903398 

을 내가 이해 한 것은 tf 세션을 닫지 않으면 (새로운 커널에서 실행함으로써), 동일한 "seeded"배포판을 계속 샘플링한다는 것입니다.

+0

마치 가까이에 있어도 점수에 약간의 차이가있는 것처럼 보입니다. 지금은 확률에 따라 순위를 매길 필요가 있기 때문에 작은 차이도 중요합니다 (따라서이 목적을 위해 Theano 백엔드로 전환했습니다). 하지만 고마워! 나는 내가 얻은 결과를 시도 할 것이다. –

관련 문제