python 分段函数拟合,如何在Python中应用分段线性拟合?

I am trying to fit piecewise linear fit as shown in fig.1 for a data set

fd264967392a9b54a5c1bbda3f10b3ba.png

This figure was obtained by setting on the lines. I attempted to apply a piecewise linear fit using the code:

from scipy import optimize

import matplotlib.pyplot as plt

import numpy as np

x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ,11, 12, 13, 14, 15])

y = np.array([5, 7, 9, 11, 13, 15, 28.92, 42.81, 56.7, 70.59, 84.47, 98.36, 112.25, 126.14, 140.03])

def linear_fit(x, a, b):

return a * x + b

fit_a, fit_b = optimize.curve_fit(linear_fit, x[0:5], y[0:5])[0]

y_fit = fit_a * x[0:7] + fit_b

fit_a, fit_b = optimize.curve_fit(linear_fit, x[6:14], y[6:14])[0]

y_fit = np.append(y_fit, fit_a * x[6:14] + fit_b)

figure = plt.figure(figsize=(5.15, 5.15))

figure.clf()

plot = plt.subplot(111)

ax1 = plt.gca()

plot.plot(x, y, linestyle = '', linewidth = 0.25, markeredgecolor='none', marker = 'o', label = r'\textit{y_a}')

plot.plot(x, y_fit, linestyle = ':', linewidth = 0.25, markeredgecolor='none', marker = '', label = r'\textit{y_b}')

plot.set_ylabel('Y', labelpad = 6)

plot.set_xlabel('X', labelpad = 6)

figure.savefig('test.pdf', box_inches='tight')

plt.close()

But this gave me fitting of the form in fig. 2, I tried playing with the values but no change I can't get the fit of the upper line proper. The most important requirement for me is how can I get Python to get the gradient change point. In essence I want Python to recognize and fit two linear fits in the appropriate range. How can this be done in Python?

117a2c8a6cc2c559c28fbdae3a48c8b8.png

解决方案

You can use numpy.piecewise() to create the piecewise function and then use curve_fit(), Here is the code

from scipy import optimize

import matplotlib.pyplot as plt

import numpy as np

%matplotlib inline

x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ,11, 12, 13, 14, 15], dtype=float)

y = np.array([5, 7, 9, 11, 13, 15, 28.92, 42.81, 56.7, 70.59, 84.47, 98.36, 112.25, 126.14, 140.03])

def piecewise_linear(x, x0, y0, k1, k2):

return np.piecewise(x, [x < x0], [lambda x:k1*x + y0-k1*x0, lambda x:k2*x + y0-k2*x0])

p , e = optimize.curve_fit(piecewise_linear, x, y)

xd = np.linspace(0, 15, 100)

plt.plot(x, y, "o")

plt.plot(xd, piecewise_linear(xd, *p))

the output:

06e8a403a871ad98b60e86cbbc40895c.png

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值