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.

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

Answer from Stefan on Stack Overflow
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ stable โ€บ reference โ€บ generated โ€บ numpy.gradient.html
numpy.gradient โ€” NumPy v2.4 Manual
Gradient is calculated only along the given axis or axes The default (axis = None) is to calculate the gradient for all the axes of the input array.
Top answer
1 of 1
31

You need to give gradient a matrix that describes your angular frequency values for your (x,y) points. e.g.

def f(x,y):
    return np.sin((x + y))
x = y = np.arange(-5, 5, 0.05)
X, Y = np.meshgrid(x, y)
zs = np.array([f(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))])
Z = zs.reshape(X.shape)

gx,gy = np.gradient(Z,0.05,0.05)

You can see that plotting Z as a surface gives:

Here is how to interpret your gradient:

gx is a matrix that gives the change dz/dx at all points. e.g. gx[0][0] is dz/dx at (x0,y0). Visualizing gx helps in understanding:

Since my data was generated from f(x,y) = sin(x+y) gy looks the same.

Here is a more obvious example using f(x,y) = sin(x)...

f(x,y)

and the gradients

update Let's take a look at the xy pairs.

This is the code I used:

def f(x,y):
    return np.sin(x)
x = y = np.arange(-3,3,.05)
X, Y = np.meshgrid(x, y)
zs = np.array([f(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))])
xy_pairs = np.array([str(x)+','+str(y) for x,y in zip(np.ravel(X), np.ravel(Y))])
Z = zs.reshape(X.shape)
xy_pairs = xy_pairs.reshape(X.shape)

gy,gx = np.gradient(Z,.05,.05)

Now we can look and see exactly what is happening. Say we wanted to know what point was associated with the value atZ[20][30]? Then...

>>> Z[20][30]
-0.99749498660405478

And the point is

>>> xy_pairs[20][30]
'-1.5,-2.0'

Is that right? Let's check.

>>> np.sin(-1.5)
-0.99749498660405445

Yes.

And what are our gradient components at that point?

>>> gy[20][30]
0.0
>>> gx[20][30]
0.070707731517679617

Do those check out?

dz/dy always 0 check. dz/dx = cos(x) and...

>>> np.cos(-1.5)
0.070737201667702906

Looks good.

You'll notice they aren't exactly correct, that is because my Z data isn't continuous, there is a step size of 0.05 and gradient can only approximate the rate of change.

๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 2.1 โ€บ reference โ€บ generated โ€บ numpy.gradient.html
numpy.gradient โ€” NumPy v2.1 Manual
Gradient is calculated only along the given axis or axes The default (axis = None) is to calculate the gradient for all the axes of the input array.
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ how-to-use-the-numpygradient-function-for-a-2d-array-in-python
How to use the numpy.gradient function for a 2D array in Python
gradient: This will calculate the gradient using Nth order (as specified by edge_order) accurate boundary differences.
๐ŸŒ
Integratedmlai
integratedmlai.com โ€บ gradient-descent-using-pure-python-without-numpy-or-scipy
Gradient Descent Using Pure Python without Numpy or Scipy โ€“ Integrated Machine Learning and Artificial Intelligence
February 29, 2020 - Equations 2 show us the calculus steps for finding the gradient (slope) for the equation of a line. HOWEVER, remember, differentiation is an analytical determination of the gradient (i.e. slope) of a function at any given set of inputs. IF EVER NECESSARY, we could numerically differentiate a function at different inputs.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ how-to-find-gradient-of-a-function-using-python
How to find Gradient of a Function using Python? | GeeksforGeeks
July 28, 2020 - Numpy in Python is a general-purpose array-processing package. It provides a high-performance multidimensional array object and tools for working with these arrays. It is the fundamental package for scientific computing with Python. Numpy provides very easy methods to calculate the average, variance
๐ŸŒ
Medium
medium.com โ€บ @ilmunabid โ€บ how-to-find-a-gradient-slope-of-a-function-in-python-774f865467d2
What is Gradient/Slope? and How to Calculate One in Python (SymPy) | Medium
June 5, 2022 - derivative is used to find the gradient of a curve or to measure steepness. it is also called the rate of change. so we take the change in y and divide that with the change in x
Find elsewhere
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 2.0 โ€บ reference โ€บ generated โ€บ numpy.gradient.html
numpy.gradient โ€” NumPy v2.0 Manual
Gradient is calculated only along the given axis or axes The default (axis = None) is to calculate the gradient for all the axes of the input array.
๐ŸŒ
Medium
surajsinghbisht054.medium.com โ€บ mastering-gradient-descent-math-python-and-the-magic-behind-machine-learning-d12a7791f24e
Mastering Gradient Descent: Math, Python, and the Magic Behind Machine Learning โ€” Part 1 | by Suraj Singh Bisht | Medium
December 26, 2023 - In this article, Iโ€™ll explain what gradient descent is, why itโ€™s crucial to learn, the basic math behind it, and how it benefits machine learning, and Iโ€™ll even provide a straightforward Python code example. This code example will simulate a PyTorch tensor class wrapper to automatically calculate gradient values, among other things.
๐ŸŒ
Kodeclik
kodeclik.com โ€บ numpy-gradient
Python numpy.gradient()
October 16, 2024 - For the last line, note that 7 is (8-1)/(2-1). Similarly, 13 is (27-1)/(3-1) and 19 is (27-8)/(3-2). Note that if we were to do this analytically, the derivatives will be given by 3*x*x, or [3 12 27] which is not quite the same as what is returned. This is because numpy.gradient() uses finite difference approximations (as shown by the above calculations) which have approximation errors.
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ what is the numpy.gradient() method in numpy?
What is the numpy.gradient() method in Numpy? - Scaler Topics
May 4, 2023 - The gradient is calculated using the numpy gradient() function by utilizing either the first or second-order correct one-sides (in either direction) differences at the boundaries and second-order accurate central differences in the interior ...
๐ŸŒ
AskPython
askpython.com โ€บ home โ€บ numpy gradient: returning the gradient of n-dimensional array
Numpy Gradient: Returning the Gradient of N-dimensional Array - AskPython
December 29, 2022 - edge_order โ€“ an optional provision that deals with the boundaries at which the gradient is to be calculated. It can be set as โ€˜1โ€™ or โ€˜2โ€™, with the former being the default setting ยท Python calculates the gradient by finding the difference,
๐ŸŒ
IncludeHelp
includehelp.com โ€บ python โ€บ calculating-gradient-with-numpy.aspx
Calculating gradient with NumPy
# Import numpy import numpy as np # Creating a grid x,y,z = np.mgrid[-2:1:2, -2:1:2, -2:1:2] # Display 3 dimensions print("x:\n",x,"\n") print("y:\n",y,"\n") print("z:\n",z,"\n") # Defining an expresion ex = 2*x**2 + 3*y**2 - 4*z # Calculating gradient x_r = np.gradient(ex) y_r = np.gradient(ex) z_r = np.gradient(ex) # Display result print("x:\n",x_r,"\n") print("y:\n",y_r,"\n") print("z:\n",z_r,"\n")
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 62714673 โ€บ how-can-i-calculate-the-gradient-of-a-vector-field-from-its-values
python 3.x - How can I calculate the gradient of a vector field from its values? - Stack Overflow
import numpy as np N = 100 limit = .1 def vec(x,y,z): # Example vector field return np.array([x,x,z]) x = np.arange(-limit, limit, 2*limit/N) # np.arange takes the spacing as 3. arg y = np.arange(-limit, limit, 2*limit/N) z = np.arange(-limit, limit, 2*limit/N) # Create 3D grid from 1D arrays, indexing is important! X,Y,Z = np.meshgrid(x,y,z,indexing='ij') V = vec(X,Y,Z) # Get vector field, shape: (3,N,N,N) D = np.gradient(V, x, y, z, axis=(1,2,3)) # Get gradient, this is a list!
Top answer
1 of 3
3

