What does numpy.gradient do?

匿名 (未验证) 提交于 2019-12-03 02:56:01

问题:

So I know what the gradient of a (mathematical) function is, so I feel like I should know what numpy.gradient does. But I don't. The documentation is not really helpful either:

Return the gradient of an N-dimensional array.

What is the gradient of an array? When is numpy.gradient useful?

回答1:

The gradient is computed using central differences in the interior and first differences at the boundaries.

and

The default distance is 1

This means that in the interior it is computed as

where h = 1.0

and at the boundaries



回答2:

Also in the documentation1:

>>> y = np.array([1, 2, 4, 7, 11, 16], dtype=np.float) >>> j = np.gradient(y) >>> j  array([ 1. ,  1.5,  2.5,  3.5,  4.5,  5. ]) 
  • Gradient is defined as (change in y)/(change in x).
  • x, here, is the index, so the difference between adjacent values is 1.

  • At the boundaries, the first difference is calculated. This means that at each end of the array, the gradient given is simply, the difference between the end two values (divided by 1)

  • Away from the boundaries the gradient for a particular index is given by taking the difference between the the values either side and dividing by 2.

So, the gradient of y, above, is calculated thus:

j[0] = (y[1]-y[0])/1 = (2-1)/1  = 1 j[1] = (y[2]-y[0])/2 = (4-1)/2  = 1.5 j[2] = (y[3]-y[1])/2 = (7-2)/2  = 2.5 j[3] = (y[4]-y[2])/2 = (11-4)/2 = 3.5 j[4] = (y[5]-y[3])/2 = (16-7)/2 = 4.5 j[5] = (y[5]-y[4])/1 = (16-11)/1 = 5 

You could find the minima of all the absolute values in the resulting array to find the turning points of a curve, for example.


1The array is actually called x in the example in the docs, I've changed it to y to avoid confusion.



回答3:

Think about N-dimensional array as a matrix. Then gradient is nothing else as matrix differentiation

For a good explanation look at gradient description in matlab documentation.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!