NumPy is a programming language that deals with multi-dimensional arrays and matrices. On top of the arrays and matrices, NumPy supports a large number of mathematical operations. In this part, we will review the essential functions that you need to know for the tutorial on ‘TensorFlow.’

Why use NumPy?

NumPy is memory efficiency, meaning it can handle the vast amount of data more accessible than any other library. Besides, NumPy is very convenient to work with, especially for matrix multiplication and reshaping. On top of that, NumPy is fast. In fact, TensorFlow and Scikit learn to use NumPy array to compute the matrix multiplication in the back end. In this Python NumPy Tutorial, we will learn:

How to Install NumPy Python NumPy Array numpy.zeros() & numpy.ones() in Python numpy.reshape() and numpy.flatten() in Python numpy.hstack() and numpy.vstack() in Python numpy.asarray() in Python with Example np.arange() Function numpy.linspace() and numpy.logspace() in Python Indexing and Slicing NumPy Arrays NumPy Statistical Functions with Example Numpy Dot Product Function NumPy Matrix Multiplication with np.matmul() Example

How to Install NumPy

To install NumPy library, please refer our tutorial How to install TensorFlow. NumPy is installed by default with Anaconda. In remote case, NumPy not installed- You can install NumPy using Anaconda:

In Jupyter Notebook :

Import NumPy and Check Version

The command to import numpy is: Above code renames the Numpy namespace to np. This permits us to prefix Numpy function, methods, and attributes with ” np ” instead of typing ” numpy.” It is the standard shortcut you will find in the numpy literature To check your installed version of NumPy, use the below command: Output:

What is Python NumPy Array?

NumPy arrays are a bit like Python lists, but still very much different at the same time. For those of you who are new to the topic, let’s clarify what it exactly is and what it’s good for. As the name kind of gives away, a NumPy array is a central data structure of the numpy library. The library’s name is actually short for “Numeric Python” or “Numerical Python”.

Creating a NumPy Array

Simplest way to create an array in Numpy is to use Python List To convert python list to a numpy array by using the object np.array. To display the contents of the list Output: In practice, there is no need to declare a Python List. The operation can be combined. NOTE: Numpy documentation states use of np.ndarray to create an array. However, this the recommended method. You can also create a numpy array from a Tuple.

Mathematical Operations on an Array

You could perform mathematical operations like additions, subtraction, division and multiplication on an array. The syntax is the array name followed by the operation (+.-,*,/) followed by the operand Example: Output: This operation adds 10 to each element of the numpy array.

Shape of Array

You can check the shape of the array with the object shape preceded by the name of the array. In the same way, you can check the type with dtypes. An integer is a value without decimal. If you create an array with decimal, then the type will change to float.

2 Dimension Array

You can add a dimension with a “,”coma Note that it has to be within the bracket []

3 Dimension Array

Higher dimension can be constructed as follow: Python numpy.zeros() Example numpy.zeros() function Syntax Python numpy.zeros() Parameters Here,

Shape: is the shape of the numpy zero array Dtype: is the datatype in numpy zeros. It is optional. The default value is float64 Order: Default is C which is an essential row style for numpy.zeros() in Python.

Output: Example of numpy zero with Datatype Output: Python numpy.ones() 2D Array with Datatype Example Python numpy.ones() Syntax Python numpy.ones() Parameters Here,

Shape: is the shape of the np.ones Python Array Dtype: is the datatype in numpy ones. It is optional. The default value is float64 Order: Default is C which is an essential row style.

Output: After studying NumPy vstack and hstack, let’s learn an example to generate random numbers in NumPy. Syntax of np.reshape() Here, a: Array that you want to reshape newShape: The new desires shape Order: Default is C which is an essential row style. Example of NumPy Reshape Output: Syntax of np.flatten() Here, Order: Default is C which is an essential row style. Example of NumPy Flatten Output: Lets study hstack in Python with an example: Example: Output: Lets study it with an example: Example: Output:

Generate Random Numbers using NumPy

To generate random numbers for Gaussian distribution, use: Here,

Loc: the mean. The center of distribution Scale: standard deviation. Size: number of returns

Example: If plotted the distribution will be similar to following plot

NumPy Asarray Function

