简体   繁体   中英

Performance difference between numpy.random and random.random in Python

I want to see what random number generator package is faster in my neural network.

I am currently changing a code from github, in which both numpy.random and random packages are used to generate random integers, random choices, random samples etc.

The reason that I am changing this code is that for research purposes I would like to set a global seed to be able to compare accuracy performance for different settings of hyperparameters. The problem is that at this moment I have to set 2 global seeds, both for the random package and for the numpy package. Ideally, I would like to set only one seed as drawings from two sequences of random number generators might become correlated more quickly.

However, I do not know what package will perform better (in terms of speed): numpy or random. So I would like to find seeds for both packages that correspond to exactly the same Mersenne Twister sequence. In that way, the drawings for both models are the same and therefore also the number of iterations in each gradient descent step are the same, leading to a difference in speed only caused by the package I use.

I could not find any documentation on pairs of seeds that end up in the same random number sequence for both packages and also trying out all kind of combinations seems a bit cumbersome.

I have tried the following:

np.random.seed(1)
numpy_1=np.random.randint(0,101)
numpy_2=np.random.randint(0,101)
numpy_3=np.random.randint(0,101)
numpy_4=np.random.randint(0,101)
for i in range(20000000):
    random.seed(i)
    random_1=random.randint(0,101)
    if random_1==numpy_1:
        random_2=random.randint(0,101)
        if random_2==numpy_2:
            random_3=random.randint(0,101)
            if random_3==numpy_3:
                random_4=random.randint(0,101)
                if random_4==numpy_4:
                    break
print(np.random.randint(0,101))
print(random.randint(0,101))

But this did not really work, as could be expected.

numpy.random and python random work in different ways, although, as you say, they use the same algorithm.

In terms of seed : You can use the set_state and get_state functions from numpy.random (in python random called getstate and setstate ) and pass the state from one to another. The structure is slightly different (in python the pos integer is attached to the last element in the state tuple). See the docs for numpy.random.get_state() andrandom.getstate() :

import random
import numpy as np
random.seed(10)
s1 = list(np.random.get_state())
s2 = list(random.getstate())

s1[1] = np.array(s2[1][:-1]).astype('int32')
s1[2] = s2[1][-1]

np.random.set_state(tuple(s1))

print(np.random.random())
print(random.random())
>> 0.5714025946899135
0.5714025946899135

In terms of efficiency : it depends on what you want to do, but numpy is usually better because you can create arrays of elements without the need of a loop:

%timeit np.random.random(10000)
142 µs ± 391 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit [random.random() for i in range(10000)]
1.48 ms ± 2.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In terms of "randomness" , numpy is (according to their docs ), also better:

Notes: The Python stdlib module "random" also contains a Mersenne Twister pseudo-random number generator with a number of methods that are similar to the ones available in RandomState . RandomState , besides being NumPy-aware, has the advantage that it provides a much larger number of probability distributions to choose from.

Consider the following dirty hack:

import random
import numpy as np

random.seed(42)
np.random.seed(42)

print(random.random(), np.random.random())

# copy numpy random module state to python random module
a = random.getstate()
b = np.random.get_state()
a2 = (a[0], tuple(int(val) for val in list(b[1]) + [a[1][-1]]), *a[2:])
random.setstate(a2)

print(random.random(), np.random.random())

Output:

0.6394267984578837 0.3745401188473625  # different
0.9507143064099162 0.9507143064099162  # same

Not sure if this way really consistent across all the possibilities of both implementations.

Duplication of this post

Answer depends of the needs :
- Cryptography / security : secrets
- Scientific Research : numpy
- Common Use : random

Just a quick recap. NumPy's np.random.randint(a, b) is different from random.randint(a, b) .

print(np.random.randint(0,101)) # return betweem [0, 101), 101 exclusive
print(random.randint(0,101)) # return between [0, 101], 101 inclusive

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM