0
0
NumPydata~5 mins

Setting random seed for reproducibility in NumPy

Choose your learning style9 modes available
Introduction

Setting a random seed makes sure you get the same random numbers every time you run your code. This helps when you want to share your work or check your results later.

When you want to share your data analysis and others need to get the same results.
When you are testing your code and want consistent random data.
When you run experiments multiple times and want to compare results fairly.
When you create random samples for training machine learning models and want repeatable splits.
Syntax
NumPy
import numpy as np
np.random.seed(your_seed_number)

Replace your_seed_number with any integer you choose.

Calling np.random.seed() sets the starting point for random number generation.

Examples
This sets the seed to 42 and prints 3 random numbers between 0 and 1.
NumPy
import numpy as np
np.random.seed(42)
print(np.random.rand(3))
This sets the seed to 0 and prints 5 random integers between 1 and 9.
NumPy
import numpy as np
np.random.seed(0)
print(np.random.randint(1, 10, size=5))
Sample Program

This program sets the seed to 123, then generates and prints 5 random numbers. Running it multiple times will print the same numbers.

NumPy
import numpy as np

# Set seed for reproducibility
np.random.seed(123)

# Generate 5 random numbers between 0 and 1
random_numbers = np.random.rand(5)

print("Random numbers:", random_numbers)
OutputSuccess
Important Notes

Setting the seed affects all random functions in numpy until you change it again.

Use the same seed number to get the same random results every time.

Summary

Setting a random seed makes your random results repeatable.

Use np.random.seed(number) before generating random numbers.

This helps when sharing or testing your code.