1

I realize that a lot probably has to be added but if someone could point me in the right direction for applying a line of best fit for the exponential graph that would be much appreciated. Here is what I have so far:

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()
4

2 回答 2

2

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

http://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html

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

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

http://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html

于 2013-07-02T14:46:36.153 回答
0

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

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)

我希望这个对你有用!

于 2013-07-07T19:48:10.563 回答