numpy中的二阶梯度

2024-04-25 17:29:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用数值方法计算阵列的二阶梯度。

a = np.sin(np.arange(0, 10, .01))
da = np.gradient(a)
dda = np.gradient(da)

这就是我想到的。应该这样做吗?

我这么问是因为在numpy中没有np.gradient(a,order=2)的选项。我担心这个用法是否错误,这就是为什么numpy没有实现这个。

PS1:我确实意识到有np.diff(a,2)。但这只是单侧估计,所以我很好奇为什么np.gradient没有类似的关键字。

PS2:np.sin()是一个玩具数据-实际数据没有分析形式。

谢谢你!


Tags: 数据方法numpy选项npordersinda
3条回答

这是原始文档的摘录(在编写本文时,可在http://docs.scipy.org/doc/numpy/reference/generated/numpy.gradient.html找到)。它指出,除非采样距离为1,否则需要包含包含距离的列表作为参数。

numpy.gradient(f, *varargs, **kwargs)

Return the gradient of an N-dimensional array.

The gradient is computed using second order accurate central differences in the interior and either first differences 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.

Parameters:
f : array_like An N-dimensional array containing samples of a scalar function.

varargs : list of scalar, optional N scalars specifying the sample distances for each dimension, i.e. dx, dy, dz, ... Default distance: 1.

edge_order : {1, 2}, optional Gradient is calculated using Nth order accurate differences at the boundaries. Default: 1. New in version 1.9.1.

Returns:
gradient : ndarray N arrays of the same shape as f giving the derivative of f with respect to each dimension.

我会支持jrennie的第一句话-这完全取决于。numpy.gradient函数要求数据均匀分布(尽管如果是多维的,则允许每个方向上的距离不同)。如果你的数据不符合这一点,那么numpy.gradient就没有多大用处了。实验数据可能有(好的,会有)噪声,除了不一定都是均匀分布的。在这种情况下,最好使用scipy.interpolate样条函数(或对象)之一。这些函数可以取间隔不均的数据,允许平滑,并且可以返回高达k-1的导数,其中k是请求的样条曲线拟合顺序。k的默认值是3,所以二阶导数就可以了。 示例:

spl = scipy.interpolate.splrep(x,y,k=3) # no smoothing, 3rd order spline
ddy = scipy.interpolate.splev(x,spl,der=2) # use those knots to get second derivative 

像scipy.interpolate.UnivariateSpline这样的面向对象的样条函数有求导数的方法。请注意,派生方法在Scipy 0.13中实现,而在0.12中不存在。

注意,正如@JosephCottham在2018年的评论中指出的,这个答案(至少对Numpy 1.08有好处)不再适用,因为(至少)Numpy 1.14。检查您的版本号和呼叫的可用选项。

数值梯度计算没有普遍的正确答案。在计算样本数据的梯度之前,必须对生成该数据的底层函数做一些假设。技术上可以使用np.diff进行梯度计算。使用np.gradient是一种合理的方法。我看不出你所做的有什么本质上的错误——这是一维函数的二阶导数的一种特殊近似。

相关问题 更多 >