import numpy as npimport scipy.stats as stimport iqplotimport bokeh.ioimport bokeh.plottingbokeh.io.output_notebook()
Loading BokehJS ...
A good portion of the random number generation functionality you will need is in the np.random module. It allows for draws of independent random numbers for many convenient named distributions. The scipy.stats module offers even more distributions, but for most applications, Numpy’s generators suffice and are typically faster than using Scipy, which has more overhead.
13.1 Uniform random numbers
Let’s start by generating random numbers from a Uniform distribution.
The function uniform() in the np.random module generates random numbers on the interval [low, high) from a Uniform distribution. The size keyword argument is how many random numbers you wish to generate, and is a keyword argument in all Numpy’s functions to draw from specific distributions. The random numbers are returned as a Numpy array.
We can check to make sure it is appropriately drawing random numbers out of the Uniform distribution by plotting the cumulative distribution function. We’ll generate 1,000 random numbers and plot them along with the CDF of a Uniform distribution.
# Generate random numbersx = np.random.uniform(low=0, high=1, size=1000)# Plot the ECDF of randomly generated numbersp = iqplot.ecdf(x, marker_kwargs={"fill_color": None},)p.line( x=[0, 1], y=[0, 1], line_width=2, line_color="orange",)bokeh.io.show(p)
So, it looks like our random number generator is doing a good job.
Generating random numbers on the uniform interval is one of the most commonly used RNG applications. For example, you can simulate flipping a biased (unfair) coin by drawing from a Uniform distribution and then asking if the random number if less than the bias.
# Generate 20 random numbers on uniform intervalx = np.random.uniform(low=0, high=1, size=20)# Make the coin flips (< 0.7 means we have a 70% chance of heads)heads = x <0.7# Show which were heads, and count the number of headsprint(heads)print("\nThere were", np.sum(heads), "heads.")
Of course, you could also do this by drawing out of a Binomial distribution.
print(f"There were {np.random.binomial(20, 0.7)} heads.")
There were 12 heads.
13.2 Choice of generator
As of version 1.23 of Numpy, the algorithm under the hood of calls to functions like np.random.uniform() is the Mersenne Twister Algorithm for generating random numbers. It is a very widely used and reliable method for generating random numbers. However, starting with version 1.17, the numpy.random module offers random number generators with better speed and statistical performance, including a 64-bit permuted congruential generator (PCG64). Going forward, the preferred approach to doing random number generation is to first instantiate a generator of your choice, and then use its methods to generate numbers out of probability distributions.
Let’s set up a PCG64 generator, which is Numpy’s default (though this will soon be updated to the PCG64 DXSM, which works better for massively parallel generation, per Numpy’s documentation).
rng = np.random.default_rng()
Now that we have the generator, we can use it to draw numbers out of distributions. The syntax is the same as before, except rng replaces np.random.
Now, just to demonstrate that random number generation is deterministic, we will explicitly seed the random number generator (which is usually seeded with a number representing the date/time to avoid repeats) to show that we get the same random numbers.
# Instantiate generator with a seedrng = np.random.default_rng(seed=3252)# Draw random numbersrng.uniform(size=10)
If you are writing tests, it is often useful to seed the random number generator to get reproducible results. Otherwise, it is best to use the default seed, based on the date and time, so that you get a new set of random numbers in your applications each time do computations.
13.4 Drawing random numbers out of other distributions
Say we wanted to draw random samples from a Normal distribution with mean μ and standard deviation σ.
# Set parametersmu =10sigma =1# Draw 100000 random samplesx = rng.normal(mu, sigma, size=100000)# Plot the histogramp = iqplot.histogram(x, rug=False, density=True, y_axis_label="approximate PDF",)bokeh.io.show(p)
It looks Normal, but, again, comparing the resulting ECDF is a better way to look at this. We’ll check out the ECDF with 1000 samples so as not to choke the browser with the display. I will also make use of the theoretical CDF for the Normal distribution available from the scipy.stats module.
It is often useful to randomly choose elements from an existing array. (Actually, this is probably the functionality we will use the most, since it is used in bootstrapping.) The rng.choice() function does this. You equivalently could do this using rng.integers(), where the integers represent indices in the array, exceptrng.choice() has a great keyword argument, replace, which allows random draws with or without replacement. For example, say you had 50 samples that you wanted to send to a facility for analysis, but you can only afford to send 20. If we used rng.integers(), we might have a problem.
Answer: VERY OFTEN! We will use random number generator extensively as we explore probability distributions.
In many ways, probability is the language of biology. Molecular processes have energetics that are comparable to the thermal energy, which means they are always influenced by random thermal forces. The processes of the central dogma, including DNA replication, are no exceptions. This gives rise to random mutations, which are central to understanding how evolution works. And of course neuronal firing is also probabilistic. If we want to understand how biology works, it is often useful to use random number generators to model the processes.