[英]Smooth Data and Find Maximum
我有兩個變量x和y的數據集(請參見下文)。 我想找到x的哪個值,y出現最大值? 我當前的方法是簡單地查找x,這使我獲得了最大的y。 這不是理想的選擇,因為我的數據非常嘈雜,因此我想先進行某種平滑處理,然后再找到最大值。
到目前為止,我已經嘗試使用R通過np
包中的npreg
(內核回歸)對數據進行平滑處理,以獲取此曲線:
但我不確定如何找到最大值。
我想用Python解決以下問題:
1)平滑數據(不必是內核回歸)
2)使用平滑數據找到x的值,其中y中的最大值出現
x y
-20 0.006561733
-19 -4.48E-08
-18 -4.48E-08
-17 -4.48E-08
-16 0.003281305
-15 0.00164063
-14 0.003280565
-13 0.003282537
-12 -4.48E-08
-11 0.003281286
-10 0.004921239
-9 0.00491897
-8 -1.52E-06
-7 0.004925867
-6 -1.27E-06
-5 0.009839438
-4 0.001643726
-3 -4.48E-08
-2 2.09E-06
-1 -0.001640027
0 0.006559627
1 0.001636958
2 2.36E-06
3 0.003281469
4 0.011481469
5 0.004922279
6 0.018044207
7 0.011483134
8 0.014765087
9 0.008201379
10 0.00492497
11 0.006560482
12 0.009844796
13 0.011483199
14 0.008202129
15 0.001641621
16 0.004921645
17 0.006563377
18 0.006561068
19 0.008201004
我會對數據運行高斯過濾器以使其平滑:
# first, make a function to linearly interpolate the data
f = scipy.interpolate.interp1d(x,y)
# resample with 1000 samples
xx = np.linspace(-20,19, 1000)
# compute the function on this finer interval
yy = f(xx)
# make a gaussian window
window = scipy.signal.gaussian(200, 60)
# convolve the arrays
smoothed = scipy.signal.convolve(yy, window/window.sum(), mode='same')
# get the maximum
xx[np.argmax(smoothed)]
這是平滑的結果:
最大值出現在6.93。
scipy.signal
還有很多其他窗口函數和過濾選項。 有關更多信息,請參見文檔 。
您可能可以使用平滑樣條函數:
import numpy as np
from scipy import interpolate
x = range(-20,20)
y = [0.006561733, -4.48e-08, -4.48e-08, -4.48e-08, 0.003281305, 0.00164063, 0.003280565, 0.003282537, -4.48e-08, 0.003281286, 0.004921239, 0.00491897, -1.52e-06, 0.004925867, -1.27e-06, 0.009839438, 0.001643726, -4.48e-08, 2.09e-06, -0.001640027, 0.006559627, 0.001636958, 2.36e-06, 0.003281469, 0.011481469, 0.004922279, 0.018044207, 0.011483134, 0.014765087, 0.008201379, 0.00492497, 0.006560482, 0.009844796, 0.011483199, 0.008202129, 0.001641621, 0.004921645, 0.006563377, 0.006561068, 0.008201004]
tck = interpolate.splrep(x,y) # pass in s= some value to change smoothing:
# higher = smoother, s=0 for no smoothing
xnew = np.arange(-20, 20, 0.1)
ynew = interpolate.splev(xnew,tck,der=0)
現在xnew
和ynew
包含擬合的精巧版本,您可以通過
max_index = np.argmax(ynew)
max_value = ynew[max_index]
max_x = xnew[max_index]
抱歉,我無法對此進行測試; 我現在正在使用的計算機沒有scipy等。雖然應該給您一些想法。
參考: http : //docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html
我不確定要解決的主要問題是什么? 更好的平滑,查找最小值還是在Python中完成所有操作? 如果您在R方面取得了可喜的進展,為什么要改用Python? 我發現在R中內置的supsmu
函數通常可以很好地完成非參數平滑。 這就是我在R中的做法。
smooth <- do.call(supsmu, data)
min.idx <- which.min(smooth$y)
min.point <- c(smooth$x[min.idx], smooth$y[min.idx])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.