2016-08-05 42 views
0

我知道這個問題屬於峯值檢測和there are answers available的範疇,但我認爲我的問題很簡單,並且涉及到原理的證明。Python:2D numpy數組中峯的正確位置?

說我生成浮點值這樣的,其指的nxn點(離散域)規則網格的倍數,nxn 2D numpy的數組:

myarray= 
array([[ 0.82760819, 0.82113999, 0.811576 , 0.80308705, 0.81231903, 
     0.82296263, 0.78448964, 0.79308308, 0.82160627, 0.83475755, 
     0.8580934 , 0.8857617 , 0.89901092, 0.92479025, 0.91840606, 
     0.91029942, 0.88523943, 0.85798491, 0.84190422, 0.83350783, 
     0.83520675], 
     [ 0.84971526, 0.84759644, 0.81429419, 0.79936736, 0.81750327, 
     0.81874686, 0.80666801, 0.82297348, 0.84980788, 0.85698662, 
     0.87819988, 0.89572185, 0.89009723, 0.90347858, 0.89703473, 
     0.90092666, 0.88362073, 0.86711197, 0.84791422, 0.83632138, 
     0.83685225], ...] #you can generate any nxn array of random values 

現在讓我們正常化它們:

peak_value=myarray.max() 
norm_array=myarray/peak_value 

並繼續找到峯的座標:

from collections import Counter 
longit=[] #x values of the peak 
latit=[] #y values of the peak 
for x in range(myarray.shape[0]): 
    for y in range(myarray.shape[1]): 
     if norm_array[x][y]==1: 
     longit.append(x) 
     latit.append(y) 

x=numpy.array(longit) 
y=numpy.array(latit) 

c=zip(x,y) 
temp=Counter(elem for elem in c) #Counts the number of peaks in each (x,y) point in the 11x11 grid 
d=dict(Counter(temp)) #Has the shape d={(x,y): number of peaks} 

現在,這只是2D numpy陣列的單個實現。給定多個陣列,問題是:

這是找到峯(x,y)的正確方法嗎?有沒有更高效的方法?請考慮可能存在多個峯值。

回答

2

在C/C++中,使用浮點數執行==被認爲是危險的。使用numpy.wherej指數

a = random.rand(13, 11) 
idx_unrolled = argmax(a) 
the_peak = a[idx_unrolled/11, idx_unrolled%11] 

如果你需要的所有長槍,你可以得到的i名單:

如果沒有多個完全相同長槍,你可以使用numpy.argmax

i, j = where(a > 0.99*the_peak) 

使用所需號碼9調整保證金。對於單精度浮點,它不會接近1

,最好的辦法可能是這樣的[https://stackoverflow.com/a/19141711/774971]:

i, j = where(a > (1.0 - 5*np.finfo(a.dtype).eps)*the_peak) 
+0

好了,我不知道。可能有多個峯值。在這種情況下你有什麼建議? – FaCoffee

+0

此外,我的問題不是關於我的最大值,因爲我規範化數組。它是關於網格中的座標。所以你的最後一行,我不需要它,因爲我的最大值總是1.0。 – FaCoffee

+2

我在新版本中做過多個峯值。我關於'max'的觀點是,你可能會得到'0.99999999999'而不是'1.00000000000',你會完全錯過你的高峯。它發生在浮點算術中,特別是當你進行繁重的數學或建模[http://floating-point-gui.de/errors/comparison]時。 –