Complete Numpy Random Tutorial – Rand, Randn, Randint, Normal, Uniform, Binomial and more

Table of Contents

Numpy Random

In machine learning and data science, at times you would be required to work with randomly generated data. In this post, we will see how we can use different methods of numpy random to generate random integers or a numpy array with random integers. We are going to cover the following –

1) numpy random seed

2) numpy random normal

3) numpy random rand

4) numpy random randn

5) numpy random choice

6) numpy random uniform

7) numpy random binomial

8) numpy random poisson

9) numpy random randint

10) numpy random sample

Before we start with this tutorial, let us first import numpy.

Numpy Import

In [1]:
import numpy as np

1) np.random.seed

Numpy Random generates pseudo-random numbers, which means that the numbers are not entirely random. They only appear random but there are algorithms involved in it.

If we initialize the initial conditions with a particular seed value, then it will always generate the same random numbers for that seed value. This means numpy random is deterministic for a given seed value.

np.random.seed can be used to set the seed value before generating numpy random arrays or random numbers.

Syntax

np.random.seed(seed=None)

seed (optional) – The input is int or 1-d array_like.

Setting the Numpy Seed Value

In [72]:
np.random.seed(5)

2) np.random.normal

np.random.normal returns a random numpy array or scalar whose elements are randomly drawn from a normal distribution

Syntax

np.random.normal(loc=0.0, scale=1.0, size=None)

loc – It represents Mean (“centre”) of the distribution. It is float or array_like of floats

scale – It represents Standard deviation (spread or “width”) of the distribution. It is float or array_like of floats

size (optional) – It represents the shape of the output array. If the given shape is, e.g., (m, n, k), then m n k samples are drawn. If the size is None (default), a single value is returned, if loc and scale are both scalars. Otherwise, np.broadcast(loc, scale).size samples are drawn.

Example – 1: Creating 1-D Numpy Random Array

In [57]:
np.random.normal(1,1,2)
Out[57]:
array([ 3.2336465 , -0.40779152])

Example – 2: Creating 2-D Numpy Random Array

In [60]:
np.random.normal(2,1,(3,2))
Out[60]:
array([[1.39441865, 1.28409766],
       [2.74850019, 2.03432562],
       [1.68098484, 1.94838727]])

Example – 3: Creating 3-D Numpy Random Array

In [63]:
np.random.normal(2,3,(3,2,4))
Out[63]:
array([[[ 2.40038206, -1.60592695,  2.99413407,  3.01597174],
        [ 6.24667659,  0.01566748, -2.45512535,  4.55757841]],

       [[ 1.98075188,  0.21801424,  4.88015683,  1.08838025],
        [ 3.38653395, -0.61127652,  3.29363281,  0.95027105]],

       [[-0.12289567,  4.20374089,  7.8723445 , -1.62212758],
        [ 7.73655833,  8.64351739,  3.9377977 ,  7.42301642]]])

Example 4: A Random Python Float

In [64]:
np.random.normal(2,3)
Out[64]:
4.563562413316882

3) np.random.rand

np.random.rand returns a random numpy array or scalar whose element(s) are drawn randomly from the normal distribution over [0,1). (including 0 but excluding 1)

It returns a single python float if no input parameter is specified.

Syntax

np.random.rand(d0,d1,d2,.. dn)

d0,d1,d2,.. dn (optional) – It represents the dimension of the required array given as int. It is optional, if not specified, it will return a single python float.

Example 1: Creating 1-D Numpy Random Array

In [11]:
np.random.rand(3)
Out[11]:
array([0.7798154 , 0.45685334, 0.89824928])

Example 2: Creating 2-D Numpy Random Array

In [19]:
np.random.rand(5,3)
Out[19]:
array([[0.17963626, 0.46373528, 0.30762711],
       [0.27334617, 0.45668808, 0.54813439],
       [0.44506229, 0.32059869, 0.92962626],
       [0.78297602, 0.20849134, 0.65793903],
       [0.66985367, 0.45470811, 0.05023272]])

Example 3: Creating 3-D Numpy Random Array

In [16]:
np.random.rand(3,2,4)
Out[16]:
array([[[0.82564261, 0.99100227, 0.3498416 , 0.25349147],
        [0.97474162, 0.8879708 , 0.52644532, 0.48392986]],

       [[0.24771917, 0.55511987, 0.64328105, 0.26636461],
        [0.83461679, 0.19501868, 0.51199488, 0.75963094]],

       [[0.545668  , 0.22256917, 0.51817445, 0.84151684],
        [0.80153195, 0.42129928, 0.49337318, 0.8382367 ]]])

Example 4: A Random Python Float

In [17]:
np.random.rand()
Out[17]:
0.5747916494126569

4) np.random.randn

np.random.randn returns a random numpy array or scalar of sample(s), drawn randomly from the standard normal distribution.

It returns a single python float if no input parameter is specified.

