栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

可以使用Ivan的detect_peaks函数对任意维度的数组找到局部极小值的位置,并进行少量修改:

import numpy as npimport scipy.ndimage.filters as filtersimport scipy.ndimage.morphology as morphologydef detect_local_minima(arr):    # https://stackoverflow.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]


转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/640066.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号