At times, it is necessary to introduce randomness according to a particular distribution when implementing various machine learning models. In this post, we’ll examine how to use the NumPy’s random.uniform()
function, which will generate n
values from a uniform distribution within a specified range.
Basic Syntax: np.random.uniform(low, high, size)
from numpy.random import default_rng
# Instantiate NumPy Generator instance, setting random seed
rng = default_rng(seed = 1)
# Sample 1: [0, 1), 200 numbers
sample1 = rng.uniform(low = 0, high = 1, size = 200)
print("Sample 1:")
print(sample1)
# Sample 2: [-10, 100), 200 numbers
sample2 = rng.uniform(low = -10, high = 10, size = 200)
print("Sample 2:")
print(sample2)
Output:
Sample 1:
[0.1719594 0.22005712 0.6320633 0.58757608 0.36199078 0.06035538
0.19761037 0.65092953 0.23661011 0.62843592 0.32415973 0.45364117
...]
Sample 2:
[-3.42699535 5.59605115 -0.21797547 -0.50691541 -9.76982705 -1.19263974 -1.5363445 7.52296261 2.43838142 -3.51784328
...]
NOTE: since NumPy version 1.17.0, it has been recommended to first instantiate a Generator, such as default_rng()
, and then call the numpy.random.uniform()
function on the generator object. In this case, we've set the random seed for the Generator so that the results are reproducible.
The uniform()
function takes three arguments:
low
: the lowest value that can be generated, NumPy’s range for the function is inclusive of this valuehigh
: the upper boundary for the function, NumPy’s range for the function is exclusive of this valuesize
: the number of values to generate
If we use seaborn's histplot()
function to create histograms of the distribution of our two samples, we'll see that they are roughly uniform, as expected.
np.random.uniform(low = 0, high = 1, size = 200)
Sample 1: 
np.random.uniform(low = -10, high = 10, size = 200)
Sample 2: 
From the above plots, we can see the distributions are roughly uniform!
About
Einblick is an agile data science platform that provides data scientists with a collaborative workflow to swiftly explore data, build predictive models, and deploy data apps. Founded in 2020, Einblick was developed based on six years of research at MIT and Brown University. Einblick customers include Cisco, DARPA, Fuji, NetApp and USDA. Einblick is funded by Amplify Partners, Flybridge, Samsung Next, Dell Technologies Capital, and Intel Capital. For more information, please visit www.einblick.ai and follow us on LinkedIn and Twitter.