2013-06-05 50 views
1

我試圖擬合一些數據,該數據在時間= 0時開始出現平坦,尖銳的峯值,然後作爲兩個負指數衰減(首先是快速的指數,然後是少量的時間作爲較慢的時間)。我一直在嘗試使用scipy.optimize中的curve_fit,但擬合似乎沒有認識到第一個快速衰減的指數。將SciPy curve_fit用於具有多種功能形式的數據

我所做的是爲不同的時間範圍定義兩個適合的函數。對於時間< 0我有一個常數(我稱爲線,因爲一開始我正在使用一條線)。對於時間> 0,我定義了具有不同參數的兩個指數的和。然後我對這些參數進行猜測,並將所有內容輸入到curve_fit中。

我真的只是想知道如果任何人有關於如何得到它認識到第一峯和快速衰減的任何想法...

在我的谷歌搜索,我只能找裝修簡單的數據實例(如單指數或多項式)。我可能會接近完全錯誤,任何幫助將不勝感激。謝謝!

另外,我會附上情節是我所得到,但是這是我的第一篇文章,我有沒有信譽,所以它不會讓我...

這裏是一個數據鏈接: http://www.lehigh.edu/~ivb2/teaching/smp/current/DecayData.txt

下面是代碼:

#!/usr/bin/env python 

import numpy as np 
from scipy import optimize 
from scipy.optimize import curve_fit 
import matplotlib.pyplot as plt 

def line(x, *p): 
    return p[0] 

def exponential(x, *p): 
    return p[0] * np.exp(p[1] * x) + p[2] 

#Fit function (neg exp in this case) 
def fitfunc(time, *p): 
    tempArray = np.empty_like(time) 
    tempArray[time <= 0] = line(time, p[6]) 
    tempArray[0 < time] = exponential(time, p[0], p[1], p[2]) + exponential(time, p[3], p[4], p[5]) 
    return tempArray 

#Read in the data to 3 arrays 
time, decay1, decay2 = np.loadtxt('DecayData.txt', unpack=True) 

#An initial guess for the fit parameters 
guess = np.array([5e-2, -2500, 0, 5e-2, -2000, 0, 0]) 

#Fits the functions using curve_fit 
popt, pcov = curve_fit(fitfunc, time, decay1, guess) 

print popt 

fig = plt.figure() 
ax = fig.add_subplot(111) 
ax.plot(time, decay1) 
ax.plot(time, fitfunc(time, *popt)) 
plt.show() 

回答

0

我看到兩個問題:

  • fitfunc你寫

    tempArray[time <= 0] = line(time, p[6]) 
    tempArray[0 < time] = exponential(time, p[0], p[1], p[2]) + exponential(time, p[3], p[4], p[5]) 
    

但數組的大小是不是在平等的雙方是相同的。我認爲在第二線時代是不好的;我已經與

tempArray[time <= 0] = line(time[time<=0], p[6]) 
    tempArray[0 < time] = exponential(time[0<time], p[0], p[1], p[2]) + exponential(time[0<time], p[3], p[4], p[5]) 
  • 您最初的猜測代替它p[1]如果很假,我已經-250000

有了這兩個變化更換-2500,它工作正常,我的電腦上。

JPG