Random Sampling – SolutionsΒΆ

Solutions demonstrating NumPy’s random number generation functions. Multiple approaches are shown where applicable – for example, np.random.randn(), np.random.standard_normal(), and np.random.normal() all generate normally distributed values with slightly different interfaces.

import numpy as np
np.__version__
__author__ = 'kyubyong. longinglove@nate.com'

Simple Random DataΒΆ

Solutions using np.random.rand(), np.random.randn(), np.random.standard_normal(), np.random.normal(), np.random.randint(), and np.random.choice() for generating random arrays.

Q1. Create an array of shape (3, 2) and populate it with random samples from a uniform distribution over [0, 1).

np.random.rand(3, 2) 
# Or np.random.random((3,2))

Q2. Create an array of shape (1000, 1000) and populate it with random samples from a standard normal distribution. And verify that the mean and standard deviation is close enough to 0 and 1 repectively.

out1 = np.random.randn(1000, 1000)
out2 = np.random.standard_normal((1000, 1000))
out3 = np.random.normal(loc=0.0, scale=1.0, size=(1000, 1000))
assert np.allclose(np.mean(out1), np.mean(out2), atol=0.1)
assert np.allclose(np.mean(out1), np.mean(out3), atol=0.1)
assert np.allclose(np.std(out1), np.std(out2), atol=0.1)
assert np.allclose(np.std(out1), np.std(out3), atol=0.1)
print np.mean(out3)
print np.std(out1)

Q3. Create an array of shape (3, 2) and populate it with random integers ranging from 0 to 3 (inclusive) from a discrete uniform distribution.

np.random.randint(0, 4, (3, 2))

Q4. Extract 1 elements from x randomly such that each of them would be associated with probabilities .3, .5, .2. Then print the result 10 times.

x = [b'3 out of 10', b'5 out of 10', b'2 out of 10']
for _ in range(10):
    print np.random.choice(x, p=[.3, .5, .2])

Q5. Extract 3 different integers from 0 to 9 randomly with the same probabilities.

np.random.choice(10, 3, replace=False)

PermutationsΒΆ

Solutions using np.random.shuffle() (in-place) and np.random.permutation() (returns new array) for randomizing element order.

Q6. Shuffle numbers between 0 and 9 (inclusive).

x = np.arange(10)
np.random.shuffle(x)
print x
# Or
print np.random.permutation(10)

Random GeneratorΒΆ

Solution using np.random.seed() for reproducible random number generation.

Q7. Assign number 10 to the seed of the random generator so that you can get the same value next time.

np.random.seed(10)