The asarray()function is used when you want to convert an input to an array. The input could be a lists, tuple, ndarray, etc. Syntax: Here, data: Data that you want to convert to an array dtype: This is an optional argument. If not specified, the data type is inferred from the input data Order: Default is C which is an essential row style. Other option is F (Fortan-style) Example: Consider the following 2-D matrix with four rows and four columns filled by 1 If you want to change the value of the matrix, you cannot. The reason is, it is not possible to change a copy. Matrix is immutable. You can use asarray if you want to add modification in the original array. Let’s see if any change occurs when you want to change the value of the third rows with the value 2. Code Explanation: np.asarray(A): converts the matrix A to an array [2]: select the third rows Output: Syntax: Python NumPy arange Parameters:

Start: Start of interval for np.arange in Python function. Stop: End of interval. Step: Spacing between values. Default step is 1. Dtype: Is a type of array output for NumPy arange in Python.

Example: Output: Example: If you want to change the step in this NumPy arange function in Python example, you can add a third number in the parenthesis. It will change the step. Output:

NumPy Linspace Function

Linspace gives evenly spaced samples. Syntax: Here,

Start: Starting value of the sequence Stop: End value of the sequence Num: Number of samples to generate. Default is 50 Endpoint: If True (default), stop is the last value. If False, stop value is not included.

Example: For instance, it can be used to create 10 values from 1 to 5 evenly spaced. Output: If you do not want to include the last digit in the interval, you can set endpoint to false Output:

LogSpace NumPy Function in Python

LogSpace returns even spaced numbers on a log scale. Logspace has the same parameters as np.linspace. Syntax: Example: Output: Finaly, if you want to check the memory size of an element in an array, you can use itemsize Output: Each element takes 16 bytes.

Indexing and Slicing in Python

Slicing data is trivial with numpy. We will slice the matrice “e”. Note that, in Python, you need to use the brackets to return the rows or columns Example: Remember with numpy the first array/column starts at 0. Output: In Python, like many other languages,

The values before the comma stand for the rows
The value on the rights stands for the columns.
If you want to select a column, you need to add : before the column index.
means you want all the rows from the selected column.

To return the first two values of the second row. You use : to select all columns up to the second

Statistical Functions in Python

NumPy has quite a few useful statistical functions for finding minimum, maximum, percentile standard deviation and variance, etc from the given elements in the array. The functions are explained as follows − Numpy is equipped with the robust statistical function as listed below Consider the following Array: Example: Output: Example of NumPy Statistical function Output: Syntax: Parameters Here, x,y: Input arrays. x and y both should be 1-D or 2-D for the np.dot() function to work out: This is the output argument for 1-D array scalar to be returned. Otherwise ndarray should be returned. Returns The function numpy.dot() in Python returns a Dot product of two arrays x and y. The dot() function returns a scalar if both x and y are 1-D; otherwise, it returns an array. If ‘out’ is given then it is returned. Raises Dot product in Python raises a ValueError exception if the last dimension of x does not have the same size as the second last dimension of y. Example: Output:

Matrix Multiplication in Python

The Numpy matmul() function is used to return the matrix product of 2 arrays. Here is how it works

  1. 2-D arrays, it returns normal product
  2. Dimensions > 2, the product is treated as a stack of matrix
  3. 1-D array is first promoted to a matrix, and then the product is calculated Syntax: Here, x,y: Input arrays. scalars not allowed out: This is optional parameter. Usually output is stored in ndarray Example: In the same way, you can compute matrices multiplication with np.matmul Output:

Determinant

Last but not least, if you need to compute the determinant, you can use np.linalg.det(). Note that numpy takes care of the dimension. Example: Output:

Summary

NumPy is an open source library available in Python, which helps in mathematical, scientific, engineering, and data science programming. numpy.zeros() or np.zeros Python function is used to create a matrix full of zeroes. numpy.ones() in Python can be used when you initialize the weights during the first iteration in TensorFlow and other statistic tasks. Python NumPy Reshape function is used to shape an array without changing its data. Python NumPy Flatten function is used to return a copy of the array in one-dimension. Numpy.hstack is a function in Python that is used to horizontally stack sequences of input arrays in order to make a single array. Numpy.vstack is a function in Python which is used to vertically stack sequences of input arrays in order to make a single array. numpy.arange() is an inbuilt numpy function that returns an ndarray object containing evenly spaced values within a defined interval. Numpy.dot product is a powerful library for matrix computation. The Numpy matmul() function is used to return the matrix product of 2 arrays.