numpy.gradient¶
-
numpy.
gradient
(f, *varargs, **kwargs)[source]¶ Return the gradient of an N-dimensional array.
计算梯度:内部使用二阶精确中心差,边界处使用一阶差或二阶精确单边(向前或向后)差。The returned gradient hence has the same shape as the input array.
Parameters: f : array_like
An N-dimensional array containing samples of a scalar function.
varargs : scalar or list of scalar, optional
N个标量,其指定每个维度的样本距离,即dx、dy、dz等。默认距离:1。只有一个标量表示所有维度的样本距离。如果给定axis,则varargs的数量必须等于轴的数量。
edge_order : {1, 2}, optional
边界处使用的Nth阶精度差来计算梯度。Default: 1.
New in version 1.9.1.
axis:None、整数或整数元组,可选
仅沿给定轴计算梯度。默认值(axis = None)用于计算输入数组的所有轴的梯度。axis may be negative, in which case it counts from the last to the first axis.
New in version 1.11.0.
Returns: gradient : ndarray列表
Each element of list has the same shape as f giving the derivative of f with respect to each dimension.
Examples
>>> x = np.array([1, 2, 4, 7, 11, 16], dtype=np.float) >>> np.gradient(x) array([ 1. , 1.5, 2.5, 3.5, 4.5, 5. ]) >>> np.gradient(x, 2) array([ 0.5 , 0.75, 1.25, 1.75, 2.25, 2.5 ])
对于二维数组,返回将是按轴排序的两个数组。In this example the first array stands for the gradient in rows and the second one in columns direction:
>>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=np.float)) [array([[ 2., 2., -1.], [ 2., 2., -1.]]), array([[ 1. , 2.5, 4. ], [ 1. , 1. , 1. ]])]
>>> x = np.array([0, 1, 2, 3, 4]) >>> dx = np.gradient(x) >>> y = x**2 >>> np.gradient(y, dx, edge_order=2) array([-0., 2., 4., 6., 8.])
axis关键字可用于指定轴的一个子集来计算梯度
>>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=np.float), axis=0) array([[ 2., 2., -1.], [ 2., 2., -1.]]