Python,scipy - 如何使用分段函数拟合曲线,条件参数也需要计算?

问题描述 投票:0回答:1

正如标题所示,我试图将一个分段方程拟合到一个大数据集中。我希望适合我的数据的公式如下:

当x <c时,y(x)= b

其他:

y(x)= b + exp(a(x-c)) - 1,当x> = c时

如何解决这样的问题有多个答案,但作为一个Python初学者,我无法弄清楚如何将它们应用到我的问题:Curve fit with a piecewise function? Conditional curve fit with scipy?

问题是必须通过拟合算法计算所有变量(a,b和c)。

谢谢您的帮助!

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

# Reduced Dataset
y = np.array([23.032, 21.765, 20.525, 21.856, 21.592, 20.754, 20.345, 20.534,
       23.502, 21.725, 20.126, 21.381, 20.217, 21.553, 21.176, 20.976,
       20.723, 20.401, 22.898, 22.02 , 21.09 , 22.543, 22.584, 22.799,
       20.623, 20.529, 20.921, 22.505, 22.793, 20.845, 20.584, 22.026,
       20.621, 23.316, 22.748, 20.253, 21.218, 23.422, 23.79 , 21.371,
       24.318, 22.484, 24.775, 23.773, 25.623, 23.204, 25.729, 26.861,
       27.268, 27.436, 29.471, 31.836, 34.034, 34.057, 35.674, 41.512,
       48.249])

x = np.array([3756., 3759., 3762., 3765., 3768., 3771., 3774., 3777., 3780.,
       3783., 3786., 3789., 3792., 3795., 3798., 3801., 3804., 3807.,
       3810., 3813., 3816., 3819., 3822., 3825., 3828., 3831., 3834.,
       3837., 3840., 3843., 3846., 3849., 3852., 3855., 3858., 3861.,
       3864., 3867., 3870., 3873., 3876., 3879., 3882., 3885., 3888.,
       3891., 3894., 3897., 3900., 3903., 3906., 3909., 3912., 3915.,
       3918., 3921., 3924.])

# Simple exponential function without conditions (works so far)
def exponential_fit(x,a,b,c):
    return b + np.exp(a*(x-c)) 

popt, pcov = curve_fit(exponential_fit, x, y, p0 = [0.1, 20,3800])

plt.plot(x, y, 'bo')
plt.plot(x, exponential_fit(x, *popt), 'r-')
plt.show()
python-3.x scipy condition
1个回答
0
投票

将您的功能更改为:

def exponential_fit(x, a, b, c):
    if x >= c:
        return b + np.exp(a*(x-c))-1
    else:
        return b

给我:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.