Random Number Generation for ML
What you'll learn: How to use NumPy's random number generation for reproducible ML operations like weight initialization and data splitting.
Why Randomness Matters in Machine Learning
Machine learning relies heavily on controlled randomness. You need random numbers to initialize neural network weights, shuffle training data, split datasets, and introduce stochasticity into algorithms like Stochastic Gradient Descent. But here's the catch: you also need your experiments to be reproducible — getting the same "random" results when you re-run your code.
Using np.random for ML Tasks
NumPy's random module provides the tools for generating random numbers in ML workflows:
import numpy as np
# Generate random values for weight initialization
weights = np.random.randn(3, 4) # Random values from standard normal
# Random uniform values between 0 and 1
data = np.random.rand(100)
# Random integers for sampling indices
indices = np.random.randint(0, 1000, size=100)
# Shuffle an array (useful for randomizing training data)
dataset = np.arange(10)
np.random.shuffle(dataset)
The Critical Role of Seeds
Think of a random seed as a starting point for your "random" number generator. Setting a seed ensures you get the same sequence of random numbers every time:
# Without seed - different results each run
print(np.random.rand(3)) # [0.417, 0.720, 0.000] (example)
print(np.random.rand(3)) # [0.302, 0.147, 0.092] (example)
# With seed - reproducible results
np.random.seed(42)
print(np.random.rand(3)) # Always [0.374, 0.950, 0.731]
np.random.seed(42)
print(np.random.rand(3)) # Same again: [0.374, 0.950, 0.731]
Setting seeds at the start of your ML scripts ensures experiments can be replicated exactly — crucial for debugging and scientific validity.
Key Takeaway: Use np.random for all randomized ML operations, and always set a seed with np.random.seed() to make your experiments reproducible.