【问题标题】:scipy optimize.curve_fit cannot fit a function whose return value depends on a conditionalscipy optimize.curve_fit 无法拟合返回值取决于条件的函数
【发布时间】:2012-10-30 03:56:13
【问题描述】:

我想将定义如下的函数拟合到时间序列数据:

def func(t, a0, a1, a2, T, tau1, tau2):
    if t < T:
        return a0 + a1 * np.exp(-t/tau1) + a2 * np.exp(-t/tau2)
    else:
        return a0 + a1 * np.exp(-T/tau1) * (1 - t/tau1 + T/tau1) + a2 * np.exp(-T/tau2) * (1 - t/tau2 + T/tau2) 

这里,t 表示进行测量的时间,其余参数是函数的参数。问题是当我将它输入curve_fit 时,Python 抱怨t

popt, pcov = curve_fit(func, t1, d1)

其中 t1 是时间列表,d1 是在相应时间测量的数据值列表。我尝试了多种方法来解决这个问题,但无济于事。有什么建议吗?非常感谢!

【问题讨论】:

    标签: python python-2.7 scipy


    【解决方案1】:

    没错,t &lt; T 是一个布尔数组。 NumPy 拒绝为布尔数组分配真值,因为有很多可能的选择——如果 所有 元素为真,或者如果 任何 元素为真,它应该为真吗?

    不过没关系。在这种情况下,NumPy 提供了一个很好的函数来替换if ... else ... 块,即np.where

    def func(t, a0, a1, a2, T, tau1, tau2):
        return np.where(
            t < T,
            a0 + a1 * np.exp(-t/tau1) + a2 * np.exp(-t/tau2),
            a0 + a1 * np.exp(-T/tau1) * (1 - t/tau1 + T/tau1) + a2 * np.exp(-T/tau2) * (1 - t/tau2 + T/tau2) )
    

    【讨论】:

      猜你喜欢
      • 2022-11-23
      • 1970-01-01
      • 2016-06-05
      • 2018-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多