Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the fixed random seed in numpy?

Tags:

python

numpy

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)

like image 682
BhishanPoudel Avatar asked Dec 02 '22 09:12

BhishanPoudel


2 Answers

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

np.random.seed(42)
like image 60
orlp Avatar answered Dec 03 '22 22:12

orlp


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.

like image 34
Fei Yao Avatar answered Dec 03 '22 21:12

Fei Yao