scipy optimize.curve_fit 无法拟合返回值取决于条件的函数 [英] scipy optimize.curve_fit cannot fit a function whose return value depends on a conditional

查看:80
本文介绍了scipy optimize.curve_fit 无法拟合返回值取决于条件的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to fit a function, defined as follows, to a time series data:

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 < 中的歧义.比较.我相信这是因为在curve_fit内部调用func时t变成了数据点列表,而T是一个数字(不是列表):

Here, t represents the time at which a measurement is made, and the rest of the arguments are the parameters of the function. The problem is that when I feed it into curve_fit, Python complains about the ambiguity in the t < T comparison. I believe this happens because t becomes a list of data points when func is called inside curve_fit, whereas T is a number (not a list):

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

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

where t1 is a list of times and d1 is a list of the data values measured at the corresponding times. I have attempted a number of ways to get around this problem, but to no avail. Any suggestion? Thanks a lot!

推荐答案

没错,t <T 是一个布尔数组.NumPy 拒绝为布尔数组分配真值,因为有很多可能的选择——如果 all 元素为 True,它应该是 True,还是 any 元素为 True?

That's right, t < T is a boolean array. NumPy refuses to assign a truth value to boolean arrays because there are many possible choices -- should it be True if all elements are True, or if any element is True?

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

But that's okay. In this case, NumPy provides a nice function to replace the if ... else ... blocks, namely, 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) )

这篇关于scipy optimize.curve_fit 无法拟合返回值取决于条件的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