frazman
frazman

Reputation: 33243

numpy random not working with seed

import random
seed = random.random()
random_seed  = random.Random(seed)
random_vec = [ random_seed.random() for i in range(10)]

The above is essentially:

np.random.randn(10)

But I am not able to figure out how to set the seed?

Upvotes: 1

Views: 16023

Answers (2)

Roisul
Roisul

Reputation: 21

To put it simply random.seed(value) does not work with numpy arrays. For example,

import random
import numpy as np
random.seed(10)
print( np.random.randint(1,10,10)) #generates 10 random integer of values from 1~10

[4 1 5 7 9 2 9 5 2 4]

random.seed(10)
print( np.random.randint(1,10,10))

[7 6 4 7 2 5 3 7 8 9]

However, if you want to seed the numpy generated values, you have to use np.random.seed(value). If I revisit the above example,

import numpy as np

np.random.seed(10)
print( np.random.randint(1,10,10))

[5 1 2 1 2 9 1 9 7 5]

np.random.seed(10)
print( np.random.randint(1,10,10))

[5 1 2 1 2 9 1 9 7 5]

Upvotes: 2

abarnert
abarnert

Reputation: 365717

I'm not sure why you want to set the seed—especially to a random number, even more especially to a random float (note that random.seed wants a large integer).

But if you do, it's simple: call the numpy.random.seed function.

Note that NumPy's seeds are arrays of 32-bit integers, while Python's seeds are single arbitrary-sized integers (although see the docs for what happens when you pass other types).

So, for example:

In [1]: np.random.seed(0)    
In [2]: s = np.random.randn(10)
In [3]: s
Out[3]:
array([ 1.76405235,  0.40015721,  0.97873798,  2.2408932 ,  1.86755799,
       -0.97727788,  0.95008842, -0.15135721, -0.10321885,  0.4105985 ])
In [4]: np.random.seed(0)
In [5]: s = np.random.randn(10)
In [6]: s
Out[6]:
array([ 1.76405235,  0.40015721,  0.97873798,  2.2408932 ,  1.86755799,
       -0.97727788,  0.95008842, -0.15135721, -0.10321885,  0.4105985 ])

Same seed used twice (I took the shortcut of passing a single int, which NumPy will internally convert into an array of 1 int32), same random numbers generated.

Upvotes: 8

Related Questions