Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating gradient with NumPy

I really can not understand what numpy.gradient function does and how to use it for computation of multivariable function gradient.

For example, I have such a function:

def func(q, chi, delta):     return q * chi * delta 

I need to compute it's 3-dimensional gradient (in other words, I want to compute partial derivatives with respect to all variables (q, chi, delta)).

How can I calculate this gradient using NumPy?

like image 539
Mikhail Elizarev Avatar asked Apr 18 '13 09:04

Mikhail Elizarev


People also ask

How does Numpy calculate gradient?

The gradient is computed using second order accurate central differences in the interior points and either first or second order accurate one-sides (forward or backwards) differences at the boundaries. The returned gradient hence has the same shape as the input array.

How do you find the gradient of a function in Python?

We will use numdifftools to find Gradient of a function. Examples: Input : x^4+x+1 Output :Gradient of x^4+x+1 at x=1 is 4.99 Input :(1-x)^2+(y-x^2)^2 Output :Gradient of (1-x^2)+(y-x^2)^2 at (1, 2) is [-4.

Is Numpy gradient a derivative?

The output of numpy. gradient() function is a list of ndarrays (or a single ndarray if there is only one dimension) corresponding to the derivatives of input f with respect to each dimension. Each derivative has the same shape as input f .

What is gradient Python?

gradient is the function or any Python callable object that takes a vector and returns the gradient of the function you're trying to minimize. start is the point where the algorithm starts its search, given as a sequence (tuple, list, NumPy array, and so on) or scalar (in the case of a one-dimensional problem).


1 Answers

The problem is, that numpy can't give you the derivatives directly and you have two options:

With NUMPY

What you essentially have to do, is to define a grid in three dimension and to evaluate the function on this grid. Afterwards you feed this table of function values to numpy.gradient to get an array with the numerical derivative for every dimension (variable).

Example from here:

from numpy import *  x,y,z = mgrid[-100:101:25., -100:101:25., -100:101:25.]  V = 2*x**2 + 3*y**2 - 4*z # just a random function for the potential  Ex,Ey,Ez = gradient(V) 

Without NUMPY

You could also calculate the derivative yourself by using the centered difference quotient. centered difference quotient

This is essentially, what numpy.gradient is doing for every point of your predefined grid.

like image 82
Stefan Avatar answered Oct 01 '22 13:10

Stefan