我目前正在制作一個自定義函式,我最終會將其輸入 scipy.optimize.curve_fit() 以進行自定義曲線擬合。我的曲線合身將像一個凹凸。高斯上升和指數下降,拼湊在高斯的最高點。我已經定義了一個高斯函式和一個指數函式,目前正在嘗試定義一個 combo() 函式。這是我到目前為止所擁有的:
def exp(x, a, b, c):
return a * np.exp((-b * x) c)
def gauss(x,d,e,f):
return d * np.exp(-((x-e)**2)/(2*(f**2)))
def combo(x,a,b,c,d,e,f):
ex = exp(x,a,b,c)
ga = gauss(x,d,e,f)
num = np.arange(0,1000,1)
test =combo(num,1,2,3,10,4,3)
我嘗試在我的組合函式中使用 if 陳述句(如果 x<d: return ga),但我收到錯誤訊息:“具有多個元素的陣列的真值不明確。使用 a.any() 或a.all()”。也許這是解決方案,但我不確定如何使用它。
uj5u.com熱心網友回復:
def combo(x,a,b,c,d,e,f, dtype=np.float64):
def gauss(x,d,e,f):
return d * np.exp(-((x-e)**2)/(2*(f**2)))
def exp(x, a, b, c):
return a * np.exp((-b * x) c)
result = np.piecewise(
x,
[x <= e,x > e],
[lambda x: gauss(x,d,e,f), lambda x: exp(x,a,b,c)],
)
return result
uj5u.com熱心網友回復:
我認為最好的方法numpy是使用陣列切片。首先,將test陣列創建為高斯陣列,然后找到它達到最大值的索引,然后用指數函式計算的值替換從該點開始的陣列:
def exp(x, a, b, c):
return a * np.exp(-c * (x-b))
def gauss(x, a, b, d):
return a * np.exp(-((x-b)**2)/(2*(d**2)))
def combo(x, a, b, c, d):
y = gauss(x, a, b, d)
g_max_ind = y.argmax()
y[g_max_ind 1:] = exp(x[g_max_ind 1:], a, b, c)
return y
num = np.arange(-50, 50, 0.5)
test = combo(num, 10, 4, 3, 3)
我假設您希望此函式是連續的,因此我更改了您的引數,以便輸入的值exp彼此gauss一致,并且我更改了arange引數,因此繪圖更有意義。如果我誤解了,請告訴我,我可以糾正。
輸出:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/421370.html
標籤:
下一篇:在R中解釋函式內部的函式
