1
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?

2
  • Why do you want to set the seed? Especially to a random number? Commented Dec 13, 2014 at 4:04
  • Setting seeds is important for reproducibility in some analyses Commented Apr 25, 2022 at 15:41

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You are assigning to s just once here, hence s will always be the same independently of setting seed a second time.
you forgot to assign a second time s = np.random.randn(10), however, the end result shall be the same.
2

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.