NumPy
NumPy is an acronym for Numerical Python.
It is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays (Wikipedia - NumPy ).
The following information about NumPy is extracted from NumPy: the absolute basics for beginners.
Advantage of NumPy
- NumPy arrays are faster and more compact than Python lists; array consumes less memory and is convenient to use.
- NumPy uses much less memory to store data and it provides a mechanism of specifying the data types; this allows the code to be optimized even further.
NDArray
Numpy NDArray is a shorthand for “N-dimensional array.” i.e. an array with any number of dimensions.
The following terms are used to identify the dimensions of the array:
- Vector = array with a single dimension (there’s no difference between row and column vectors).
- Matrices = array with two dimensions e.g. 3 row x 4 columns or referred to as "3 by 4" array.
- Tensor = 3 or higher dimensions.
What are the attributes of an array?
- An array is usually a fixed-size container of items of the same type and size.
- The number of dimensions and items in an array is defined by its shape.
- The shape of an array is a tuple of non-negative integers that specify the sizes of each dimension.
import numpy as np array_example = np.array([[[0, 1, 2, 3], [4, 5, 6, 7]], [[0, 1, 2, 3], [4, 5, 6, 7]], [[0 ,1 ,2, 3], [4, 5, 6, 7]]]) # dimension = bracket levels print("NumPy Array Dimension:{}".format(array_example.ndim)) # NumPy Array Dimension:3 # shape = no of item per bracket level print("NumPy Array Shape:{}".format(str(array_example.shape))) # NumPy Array Shape:(3, 2, 4) # size = total items print("NumPy Array Size:{}".format(array_example.size)) # NumPy Array Size:24
Practical uses of NumPy
One of the examples of practical use of NumPy is calculating Mean Square Error in Machine Learning.
# define mean square error function # accept regular lists of values # convert into np array # find their differences # and square the value def mse(actual, pred): actual, predic = np.array(actual), np.array(predic) print("Actual:") print(actual) print("Predicted:") print(predic) print("Mean Square Error:") print( (((predic-actual))**2).mean() ) print("====================") return # define actual and predicted value lists actual = [12, 13, 14, 15, 15, 22, 27] predic = [11, 13, 14, 14, 15, 16, 18] mse(actual, predic) # 17.0
0 Comments