簡體   English   中英

兩個預定義函數的組合(分段)function

[英]Combination (piecewise) function of two pre-defined functions

我目前正在制作一個自定義 function ,我最終將輸入 scipy.optimize.curve_fit() 以進行自定義曲線擬合。 我的曲線合身將像一個凹凸。 高斯上升和指數下降,拼湊在高斯的最高點。 我已經定義了一個高斯和一個指數 function,目前正在嘗試定義一個組合() function。 這是我到目前為止所擁有的:

    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)

我嘗試在組合 function 中使用 if 語句(如果 x<d: return ga),但我收到錯誤消息:“具有多個元素的數組的真值不明確。使用 a.any() 或a.all()”。 也許這是解決方案,但我不確定如何使用它。

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

我認為使用numpy執行此操作的最佳方法是使用數組切片。 首先,將test數組創建為高斯數組,然后找到它達到最大值的索引,然后用指數 function 計算的值替換從該點開始的數組:

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)

我假設你希望這個 function 是連續的,所以我改變了你的參數,使輸入到expgauss的值彼此一致,我改變了arange參數,所以 plot 更有意義。 如果我誤解了,請告訴我,我可以糾正。

Output:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM