Why can't I reproduce my results in keras using random seed?

I was doing a task using RNN to predict a time series movement.

I want to make my results reproducible. So I strictly followed this post:

My code are as follows:

# 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)

tf.compat.v1.set_random_seed(seed_value)

tf.random.set_seed(seed_value)

# 5. Configure a new global `tensorflow` session

# for later versions:
session_conf = tf.compat.v1.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)
sess = tf.compat.v1.Session(graph=tf.compat.v1.get_default_graph(), config=session_conf)
tf.compat.v1.keras.backend.set_session(sess)

However, every time I ran my codes, I still got a different result, what could the reasons be?

Have you put the same random seed in each step? otherwise, to reproduce the same results, you can create the function described below and pass the seed at each step

def reset_seed(seed_value):
    np.random.RandomState(seed_value)
    tf.compat.v1.set_random_seed(seed_value)
    tf.random.set_seed(seed_value)

Thank you!

1 Like

We have the option to use the tf.keras.utils.set_random_seed from TF 2.7 to set all random seeds for the program (Python, NumPy and Tensorflow). Please see the following for more information

Thank you!

1 Like