6

I was believing that setting a seed always gives the same result. But I got different result each times.How to set the seed so that we get the same result each time?

Here is the MWE:

import numpy as np
import pandas as pd


random_state = 100
np.random.state = random_state
np.random.seed = random_state

mu, sigma = 0, 0.25
eps = np.random.normal(mu,sigma,size=100)
print(eps[0])

I get different result each times.

Update:

I can not use np.random.seed(xxx)

BhishanPoudel
  • 15,974
  • 21
  • 108
  • 169

2 Answers2

20

np.random.seed is a function, which you need to call, not assign to it. E.g.:

np.random.seed(42)
orlp
  • 112,504
  • 36
  • 218
  • 315
8

np.random.seed is function that sets the random state globally. As an alternative, you can also use np.random.RandomState(x) to instantiate a random state class to obtain reproducibility locally. Adapted from your code, I provide an alternative option as follows.

import numpy as np
random_state = 100
rng=np.random.RandomState(random_state )
mu, sigma = 0, 0.25
eps = rng.normal(mu,sigma,size=100) # Difference here
print(eps[0])

More details on np.random.seed and np.random.RandomState can be found here.

Fei Yao
  • 1,502
  • 10
  • 10