Numpy has a random module that makes it easy to generate random numbers. This time, I will introduce how to use the random module.
First, import numpy.
>>> import numpy as np
Now, let me introduce the algorithms that can be generated by the random module.
>>> #Output one uniform random number
>>> np.random.rand()
0.5880118049738298
>>> #Output uniform random numbers to any number(Example: 3)
>>> np.random.rand(3)
array([ 0.44895901, 0.39833764, 0.99688209])
>>> #Output uniform random numbers in any dimension and any number(Example: 3x4 two-dimensional matrix)
>>> np.random.rand(3, 4)
array([[ 0.0526965 , 0.01470381, 0.33005156, 0.14598275],
[ 0.41548295, 0.69093009, 0.78780918, 0.4854191 ],
[ 0.89098149, 0.23846317, 0.49385737, 0.54687586]])
Outputs random numbers that follow a normal distribution.
>>> #General format
>>> # np.random.normal(average,Distributed,Number of outputs)
>>> #Example 1: Output one standard normal random number
>>> np.random.normal()
1.822075035860751
>>> #Example 2: Average 10,Output a random number that follows a normal distribution with variance 20 as a 3x4 matrix
>>> np.random.normal(10, 20, (3, 4))
array([[ 30.20657691, 9.14586262, 37.53208038, -7.07276197],
[ 2.72797326, 47.43580065, -4.09493013, 20.48477033],
[ 13.32781396, -10.19972429, 24.45599633, -6.52998571]])
It is also possible to generate random numbers with distributions other than the normal distribution (see Resources at the bottom).
>>> #General form
>>> # np.random.randint(lower limit,upper limit,Number of outputs)
>>> #Example 1: 0~Output one integer between 5
>>> np.random.randint(5)
2
>>> #Example 2:10-Output integers between 100 as a 3x4 matrix
>>> np.random.randint(10, 100, (3, 4))
array([[70, 34, 20, 82],
[90, 78, 38, 71],
[15, 73, 63, 53]])
>>> #General form
>>> # np.random.shuffle(Array)
>>> #Example 1: Shuffle a one-dimensional array
>>> arr1 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
>>> np.random.shuffle(arr)
>>> arr1
['E', 'H', 'C', 'I', 'D', 'B', 'G', 'A', 'F']
>>> #Example 2: Shuffle a two-dimensional array(The outermost part is shuffled)
>>> arr2 = [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]
>>> np.random.shuffle(arr2)
>>> arr2
[['G', 'H', 'I'], ['A', 'B', 'C'], ['D', 'E', 'F']]
Random numbers generated by seed can be specified.
>>> np.random.seed(10)
>>> np.random.rand()
0.771320643266746
>>> np.random.seed(10)
>>> np.random.rand()
0.771320643266746
>>> np.random.seed(11)
>>> np.random.rand()
0.1802696888767692
Recommended Posts