Syntax

np.random.randn(d0,d1,d2,.. dn)

d0,d1,d2,.. dn (optional) – It represents the dimension of the required array given as int. It is optional, if not specified, it will return a single python float.

Example 1: Creating 1-D Random Array

In [32]:
np.random.randn(6)
Out[32]:
array([-0.42125684, -0.0421679 ,  0.63053175,  0.08204267, -1.08237789,
        1.13159155])

Example 2: Creating 2-D Numpy Random Array

In [34]:
np.random.randn(6,4)
Out[34]:
array([[-1.20911446,  0.22615005,  2.74344014, -0.47000636],
       [ 2.45453931, -0.36098073,  0.9761115 ,  0.21063749],
       [ 1.05366423,  0.35103113, -0.16083158, -0.70649343],
       [ 0.22107229,  0.17888074, -1.13098505, -0.26359566],
       [ 2.29313593,  1.90569166,  0.71343492,  0.85209564],
       [ 0.67663365,  0.56029281,  1.11382612, -0.92873211]])

Example 3: Creating 3-D Numpy Random Array

In [35]:
np.random.randn(3,4,2)
Out[35]:
array([[[-0.13509054,  1.31253658],
        [ 0.79514661, -0.15733937],
        [-0.42428779,  0.07816613],
        [ 1.27951041, -1.2528357 ]],

       [[-0.49349802, -0.1929593 ],
        [-0.51593638, -1.08389571],
        [-0.72854643, -0.44708392],
        [-0.01845007,  2.02125787]],

       [[-1.8826071 ,  1.65592025],
        [-2.18326764, -0.07711314],
        [-2.9275772 ,  2.3173623 ],
        [ 0.94757097, -0.13646251]]])

Example 4: A Random Python Float

In [36]:
np.random.randn()
Out[36]:
-0.36506602839929475
[adrotate banner=”3″]

5) np.random.choice

np.random.choice returns a numpy array or a scalar by drawing random samples from a given 1-D array

Syntax

np.random.choice(a, size=None, replace=True, p=None)

a – This represents a 1-D array-like (Tuple/Lists) or int. If it is a ndarray, a random sample is generated from its elements. If an int, the random sample is generated as if a were np.arange(a)

size (optional) – This represents the desired output shape. It is either int or tuple of ints If the given shape is, e.g., (m, n, k), then m n k samples are drawn. Default is None, in which case a single value is returned.

replace (optional) – This signifies whether the sample is to be drawn with or without replacement. It is given as boolean.

p – It represents the probabilities associated with each entry in the input ‘a’. It is given as 1-D array-like. If it is not provided, then the sample assumes a uniform distribution over all entries in a.

Example 1: Generating one Random Sample from List

In [14]:
np.random.choice([2,4,5,8])
Out[14]:
8

Example 2: Generating a Numpy Array of Random Sample from Tuple

In [13]:
np.random.choice((2,4,5,8), size = (2,3))
Out[13]:
array([[5, 2, 8],
       [4, 2, 2]])

Example 3: Generating a Numpy Array of Random Sample by passing an int

When we pass an int instead of an array, it treats the input as np.arange(a)

In [20]:
np.random.choice(4, size = (2,2)) ## 4 is treated as np.arange(4)
Out[20]:
array([[0, 1],
       [3, 3]])

6) np.random.uniform

np.random.uniform returns a random numpy array or scalar whose element(s) are drawn randomly from the uniform distribution over [low,high). (including low but excluding high)

Syntax

np.random.uniform(low=0.0, high=1.0, size=None)

low (optional) – It represents the lower boundary of the output interval. All samples generated are greater than or equal to low. This input is float or array_like of floats. The default value is 0.

high (optional) – It represents the upper boundary of the output interval. All samples generated are less than high. This input is float or array_like of floats. The default value is 1.0.

size (optional) – It represents the output shape. This input is int or tuple of ints. If the given shape is, e.g., (m, n, k), then m n k samples are drawn. If the size is not given, then a single value is returned if low and high are both scalars. Otherwise, np.broadcast(low, high).size samples are drawn.

Example 1: Generating a Random sample

In [32]:
np.random.uniform() ## Default inputs
Out[32]:
0.8058568054860041
In [70]:
np.random.uniform(low = 2, high = 10)
Out[70]:
8.78205396325222

Example 2: Creating a 1-D Random Numpy Array

In [71]:
np.random.uniform(low = 2, high = 10, size = (3))
Out[71]:
array([6.79454712, 3.03754559, 9.95066636])

Example 3: Creating a 2-D Random Numpy Array

In [42]:
np.random.uniform(low = 2, high = 10, size = (3,4))
Out[42]:
array([[9.86355621, 8.45282899, 3.83705226, 8.13030929],
       [7.71767957, 2.05086033, 8.88954274, 4.23133409],
       [6.64220628, 3.26866265, 2.71334945, 9.34853175]])

