Python 求解适合当前代码的非线性曲线

Python 求解适合当前代码的非线性曲线,python,matplotlib,curve-fitting,nonlinear-optimization,Python,Matplotlib,Curve Fitting,Nonlinear Optimization,我意识到可能需要添加很多内容,但如果有人能为我指出一条适用于指数图的最佳拟合线的正确方向,我将不胜感激。 以下是我到目前为止的情况: import matplotlib.pyplot as plt x = [] y = [] readFile = open ('TEXT.txt', 'r') sepFile = readFile.read().split('\n') readFile.close() for plotPair in sepFile: xAndY = plotPair

我意识到可能需要添加很多内容,但如果有人能为我指出一条适用于指数图的最佳拟合线的正确方向,我将不胜感激。 以下是我到目前为止的情况:

import matplotlib.pyplot as plt

x = []
y = []

readFile = open ('TEXT.txt', 'r')
sepFile = readFile.read().split('\n')
readFile.close()

for plotPair in sepFile:
    xAndY = plotPair.split('\t')
    x.append(int (xAndY[0]))
    y.append(float (xAndY[1]))
print x
print y

plt.plot (x, y, 'o' )
plt.xlabel('')
plt.ylabel('')
plt.show()

一般来说,真正拟合非线性曲线是一个非常困难的问题(主要是因为解空间是无限的和非连续的),但一般来说,scipy是您要寻找此类问题的解决方案的地方。如果您知道方程的一般形式,可以对其应用变换,并使用多边形拟合算法(仍然是无限的,但连续的)尝试拟合它。请看这里:

当然,对于指数曲线,通过取数据的对数,可以非常简单地使用它

如果你真的想优化一些任意的最小二乘拟合,你必须停止曲线拟合,开始考虑多变量优化。同样,scipy是您应该寻找解决方案的地方,但请在此处查看优化库:


使用一系列三角函数为曲线拟合提供了一种非常稳健的方法。下面的示例使用一系列的
正弦
余弦

from scipy import sin, cos, linspace
def f(x, a0,s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12,
            c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12):
    return a0 + s1*sin(1*x) +  c1*cos(1*x) \
              + s2*sin(2*x) +  c2*cos(2*x) \
              + s3*sin(3*x) +  c3*cos(3*x) \
              + s4*sin(4*x) +  c4*cos(4*x) \
              + s5*sin(5*x) +  c5*cos(5*x) \
              + s6*sin(6*x) +  c6*cos(6*x) \
              + s7*sin(7*x) +  c7*cos(7*x) \
              + s8*sin(8*x) +  c8*cos(8*x) \
              + s9*sin(9*x) +  c9*cos(9*x) \
             + s10*sin(9*x) + c10*cos(9*x) \
             + s11*sin(9*x) + c11*cos(9*x) \
             + s12*sin(9*x) + c12*cos(9*x)

from scipy.optimize import curve_fit
popt, pcov = curve_fit(f, x, y)
x_fit = linspace(x.min(), x.max(), 1000)
y_fit = f(x_fit, *popt)

我希望它对你有用

为了将数学(如指数)曲线拟合到数据中,我将使用
scipy.stats.expon.fit
。语法与任何其他标准分布相同。如前所述,使用对数并对直线进行拟合可能是最好的;否则,我将使用上述
优化
包中的
曲线拟合
例程,它似乎最适合您的问题。