限制Python中的指数回归

时间:2019-01-18 11:55:39

标签: python matplotlib

我已经根据实验中的一些数据成功创建了指数回归。但是,我希望当y值开始趋于平稳(约x = 42000秒)时停止回归。请参见附件中的图片。

这是到目前为止的代码:

import matplotlib.pyplot as plt;
import numpy as np;
import pandas as pd
import scipy.optimize as opt;

# This is the function we are trying to fit to the data.
def func(x, a, b, c):
     return a * b**x

dataC = pd.read_csv("yeastdata1cropped.txt")
data = pd.read_csv("yeastdata1.txt")

xdata = np.array(data.iloc[:,1])
ydata = np.array(data.iloc[:,0])

xdatac = np.array(dataC.iloc[:,1])
ydatac = np.array(dataC.iloc[:,0])

# Plot the actual data
plt.plot(xdata, ydata, ".", label="Data");

# The actual curve fitting happens here
optimizedParameters, pcov = opt.curve_fit(func, xdatac, ydatac);

# Use the optimized parameters to plot the best fit
plt.plot(xdata, func(xdata, *optimizedParameters), label="fit");

# Show the graph
plt.legend();
plt.show();

enter image description here

1 个答案:

答案 0 :(得分:0)

您只需要将相关/感兴趣的值传递给拟合值,如下所示。您可以使用NumPy索引仅传递小于42000的x值。使用[xdatac<42000]将返回此条件保持True的索引/位置。其余代码保持不变。

optimizedParameters, pcov = opt.curve_fit(func, xdatac[xdatac<42000],
                                          ydatac[xdatac<42000]);

这样,拟合将最多执行42000次,您仍然可以稍后通过传递完整的x数据来绘制拟合线。