- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一组模拟数据,我想在其中找到 n 维中的最低斜率。数据的间距在每个维度上都是恒定的,但并不完全相同(为了简单起见,我可以更改它)。
我可以忍受一些数值上的不准确,尤其是在边缘处。我非常不希望生成样条曲线并使用该导数;仅基于原始值就足够了。
可以使用 numpy.gradient()
函数计算 numpy
的一阶导数。
import numpy as np
data = np.random.rand(30,50,40,20)
first_derivative = np.gradient(data)
# second_derivative = ??? <--- there be kudos (:
这是关于拉普拉斯与海森矩阵的评论;这不再是一个问题,而是为了帮助 future 的读者理解。
我使用二维函数作为测试用例来确定低于阈值的“最平坦”区域。以下图片显示了使用 second_derivative_abs = np.abs(laplace(data))
的最小值与以下最小值的结果差异:
second_derivative_abs = np.zeros(data.shape)
hess = hessian(data)
# based on the function description; would [-1] be more appropriate?
for i in hess[0]: # calculate a norm
for j in i[0]:
second_derivative_abs += j*j
色标表示函数值,箭头表示一阶导数(梯度),红点表示最接近零的点,红线表示阈值。
数据的生成器函数是 ( 1-np.exp(-10*xi**2 - yi**2) )/100.0
其中 xi、yi 是用 生成的np.meshgrid
.
拉普拉斯:
黑森州:
最佳答案
二阶导数由 Hessian matrix 给出.这是 ND 数组的 Python 实现,包括两次应用 np.gradient
并适本地存储输出,
import numpy as np
def hessian(x):
"""
Calculate the hessian matrix with finite differences
Parameters:
- x : ndarray
Returns:
an array of shape (x.dim, x.ndim) + x.shape
where the array[i, j, ...] corresponds to the second derivative x_ij
"""
x_grad = np.gradient(x)
hessian = np.empty((x.ndim, x.ndim) + x.shape, dtype=x.dtype)
for k, grad_k in enumerate(x_grad):
# iterate over dimensions
# apply gradient again to every component of the first derivative.
tmp_grad = np.gradient(grad_k)
for l, grad_kl in enumerate(tmp_grad):
hessian[k, l, :, :] = grad_kl
return hessian
x = np.random.randn(100, 100, 100)
hessian(x)
请注意,如果您只对二阶导数的大小感兴趣,则可以使用 Laplace operator由 scipy.ndimage.filters.laplace
实现, 是Hessian矩阵的迹(对角线元素之和)。
取 Hessian 矩阵的最小元素可用于估计任何空间方向上的最低斜率。
关于python - n维数组的numpy二阶导数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31206443/
在做 Ch06 的练习 6.5 时 |在 Middlebrook 博士的 D-OA 方法中,我尝试制作传递函数的波德图: bodeplot[s/100+100/s*(1+10/s)](wolframa
我正在尝试做这样的事情 编辑 - 整个查询。 SELECT * FROM ride WHERE ( SELECT COUNT(*) FROM ( SELECT DISTINCT
我尝试求解简单的数值方程 - 没有源的线性波动方程:utt = v2 uxx 其中 v - 波速。 我使用初始条件: u(x, 0) = sin(x) ux(x, 0) = -v * sin(x) 对
我正在尝试使用 C++ 求解 4 个二阶多项式方程组。解决该系统的最快方法是什么?如果可能,您能否链接或编写一些伪代码来解释它?我知道涉及 Groebners 基础或 QR 分解的解决方案,但我找不到
我在 Checkmarx 中遇到错误。 Method abortJob at line 209 of XXX/classes/Monitoring.cls gets user inputfrom th
对于二阶 ODE(python 中的 dopri5 方法),下面的代码总是会导致错误:C:\Users\MY\Anaconda3\lib\site-packages\scipy\integrate\_
重要更新:我已经找到答案并将它们放在这个简单的开源库中:http://bartolsthoorn.github.com/NVDSP/检查一下,如果您在 IOS 中遇到音频过滤器问题,它可能会为您节省不
我是一名优秀的程序员,十分优秀!