[PYTHON] Random number generation summary by Numpy

The Python standard also has a module called random, but numpy, which can perform vector operations, runs faster when it says "generate a large number of random numbers and perform some processing". There are also a lot of distribution functions.

Uniform random number

Generate a uniform random number from 0 to 1 with numpy.random.rand (). Multiple random numbers can be generated by specifying an argument. If you want to change the range of random numbers, you can perform vector operations later.

from numpy.random import *

rand()		#Generate one random number from 0 to 1
rand(100)	#Generate 100 random numbers from 0 to 1
rand(10,10)	#Generate a 10x10 matrix with random numbers from 0 to 1

rand(100) * 40 + 30	#Generate 100 random numbers from 30 to 70

Random numbers that follow a particular distribution function

Any number of random numbers can be generated by specifying an argument such as size = (10,10).

from numpy.random import *

"""Standard normal distribution. So-called Gaussian. Randn for standard normal distribution()If you want to specify the mean / variance, normal()Is used."""
randn()			#Standard normal distribution(Average 0,Standard deviation 1)
randn(10)		#Generate 10 standard normal distributions
randn(10,10)	#10x10 matrix with standard normal distribution

normal(50,10)	#Normal distribution with mean 50 and standard deviation 10

"""Binomial distribution. The number of coins that will be fronted by throwing coins with a probability of p n times."""
binomial(n=100, p=0.5)

"""Poisson distribution. Distribution of the number of times that occurs when a phenomenon that rarely occurs is observed for a long time. λ is the average."""
poisson(lam=10)		# λ=Poisson distribution of 10

"""Beta distribution. Used for conjugate prior distribution of binomial distribution."""
beta(a=3, b=5)		# a=3, b=Beta distribution of 5

There are many other distributions such as χ distribution, Dirichlet distribution, exponential distribution, F distribution, gamma distribution, geometric distribution, Gumbel distribution, hypergeometric distribution, Laplace distribution, logistic distribution, lognormal distribution, and so on. See this page for details. http://docs.scipy.org/doc/numpy/reference/routines.random.html

integer

from numpy.random import *

randint(100)			#Generate one integer from 0 to 99
randint(30,70)			#Generate one integer from 30 to 69
randint(0,100,20)		#Generate 20 integers from 0 to 99
randint(0,100,(5,5))	#Generate a 5x5 matrix with integers from 0 to 99

random_integers(100)	#Generate one integer from 1 to 100
random_integers(30,70)	#Generate one integer from 30 to 70

Random extraction from list

from numpy import *

city = ["Sapporo","Sendai","Tokyo","Nagoya","Kyoto","Osaka","Fukuoka"]

random.choice(city)						#Randomly extract one
random.choice(city,10)					#Random extraction of 10 (with duplication)
random.choice(city,5,replace=False)	#Random extraction of 5 (no duplication))

#When weighting probabilities
weight = [0.1, 0.1, 0.3, 0.1, 0.1, 0.2, 0.1]
random.choice(city, p=weight)			#Extract one with the specified probability

Initialization of random number generation

Random numbers generated by Numpy are pseudo-random numbers, so if you specify a fixed seed, the same random number will be generated every time. It is used when you want the same random number to be output every time, such as when debugging.

from numpy.random import *

seed(100)		#Any number is fine
rand()			#Returns the same value every time

Check the distribution with a histogram

If you are uncertain whether the desired random numbers are generated, it is advisable to generate a large number of random numbers and draw a histogram. Here, a graph drawing module called matplotlib is used.

from numpy.random import *
import matplotlib.pyplot as plt

R = randn(10000)		#Generate 10,000 random numbers with standard normal distribution
plt.hist(R, bins=100)	#Create 100 histograms
plt.show()				#Show graph

output.png

Application: Random walk generation

Generate a random number sequence of right or left, that is, +1 or -1, and take the cumulative sum cumsum ().

from numpy import *

L = 1000							#Number of steps
step = random.choice([-1,1],L)	 	# +1 or -Generate L 1
position = cumsum(step)				#Change of position

output.png

Recommended Posts

Random number generation summary by Numpy
Numpy random module random number generator
[python] Random number generation memorandum
Prime number generation program by Python
Pseudo-random number generation and random sampling
Non-overlapping integer random number generation (0-N-1)
numpy> Random number list output> zip () / print%
#Random string generation
Derivation of multivariate t distribution and implementation of random number generation by python
High-dimensional random number vector generation ~ Latin Hypercube Sampling / Latin hypercube sampling ~
I made a random number graph with Numpy
[Note] Random number creation?
Faker summary by language
07. Sentence generation by template
pandas Matplotlib Summary by usage
Random forest (implementation / parameter summary)
Random Forests Understand by Points
Random number seed fixed in TensorFlow and Numpy A little different