【问题标题】:Using SciPy curve_fit for data with multiple functional forms使用 SciPy curve_fit 处理具有多种功能形式的数据
【发布时间】:2013-06-01 08:05:02
【问题描述】:

我正在尝试拟合一些数据,这些数据一开始是平坦的,在时间 = 0 时急剧达到峰值,然后衰减为两个负指数(首先是快速指数,然后在一小段时间后作为较慢指数) .我一直在尝试使用 scipy.optimize 中的曲线拟合,但拟合似乎无法识别第一个快速衰减的指数。

我所做的只是为不同的时间范围定义两个拟合函数。对于 time 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()

【问题讨论】:

    标签: scipy curve-fitting


    【解决方案1】:

    我看到两个问题:

    • 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] 的初步猜测如果非常错误,我已将-2500 替换为-250000

    通过这两项更改,它在我的计算机上运行良好。

    JPG

    【讨论】:

      猜你喜欢
      • 2017-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-29
      • 1970-01-01
      • 1970-01-01
      • 2021-03-28
      相关资源
      最近更新 更多