假设我在NumPy中有一个数组,包含一个连续可微函数的求值,我想找到局部极小值。没有噪声,所以每个点的值都低于它所有邻居的值,这就满足了我的局部最小值的标准。
我有以下列表理解,它适用于二维数组,忽略边界上的潜在最小值:
import numpy as N
def local_minima(array2d):
local_minima = [ index
for index in N.ndindex(array2d.shape)
if index[0] > 0
if index[1] > 0
if index[0] < array2d.shape[0] - 1
if index[1] < array2d.shape[1] - 1
if array2d[index] < array2d[index[0] - 1, index[1] - 1]
if array2d[index] < array2d[index[0] - 1, index[1]]
if array2d[index] < array2d[index[0] - 1, index[1] + 1]
if array2d[index] < array2d[index[0], index[1] - 1]
if array2d[index] < array2d[index[0], index[1] + 1]
if array2d[index] < array2d[index[0] + 1, index[1] - 1]
if array2d[index] < array2d[index[0] + 1, index[1]]
if array2d[index] < array2d[index[0] + 1, index[1] + 1]
]
return local_minima
然而,这是相当缓慢的。我还想让这个工作的任何数量的维度。例如,有没有一种简单的方法可以得到任意维数组中某个点的所有邻域?或者我完全错误地对待这个问题?我应该改用numpy.gradient()
吗?
试试这个2D:
这将返回一个array2d类型的数组,在本地最小值(四个邻居)所在的位置为True/False。
对于任意维的数组,可以找到局部极小值的位置 使用Ivan的detect_peaks function,稍加修改:
你可以这样使用:
这表示最小值出现在指数[0,0,3]、[0,4,0]、[1,1,1]和[1,3,3]:
相关问题 更多 >
编程相关推荐