In Python you can use the numpy.gradient function to do this. This said function uses central differences for the computation, like so: \begin{eqnarray} \nabla_x I (i, j) = \frac{I(i + 1, j) - I(i - 1, j)}{2}, \hspace{.5em}\nabla_y I (i, j) = \frac{I(i, j+1) - I(i, j-1)}{2}. \end{eqnarray}

Here is a code snippet for your specific image:

import numpy as np
import matplotlib.pyplot as plt

# load image
img = np.array([[21.0, 20.0, 22.0, 24.0, 18.0, 11.0, 23.0],
                [21.0, 20.0, 22.0, 24.0, 18.0, 11.0, 23.0],
                [21.0, 20.0, 22.0, 24.0, 18.0, 11.0, 23.0],
                [21.0, 20.0, 22.0, 99.0, 18.0, 11.0, 23.0],
                [21.0, 20.0, 22.0, 24.0, 18.0, 11.0, 23.0],
                [21.0, 20.0, 22.0, 24.0, 18.0, 11.0, 23.0],
                [21.0, 20.0, 22.0, 24.0, 18.0, 11.0, 23.0]])
print "image =", img

# compute gradient of image
gx, gy = np.gradient(img)
print "gx =", gx
print "gy =", gy

# plotting
plt.close("all")
plt.figure()
plt.suptitle("Image, and it gradient along each axis")
ax = plt.subplot("131")
ax.axis("off")
ax.imshow(img)
ax.set_title("image")

ax = plt.subplot("132")
ax.axis("off")
ax.imshow(gx)
ax.set_title("gx")

ax = plt.subplot("133")
ax.axis("off")
ax.imshow(gy)
ax.set_title("gy")
plt.show()

To answer your specific question, the gradient (via central differences!) of the image at pixel with value $99$ is $0$ along the $x$ axis and $-2$ along the $y$ axis.

2 of 3
1

Suppose the image is continuous and differentiable in $x$ and $y$. Then $I(x,y)$ is the value of the pixel at each $(x,y)$, i.e. $I: \mathbb{R}^2 \mapsto \mathbb{R}$. Recall that the gradient at a point $(u,v)$ is:

$$ \nabla I(u,v) = \begin{bmatrix} \frac{\partial I}{\partial x}(u,v) \\ \frac{\partial I}{\partial y}(u,v) \end{bmatrix} $$

Given a discrete grid, you should approximate the partial derivative in $x$ and $y$ directions using finite difference approximations at the point of interest.

Assume your function $I$ is sampled over points $\{1, \ldots, 7 \} \times \{1, \ldots, 7 \}$ in image-coordinates, i.e. $I(1,1) = 21$, $I(1,7) = 23$, etc... So you're looking for the gradient at $(4,4)$. If you assume the resolution between points is 1, then the forward difference approximation in the $x$ direction gives:

$$ \frac{\partial I}{\partial x}(4,4) \approx I(5,4) - I(4,4) = 24 - 99 $$

Do the same in $y$ to obtain the full gradient at the point.

๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Higher order central differences using NumPy.gradient() - Python Help - Discussions on Python.org
September 5, 2022 - Hello everyone, I am new to Python and am still learning it. So my apologies if this is a basic question. I am given two arrays: X and Y. Where Y=2*(x^2)+x/2. I need to calculate the first and the fifth order central differences of Y with respect to X using the numpy.gradient function.
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ np.gradient() โ€” a simple illustrated guide
np.gradient() - A Simple Illustrated Guide - Be on the Right Side of Change
June 24, 2022 - In Python, the numpy.gradient() function approximates the gradient of an N-dimensional array. It uses the second-order accurate central differences in the interior points and either first or second-order accurate one-sided differences at the ...