如何在 NumPy 中找到平滑多维数组的局部最小值
假设我在 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() 来代替吗?
Say I have an array in NumPy containing evaluations of a continuous differentiable function, and I want to find the local minima. There is no noise, so every point whose value is lower than the values of all its neighbors meets my criterion for a local minimum.
I have the following list comprehension which works for a two-dimensional array, ignoring potential minima on the boundaries:
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
However, this is quite slow. I would also like to get this to work for any number of dimensions. For example, is there an easy way to get all the neighbors of a point in an array of any dimensions? Or am I approaching this problem the wrong way altogether? Should I be using numpy.gradient()
instead?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可以为任意维度的数组找到局部最小值的位置
使用伊万的detect_peaks 函数,稍加修改:
您可以像这样使用:
这表示最小值出现在索引 [0,0,3]、[0,4,0]、[1,1,1] 和 [1,3,3]:
The location of the local minima can be found for an array of arbitrary dimension
using Ivan's detect_peaks function, with minor modifications:
which you can use like this:
This says the minima occur at indices [0,0,3], [0,4,0], [1,1,1] and [1,3,3]:
尝试进行 2D 操作:
这将返回一个类似于 array2d 的数组,其中包含 True/False,其中局部最小值(四个邻居)所在的位置。
Try this for 2D:
This will return you an array2d-like array with True/False where local minima (four neighbors) are located.