如何有效地找到 NumPy 中平滑多维数组的局部最小值?

Posted

技术标签:

【中文标题】如何有效地找到 NumPy 中平滑多维数组的局部最小值?【英文标题】:How to find the local minima of a smooth multidimensional array in NumPy efficiently? 【发布时间】:2011-04-28 12:46:07 【问题描述】:

假设我在 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() 吗?

【问题讨论】:

寻找全局最大值:***.com/questions/3584243/… 【参考方案1】:

可以为任意维度的数组找到局部最小值的位置 使用Ivan的detect_peaks function,稍作修改:

import numpy as np
import scipy.ndimage.filters as filters
import scipy.ndimage.morphology as morphology

def detect_local_minima(arr):
    # https://***.com/questions/3684484/peak-detection-in-a-2d-array/3689710#3689710
    """
    Takes an array and detects the troughs using the local maximum filter.
    Returns a boolean mask of the troughs (i.e. 1 when
    the pixel's value is the neighborhood maximum, 0 otherwise)
    """
    # define an connected neighborhood
    # http://www.scipy.org/doc/api_docs/SciPy.ndimage.morphology.html#generate_binary_structure
    neighborhood = morphology.generate_binary_structure(len(arr.shape),2)
    # apply the local minimum filter; all locations of minimum value 
    # in their neighborhood are set to 1
    # http://www.scipy.org/doc/api_docs/SciPy.ndimage.filters.html#minimum_filter
    local_min = (filters.minimum_filter(arr, footprint=neighborhood)==arr)
    # local_min is a mask that contains the peaks we are 
    # looking for, but also the background.
    # In order to isolate the peaks we must remove the background from the mask.
    # 
    # we create the mask of the background
    background = (arr==0)
    # 
    # a little technicality: we must erode the background in order to 
    # successfully subtract it from local_min, otherwise a line will 
    # appear along the background border (artifact of the local minimum filter)
    # http://www.scipy.org/doc/api_docs/SciPy.ndimage.morphology.html#binary_erosion
    eroded_background = morphology.binary_erosion(
        background, structure=neighborhood, border_value=1)
    # 
    # we obtain the final mask, containing only peaks, 
    # by removing the background from the local_min mask
    detected_minima = local_min ^ eroded_background
    return np.where(detected_minima)       

你可以这样使用:

arr=np.array([[[0,0,0,-1],[0,0,0,0],[0,0,0,0],[0,0,0,0],[-1,0,0,0]],
              [[0,0,0,0],[0,-1,0,0],[0,0,0,0],[0,0,0,-1],[0,0,0,0]]])
local_minima_locations = detect_local_minima(arr)
print(arr)
# [[[ 0  0  0 -1]
#   [ 0  0  0  0]
#   [ 0  0  0  0]
#   [ 0  0  0  0]
#   [-1  0  0  0]]

#  [[ 0  0  0  0]
#   [ 0 -1  0  0]
#   [ 0  0  0  0]
#   [ 0  0  0 -1]
#   [ 0  0  0  0]]]

这表示最小值出现在索引 [0,0,3]、[0,4,0]、[1,1,1] 和 [1,3,3] 处:

print(local_minima_locations)
# (array([0, 0, 1, 1]), array([0, 4, 1, 3]), array([3, 0, 1, 3]))
print(arr[local_minima_locations])
# [-1 -1 -1 -1]

【讨论】:

不错!它的运行速度大约是我原来的 65 倍,并且适用于任意数量的维度。 对于新版本的 numpy.它将出现此错误:numpy boolean subtract, the - operator, is deprecated, use the bitwise_xor, the ^ operator, or the logical_xor function instead.。也许将detected_minima = local_min - eroded_background 更改为bitwise_xor^logical_xor 【参考方案2】:

试试这个 2D:

import numpy as N

def local_minima(array2d):
    return ((array2d <= N.roll(array2d,  1, 0)) &
            (array2d <= N.roll(array2d, -1, 0)) &
            (array2d <= N.roll(array2d,  1, 1)) &
            (array2d <= N.roll(array2d, -1, 1)))

这将为您返回一个类似 array2d 的数组,其中包含局部最小值(四个邻居)所在的 True/False。

【讨论】:

嗯,这实际上找到了局部最大值,并且需要&amp;而不是&amp;&amp;,并且需要在比较周围加上括号,但它的运行速度比我原来的***十倍。跨度> 这里发生了什么? @johnktejik 将数组中的元素与上方、下方、左侧和右侧的元素进行比较。如果它比全部小,它会将元素替换为“True”,让您知道那里有一个局部最小值。 这取决于您对局部最小值的定义。如果您在“山谷”中,但“山谷”在最小值处有一个高原,则整个高原将被忽略。不会记录该山谷的当地最小值

以上是关于如何有效地找到 NumPy 中平滑多维数组的局部最小值?的主要内容,如果未能解决你的问题,请参考以下文章

如何有效地操作一个大的numpy数组

如何在python中平滑曲线

如何在opengl中平滑多个四边形的纹理

如何在 STL 加载的 BufferGeometry 中平滑网格三角形

在 Android 中平滑滚动画布

在多维数组上使用 numpy.argmax()