Numpy Gradient Examples using numpy.gradient() method.

Numpy Gradient Examples featured image

Numpy is the best python module that allows you to do any mathematical calculations on your arrays. For example, you can convert NumPy array to the image, NumPy array, NumPy array to python list, and many things. But here in this tutorial, I will show you how to use the NumPy gradient with simple examples using the numpy.gradient() method.

 

What is Gradient?

In mathematics, Gradient is a vector that contains the partial derivatives of all variables. Like in 2- D you have a gradient of two vectors, in 3-D 3 vectors, and show on.

In NumPy, the gradient is computed using central differences in the interior and it is of first or second differences (forward or backward)  at the boundaries.  Let’s calculate the gradient of a function using numpy.gradient() method. But before that know the syntax of the gradient() method.

numpy.gradient(f, *varargs, axis=None, edge_order=1)

The numpy.gradient() function accepts the following important parameters.

f: The input array on which you want to calculate the gradient.

varargs: It is a list of scalars or arrays.

axis: Either 0 or 1  to do calculation row-wise or column-wise. The default value is None.

edge_order: {1, 2}, and it is optional. The gradient is calculated using N-th order accurate differences at the boundaries. The default value is 1.

Step by Step to calculate Numpy Gradient

Here you will know all the steps to compute the NumPy gradient of an array. Just follow the below steps.

Step 1: Import all the necessary libraries

Here I am using only NumPy python modules so importing it only. You can import any module in python using an import statement.

import numpy as np

Step 2: Create a Dummy Numpy Array.

For the demonstration purpose lets the first create a NumPy array to calculate the numpy gradient. You can create a NumPy array using numpy.array() method like below. However, you can use your own dataset for gradient calculations.

Example 1: Simple Numpy Array Gradient.

numpy_array = np.array([1, 2, 4, 7, 11, 16], dtype=float)

First-order Differences Gradient

np.gradient(numpy_array)

Second-Order Differences Gradient

np.gradient(numpy_array,2)

Example 2: Calculation of Gradient using other NumPy arrays.

You can also calculate the gradient of a NumPy array with another NumPy array. Let’s create a second NumPy array.

numpy_array2 = np.array([2, 1, 5, 10, 11, 15], dtype=float)
np.gradient(numpy_array,numpy_array2)

Example 3: Gradient for the N-dimensional NumPy array

You can calculate the gradient for the N dimension NumPy array. The gradient will of the same dimension as the dimension array. Let’s create a two-dimensional NumPy array.

numpy_array_2d = np.array([[10,20,30],[40,50,60]],dtype=float)

Use the code below to calculate the gradient.

np.gradient(numpy_array_2d)

The above code will return two arrays. The first one is the gradient of all the row values and the second one is the gradient along the column.

If you want to calculate row-wise then pass the axis =0 as an argument to the gradient() method and for column-wise axis =1.

These are some basic examples that show you how to calculate numpy gradient of a NumPy array. If you have also a dataset or excel file then you can read it using the pandas module and then extract data as a NumPy array.

Hope you have liked this article if you have any query or wants to know more then please contact us. We are always ready for help.

Other Examples

Numpy gradient of a function

Just like you can find the gradient for a single or multidimensional array. You can also find the NumPy gradient of a function using numdifftools python package. Suppose I have a function that returns polynomial expression on x. To find the gradient of the function I will pass the function name as an argument to the Gradient() method with the value in the square bracket.

Execute the below lines of code.

import numdifftools as nd

def f1(x):
    return x**2 + 1
grad = nd.Gradient(f1)([1])
print(grad)

Output

Gradient of a function in Python
A gradient of a function in Python

Other Queries

Question: I have got No module named pandas error.

This error comes when you are using the pandas module in your code but you have not installed it. To remove this error just install pandas array. It will remove this import error.

You can install pandas using the pip command.

For python 2.xx version

pip install pandas

For python 3.xx version

pip3 install pandas

 

Similar Numpy Functions –

Numpy Random Choice : Create Random Sample Array

Find Max and Min Value of Numpy Array with its index ( 1D & 2D)

Numpy cov() method Implementation in Python : 3 Steps Only

Thanks

DSL Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Meet Sukesh ( Chief Editor ), a passionate and skilled Python programmer with a deep fascination for data science, NumPy, and Pandas. His journey in the world of coding began as a curious explorer and has evolved into a seasoned data enthusiast.
 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner