Skip to main content

Introduction to NumPy’s Random Module

Random number generation and sampling are critical components in many data science applications, including simulations, random sampling, and stochastic processes. NumPy’s random module provides a suite of functions to generate random numbers, create random samples, and perform random operations efficiently. In this article, we'll explore the basics of NumPy’s random module and how to use it effectively.


1. Generating Random Numbers​

Create a local generator with np.random.default_rng(). Its random() method generates values from a uniform distribution over the half-open interval [0, 1) without changing the legacy process-wide random state.

1.1 Uniform Random Numbers​

import numpy as np

# Create a reproducible local generator
rng = np.random.default_rng(42)

# Generate a single random number
random_num = rng.random()
print("Single random number:", random_num)

# Generate a 1D array of random numbers
random_array = rng.random(5)
print("1D array of random numbers:", random_array)

# Generate a 2D array of random numbers
random_matrix = rng.random((3, 3))
print("2D array of random numbers:\n", random_matrix)

1.2 Random Integers with Generator.integers()​

You can generate random integers within a specified half-open range using Generator.integers().

# Generate a single random integer between 0 and 10
random_int = rng.integers(0, 10)
print("Single random integer:", random_int)

# Generate a 1D array of random integers between 0 and 10
random_int_array = rng.integers(0, 10, size=5)
print("1D array of random integers:", random_int_array)

2. Creating Random Samples​

Sampling is the process of selecting a subset of data from a larger dataset. NumPy’s random module provides functions to create random samples efficiently.

2.1 Random Choice with Generator.choice()​

The generator's choice() method selects elements with or without replacement.

# Create a sample array
arr = np.array([10, 20, 30, 40, 50])

# Randomly select a single element
random_choice = rng.choice(arr)
print("Randomly selected element:", random_choice)

# Randomly select multiple elements with replacement
random_choices = rng.choice(arr, size=3, replace=True)
print("Randomly selected elements with replacement:", random_choices)

# Randomly select multiple elements without replacement
random_choices_no_replace = rng.choice(arr, size=3, replace=False)
print("Randomly selected elements without replacement:", random_choices_no_replace)

2.2 Random Permutations with Generator.permutation()​

Random permutations are useful for shuffling data. Generator.permutation() returns a permuted copy for an array input.

# Create a sample array
arr = np.array([1, 2, 3, 4, 5])

# Generate a random permutation of the array
random_permutation = rng.permutation(arr)
print("Random permutation of the array:", random_permutation)

3. Setting a Random Seed​

Pass a seed when constructing a generator to replay its stream under the stated NumPy version and bit-generator algorithm. Reusing one generator continues the stream; constructing a second generator with the same seed restarts it.

3.1 Creating Seeded Generators​

# Create and use a seeded generator
seeded_rng = np.random.default_rng(42)
random_numbers = seeded_rng.random(3)
print("Random numbers with seed 42:", random_numbers)

# A new generator with the same seed restarts the stream
repeated_rng = np.random.default_rng(42)
random_numbers_again = repeated_rng.random(3)
print("Random numbers with seed 42 (repeated):", random_numbers_again)
np.testing.assert_array_equal(random_numbers, random_numbers_again)

4. Generating Random Numbers from Specific Distributions​

NumPy’s random module provides functions to generate random numbers from various statistical distributions, such as normal, binomial, and Poisson distributions.

4.1 Normal Distribution with Generator.normal()​

Generator.normal() generates normal samples with explicit location and scale parameters.

# Generate a single random number from a normal distribution
random_normal = rng.normal(loc=0.0, scale=1.0)
print("Single random number from normal distribution:", random_normal)

# Generate a 1D array of random numbers from a normal distribution
random_normal_array = rng.normal(loc=0.0, scale=1.0, size=5)
print("1D array of random numbers from normal distribution:", random_normal_array)

4.2 Binomial Distribution with Generator.binomial()​

Generator.binomial() samples the number of successes in n independent Bernoulli trials with success probability p.

# Parameters: number of trials (n), probability of success (p)
n, p = 10, 0.5

# Generate a single random number from a binomial distribution
random_binomial = rng.binomial(n, p)
print("Single random number from binomial distribution:", random_binomial)

# Generate an array of random numbers from a binomial distribution
random_binomial_array = rng.binomial(n, p, size=5)
print("Array of random numbers from binomial distribution:", random_binomial_array)

Conclusion​

The random module in NumPy is a powerful tool for generating random numbers, creating random samples, and working with various probability distributions. These operations are essential in many data science tasks, from simulations to sampling and beyond. By mastering the basics of the random module, you’ll be well-equipped to handle randomness in your data science projects, ensuring both flexibility and reproducibility.

A reproducible pseudorandom stream is not cryptographically secure and does not make a sample representative or an experiment valid. Use Python's secrets module for security-sensitive tokens, and document the seed, NumPy version, and sampling design for analysis.

Primary references​