简体   繁体   English

Python中的分段指数拟合

[英]Piecewise Exponential fit in Python

I am trying to make a piecewise fitting as shown in fig.1: 我正在尝试进行如图1所示的分段拟合:

在此处输入图片说明

Here is the code: 这是代码:

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

def piecewise_linear(x, x0, y0, k1, k2):
    return np.piecewise(x, [x < x0], [lambda x: k1*np.power(x,k2), lambda x: y0])

x=np.arange(0.0,100.0,1.0)
y=piecewise_linear( x, 45.0, 2025.0, 1.0, 2.0)

popt , pcov = optimize.curve_fit(piecewise_linear, x, y)
tau = np.linspace(x[0], x[-1], 200)
perr = np.sqrt(np.diag(pcov))
print popt
print perr
print pcov
plt.plot(x, y, 'b+')
plt.plot(tau, piecewise_linear(tau, *popt),'r')
plt.loglog()
plt.show()
plt.close()

But this gave me fitting as fig. 但是,这给了我无花果的身影。 2: 2: 在此处输入图片说明

The parameter x0 was fixed at 1, no matter how I changed the data set. 无论我如何更改数据集,参数x0都固定为1。

I don't know what's wrong with my code, and how can I correct this? 我不知道我的代码有什么问题,如何解决这个问题?

Within your optimize.curve_fit() you need to specify some initial guess for the fitting using p0 = [] where you input your initial guesses into p0 , the documentation of which can be found here . 在您的optimize.curve_fit()您需要使用p0 = []为拟合指定一些初始猜测,在此您将初始猜测输入到p0 ,有关其文档可在此处找到。

In terms of the example you have given, you already have the values of x0, y0, k1, k2 as you used them to calculate y , therefore just input these into your curve_fit : 根据给出的示例,您已经具有x0, y0, k1, k2的值x0, y0, k1, k2因为它们用于计算y ,因此只需将其输入到curve_fit

def piecewise_linear(x, x0, y0, k1, k2):
    return np.piecewise(x, [x < x0], [lambda x: k1*np.power(x,k2), lambda x: y0])

x=np.arange(0.0,100.0,1.0)
y=piecewise_linear( x, 45.0, 2025.0, 1.0, 2.0)

#insert the initial guesses into curve_fit below using p0 = [...]
popt , pcov = optimize.curve_fit(piecewise_linear, x, y, p0=[45, 2000, 1, 2])
tau = np.linspace(x[0], x[-1], 200)
perr = np.sqrt(np.diag(pcov))

print (popt)
print (perr)
print (pcov)

plt.plot(x, y, 'b+')
plt.plot(tau, piecewise_linear(tau, *popt),'r')
plt.loglog()
plt.show()

This give the following graph: 这给出了下图:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM