Random Numbers in NumPy: default_rng, Seeds, Distributions and Sampling
How NumPy makes random numbers you can bring back: default_rng and seeds, uniform versus normal, a bell curve from 1,000 samples, dice counts, choice with and without replacement, shuffle versus permutation, and a train/test split.
What you will learn
- Create a generator with np.random.default_rng and make results repeat with a seed
- Explain why a seed fixes the whole sequence, not a single call
- Sample uniform, normal and integer values and see a bell curve appear in a histogram
- Pick, shuffle and split data with choice, permutation and shuffle
Before you start
- NumPy arrays and indexing
- NumPy aggregation (mean, std, unique)
So far your arrays held values you typed in or calculated. Data science also needs values that come from chance: for sampling, for testing, and for splitting data. But how can a computer be random when it only follows instructions?
It isn't, not exactly. Think of a huge book filled with scrambled numbers. They look random, but they're already fixed on the page. A seed is the page where you start reading. Open the same page again and you read the same numbers; open another page and you get different ones. Each time you ask for more, you carry on from where you stopped. In the computer a formula plays the part of the book, which is why these are called pseudo-random numbers.
Your random generator
import numpy as np
rng = np.random.default_rng()
u = rng.random(3)
i = rng.integers(1, 10, size=5)
n = rng.standard_normal(3)
print(type(rng).__name__)
print(u.shape, i.shape, n.shape)
print(bool((u >= 0).all() and (u < 1).all()))
print(bool((i >= 1).all() and (i < 10).all()))
Generator
(3,) (5,) (3,)
True
True
default_rng creates a Generator, an object that hands out random numbers. With no seed, the numbers change on every run, so this file only prints what stays true: random stays in [0, 1) and integers(1, 10) stays from 1 to 9. Make one generator, and get everything random from it.
A seed brings the numbers back
rng = np.random.default_rng(42)
print(rng.random(3))
rng2 = np.random.default_rng(42)
print(rng2.random(3))
rng3 = np.random.default_rng(7)
print(rng3.random(3))
[0.77395605 0.43887844 0.85859792]
[0.77395605 0.43887844 0.85859792]
[0.62509547 0.8972138 0.77568569]
Same seed, same numbers, digit by digit. Run the whole file again and every line comes out the same. Let NumPy do the comparing:
first = np.random.default_rng(42).random(5)
second = np.random.default_rng(42).random(5)
other = np.random.default_rng(43).random(5)
print(first)
print(second)
print(np.array_equal(first, second))
print(np.array_equal(first, other))
[0.77395605 0.43887844 0.85859792 0.69736803 0.09417735]
[0.77395605 0.43887844 0.85859792 0.69736803 0.09417735]
True
False
Why does this matter? When a result looks wrong, you can run it again with the same numbers and find the problem. Someone else can get those numbers too, on the same NumPy version.
The generator remembers its place
rng = np.random.default_rng(42)
a = rng.random(2)
b = rng.random(2)
print(a)
print(b)
again = np.random.default_rng(42)
print(again.random(4))
[0.77395605 0.43887844]
[0.85859792 0.69736803]
[0.77395605 0.43887844 0.85859792 0.69736803]
b doesn't repeat a. It gets the next two numbers. A fresh generator with the same seed asking for four at once gives a then b. A seed fixes the whole sequence, and asking again moves you forward.
In older code
# Older code seeds one hidden, global generator
np.random.seed(42)
print(np.random.rand(3))
# Current way: your own generator
rng = np.random.default_rng(42)
print(rng.random(3))
[0.37454012 0.95071431 0.73199394]
[0.77395605 0.43887844 0.85859792]
You'll still see np.random.seed. It seeds one hidden generator shared by the whole program, and it's an older algorithm, so 42 gives different numbers. In new code, use default_rng.
Distributions: flat or a bell
A distribution is a rule for how likely each value is. Picture a spinner with equal sections: every section has the same chance, so if you count the spins the picture comes out flat. That's uniform. Now picture the heights of a large group of people. Most are near the middle and few are far from it. Count them and you get a bell. That's normal.
rng = np.random.default_rng(42)
print(rng.random(3))
print(rng.uniform(10, 50, size=3))
print(rng.normal(100, 15, size=3))
big = rng.normal(100, 15, size=10000)
print(round(big.mean(), 1), round(big.std(), 1))
[0.77395605 0.43887844 0.85859792]
[37.89472116 13.76709392 49.02489407]
[101.91760605 95.25636111 99.74798264]
99.8 15.1
random is uniform from 0 up to (not including) 1. uniform(10, 50) moves that to another range. normal(100, 15) takes a centre (the mean) and a spread (the standard deviation). Ten thousand samples come out at mean 99.8 and spread 15.1: close to what you asked for, not exact, because these are samples.
A bell from your own samples
import numpy as np
rng = np.random.default_rng(7)
scores = rng.normal(100, 15, size=1000)
counts, edges = np.histogram(scores, bins=8)
print(counts.sum())
for count, low in zip(counts, edges[:-1]):
bar = '#' * round(count / 8)
print(f"{low:6.1f} | {bar} {count}")
1000
51.2 | # 5
62.1 | #### 29
73.1 | ############## 111
84.0 | ############################# 229
94.9 | ######################################### 327
105.8 | ######################### 197
116.7 | ######### 73
127.7 | #### 29
histogram.py, drawn as bars. Nobody drew a bell; it came out of the samples.np.histogram cuts the range into eight equal bins and counts the values in each. The tallest bin starts at 94.9 and holds the centre of 100.
Random whole numbers
rng = np.random.default_rng(42)
print(rng.integers(1, 10, size=8))
print(rng.integers(1, 6, size=8, endpoint=True))
print(rng.integers(0, 100, size=(2, 3)))
[1 7 6 4 4 8 1 7]
[2 1 4 6 5 5 5 5]
[[51 12 83]
[45 50 37]]
The high value is left out, so integers(1, 10) gives 1 to 9. Add endpoint=True to include it, and 1 to 6 works like a dice. size can be a shape. Repeats are fine, because each draw is separate.
Roll that dice 600 times and count the faces:
rng = np.random.default_rng(1)
rolls = rng.integers(1, 7, size=600)
faces, counts = np.unique(rolls, return_counts=True)
for face, count in zip(faces, counts):
print(face, count)
1 109
2 85
3 103
4 93
5 107
6 103
You'd expect about 100 each. None is exactly 100, which is normal with samples, but there's no peak in the middle. It's roughly flat: uniform.
Picking from an array
Picture a bag of four coloured balls.
rng = np.random.default_rng(42)
colors = np.array(["red", "blue", "green", "yellow"])
print(rng.choice(colors, size=3))
print(rng.choice(colors, size=3, replace=False))
print(rng.choice(colors, size=6, p=[0.7, 0.1, 0.1, 0.1]))
['red' 'yellow' 'green']
['yellow' 'blue' 'red']
['red' 'yellow' 'blue' 'blue' 'red' 'red']
By default each ball goes back in the bag, so repeats are allowed. replace=False keeps a picked ball out. p weights the bag, one chance per colour, adding up to one. Ask for five without replacement from a bag of four, and you get:
ValueError: Cannot take a larger sample than population when replace is False
Ask for fewer, or allow repeats.
permutation and shuffle
rng = np.random.default_rng(42)
colors = np.array(["red", "blue", "green", "yellow"])
mixed = rng.permutation(colors)
print(mixed)
print(colors)
rng.shuffle(colors)
print(colors)
print(rng.permutation(6))
['yellow' 'green' 'blue' 'red']
['red' 'blue' 'green' 'yellow']
['yellow' 'green' 'red' 'blue']
[2 4 0 1 3 5]
Think of a stack of cards. permutation photocopies the stack, mixes the copy and hands it back, so colors is unchanged. shuffle mixes your own stack in place and returns nothing. Given a plain number, permutation(6) mixes 0 to 5.
Sampling rows and splitting data
rng = np.random.default_rng(42)
data = np.arange(12).reshape(6, 2)
print(rng.choice(data, size=2, replace=False))
order = rng.permutation(len(data))
train = data[order[:4]]
test = data[order[4:]]
print(order)
print(train.shape, test.shape)
[[0 1]
[8 9]]
[3 0 5 2 4 1]
(4, 2) (2, 2)
choice on a 2D array picks whole rows, and each row stays together. Mixing the row numbers with permutation, then taking the first four for train and the rest for test, means no row lands in both groups. That's how data is often split; train/test split and data leakage takes it further.
Recap
| Tool | Remember |
|---|---|
np.random.default_rng(seed) | Your generator; the same seed gives the same whole sequence |
random, uniform | Flat: every value in the range equally likely |
normal(mean, std) | Bell: values near the centre more likely |
integers(low, high) | High is left out unless endpoint=True |
choice | Pick from your values; replace and p control repeats and weights |
permutation / shuffle | Mixed copy / mixed in place |
Try it yourself: change the seed and the size in histogram.py and watch how the bars change. Or ask an AI tool to explain the result, then read every line it gives you.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Supervised Learning: Features, Labels, Classification and Regression
What supervised learning is, shown on one small job: sorting support tickets into billing and technical. Rules vs learning from examples, classification vs regression, why some tickets stay hidden, and a 12-ticket classifier that labels three new ones.
NumPy and pandas for AI Engineers: Arrays for Vectors, Tables for Logs
NumPy and pandas at the depth an AI engineer needs. Shape, axis and broadcasting on 1,000 sample embeddings, a loop against one @, then a 2,000-row model call log: dtypes on load, missing values, filters, groupby model, merge and resample.
NumPy Arrays: Creation, Shape and Data Types From Scratch
Why a NumPy array beats a list for numbers, the seven ways to create one, what shape, ndim, size and dtype tell you, and why a slice is a view. Every output is from a real run on NumPy 2.
NumPy Indexing, Slicing, Masks and np.where
Get values out of a NumPy array by position, by range, by condition and by a list of positions, write through slices, use np.where three ways, and learn which picks are views and which are copies.
