Reproducible results using Keras with TensorFlow backend

前端 未结 3 1034
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-10 04:56

I am using Keras to build a deep learning LSTM model, using TensorFlow backend. Each time I run the model, the result is different. Is there a way to fix the seed to create

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-10 05:37

    Basically, the key idea of making the result reproducible is to disable GPU. This is very important. To do this, just include

    import os
    import tensorflow as tf
    import numpy as np
    import random as rn
    
    os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
    os.environ["CUDA_VISIBLE_DEVICES"] = ""
    
    sd = 1 # Here sd means seed.
    np.random.seed(sd)
    rn.seed(sd)
    os.environ['PYTHONHASHSEED']=str(sd)
    
    from keras import backend as K
    config = tf.ConfigProto(intra_op_parallelism_threads=1,inter_op_parallelism_threads=1)
    tf.set_random_seed(sd)
    sess = tf.Session(graph=tf.get_default_graph(), config=config)
    K.set_session(sess)
    

    at the very beginning your code. Hope this can help you.

提交回复
热议问题