NumPy is library of python that performs operations on array.
It is a library rich with features used for mathematical computations and further application in machine learning domain.
It comes in very handy while generating any random arrays for operations while using machine learning algorithms.
NumPy arrays are also used for speed and efficiency in mathematical computation over python’s list.
numpy.random.rand()
importing NumPy.
import numpy
numpy contains the random module which is used to generate random sequence of numbers in uniform distribution.
generating a random float
x = numpy.random.rand() print(x)
it generated the output:
0.3859799
random.rand() generates single value in range [0,1).
generating 1-D array of random numbers
To generate 1-D array of random numbers we need to provide the parameter n.
Let’s generate a 1-D array of 5 elements.
x = numpy.random.rand(5) print(x)
Output:
[0.3456 0.7812 0.1234 0.5678 0.9123]
generating 2-D array of random numbers
To generate 2-D array of random numbers we need to provide parameter (n1, n2).
- n1 is for number of rows
- n2 is for number of columns
x = numpy.random.rand(2,3) print(x)
Output:
[[0.47460322 0.74820234 0.50623572] [0.33074561 0.23408376 0.56831165]]
creating multi-dimensional arrays
x = numpy.random.rand(2, 2, 3) print(x)
it generates a higher dimensional array.
The (2, 2, 3) represents the shape of multi-dimensional array
parameter used here:
- The first parameter, 2, represents the number of blocks or (matrices) in array.
- The second parameter, 2, represents the number of rows in each block.
- The third parameter, 3, represents the number of columns in each block.
Output:
[ [[0.123, 0.456, 0.789], [0.321, 0.654, 0.987]], [[0.234, 0.567, 0.891], [0.345, 0.678, 0.912]] ]
Summary:
- random.rand() generates a float or array of float.
- By passing parameters, we can generate 1-D or multi-dimensional array.
- random.rand() follows normal distribution.