7) np.random.binomial

np.random.binomial returns a random numpy array or scalar whose element(s) are drawn randomly from a binomial distribution

Syntax

np.random.binomial(n, p, size=None)

n – It represents the parameter of the distribution, >= 0. The input is int or array_like of ints. Floats are valid, but they will be truncated to integers.

p – It represents the parameter of the binomial distribution, >= 0 and <=1. The input is float or array_like of floats.

size – It represents the output shape. The input is int or tuple of ints, optional. If the given shape is, e.g., (m, n, k), then m n k samples are drawn. If the size is not given, a single value is returned if n and p are both scalars. Otherwise, np.broadcast(n, p).size samples are drawn.

Example 1: Generating a Random Sample

In [75]:
np.random.binomial(n=52, p=0.7)
Out[75]:
34

Example 2: Creating a 1-D Random Numpy Array

In [65]:
np.random.binomial(n=52, p=0.7, size = (2)) 
Out[65]:
array([39, 32])

Example 3: Creating a 2-D Random Numpy Array

In [73]:
np.random.binomial(n=52, p=0.7, size = (2,3)) 
Out[73]:
array([[39, 33, 39],
       [32, 37, 36]])

8) np.random.poisson

np.random.poisson returns a random numpy array or scalar whose element(s) are drawn randomly from a poisson distribution

Syntax

np.random.poisson(lam=1.0, size=None)

lam – It represents the expectation of interval, should be >=0. A sequence of expectation intervals must be broadcastable over the requested size. The input is float or array_like of floats.

*size (optional) – It represents the shape of the output. The input is int or tuple of ints. If the given shape is, e.g., (m, n, k), then m n k samples are drawn. If size is not given, then a single value is returned if lam is a scalar. Otherwise, np.array(lam).size samples are drawn.

Example 1: Generating a Random Sample

In [74]:
np.random.poisson(5)
Out[74]:
4

Example 2: Creating a 1-D Random Numpy Array

In [79]:
np.random.poisson(5,size=(4))
Out[79]:
array([2, 3, 1, 7])

Example 3: Creating a 2-D Random Numpy Array

In [80]:
np.random.poisson(5,size=(4,3))
Out[80]:
array([[ 7,  2, 10],
       [ 3,  4,  7],
       [ 5,  7,  5],
       [ 8,  9,  4]])

9) np.random.randint

np.random.randint returns a random numpy array or scalar, whose element(s) is int, drawn randomly from low (inclusive) to the high (exclusive) range.

Syntax

np.random.randint(low, high=None, size=None, dtype=’l’)

low – It represents the lowest inclusive bound of the distribution from where the sample can be drawn. Unless high=None, in which case this parameter is one above the highest such integer. The input is int

high (optional) – It represents the upper exclusive bound of the distribution from where the sample can be drawn. (see above for behavior if high=None). The input is int.

size (optional) – It represents the shape of the output. The input is int or tuple of ints. If the given shape is, e.g., (m, n, k), then m n k samples are drawn. Default is None, in which case a single value is returned.

dtype (optional) – It represents the required dtype of the result. The default value is ‘np.int’.

Example 1: Generating a Random Number

In [83]:
np.random.randint(1,50)
Out[83]:
42

Example 2: Creating a 1-D Random Numpy Array

In [93]:
np.random.randint(1,50, size=(4))
Out[93]:
array([ 4, 24,  4, 32])

Example 3: Creating a 2-D Random Numpy Array

In [95]:
np.random.randint(1,50, size=(4,3))
Out[95]:
array([[48,  8,  1],
       [36, 38,  2],
       [31, 28, 32],
       [30,  7,  8]])

10) np.random.sample

np.random.sample returns a random numpy array or scalar whose element(s) are floats, drawn randomly from the half-open interval [0.0, 1.0) (including 0 and excluding 1)

Syntax

np.random.sample(size=None)

size (optional) – It represents the shape of the output. The input is int or tuple of ints. If the given shape is, e.g., (m, n, k), then m n k samples are drawn. If no size is given, then a single value is returned.

Example 1: Generating a Random Sample

In [38]:
np.random.sample()
Out[38]:
0.4263312607851021

Example 2: Creating a 1-D Random Numpy Array

In [67]:
np.random.sample(2)
Out[67]:
array([0.96748937, 0.74883372])

Example 3: Creating a 2-D Random Numpy Array

In [96]:
np.random.sample((2,4)) ## Two Dimension
Out[96]:
array([[0.52717883, 0.96121114, 0.78901011, 0.49669551],
       [0.211141  , 0.60398414, 0.74857581, 0.75586383]])
  • MLK

    MLK is a knowledge sharing community platform for machine learning enthusiasts, beginners and experts. Let us create a powerful hub together to Make AI Simple for everyone.

    View all posts

Follow Us

Leave a Reply

Your email address will not be published. Required fields are marked *