2014-01-23 15 views
0

更具體地說,我需要找到函數的第二高的最大值。可以說,當我繪製函數時我得到(1,10)的最大值,但我真正想要的是在(4,9)處找到的最大值。現在我正在使用max(函數)來查找最大值。如何找到函數中的相對最大值?

我的問題:

  • 我使用了正確的功能?

  • 我是否使用邊界?如果是這樣,怎麼樣?

在此先感謝您提供的任何幫助!

+1

爲什麼沒有得到關於迭代生成的'max'與(1,10)一創-COMP過濾器? – inspectorG4dget

+4

您是否在尋找二維數組中的第二最大值?你能提供簡單的樣本輸入和期望的輸出嗎? – Akavall

+0

請提供更多詳情!它是一個具有兩個(或更多)局部最大值的可微函數嗎?在這種情況下,只需求解f'(x)= 0並選擇該x中的第二大arg max。如果您需要數值解決方案,請在此處搜索文檔中的數值優化可能性:http://docs.scipy.org/doc/scipy/reference/optimize.html – cd98

回答

1

我numpy的> 1.8,您可以使用np.partition得到一個數組的第k大元素:您可以使用scipy.ndimage.maximum_filter()

>>> a = np.arange(11) 
>>> np.random.shuffle(a) 
>>> a 
array([10, 8, 0, 3, 2, 9, 4, 1, 7, 5, 6]) 
>>> np.partition(a, -2) # second to last element is in the right position 
array([ 5, 6, 0, 3, 2, 8, 4, 1, 7, 9, 10]) 
>>> np.partition(a, -2)[-2] 
9 
+0

[-2 ]是指在np.partition(a,-2)[ - 2]之後? – user3229883

+0

說我的模塊對象沒有屬性'分區' – user3229883

+0

'np.partition'只能在numpy> = 1.8中使用,請檢查你正在使用的'np .__ version__'。 '-2'的意思是「從結尾開始秒」。 – Jaime

1

找到當地最大:

import numpy as np 
from scipy import ndimage 

Y, X = np.mgrid[-3:3:50j, -3:3:50j] 

Z = 3 * (1 - X)**2 * np.exp(- X**2 - (Y + 1)**2) \ 
    - 10 * (X/5 - X**3 - Y**5) * np.exp(-X**2 - Y**2) \ 
    - 1.0/3 * np.exp(-(X + 1)**2 - Y**2) 

iy, ix = np.where(ndimage.maximum_filter(Z, size=(5, 5), mode="constant") == Z) 

y, x, z = Y[iy, 0], X[0, ix], Z[iy, ix] 

from matplotlib import pyplot as plt 
fig, ax = plt.subplots() 

ax.pcolormesh(X, Y, Z, cmap="gray") 
ax.scatter(x, y, c=z, marker="x"); 

找到第二高峯,只需numpy.argsort(z),並獲得倒數第二個指數。

輸出:

enter image description here

+0

我不能使用scipy :( – user3229883

相關問題