Python 3.3中的非线性拟合

时间:2014-03-09 08:54:57

标签: python curve-fitting

我想知道如何在Python 3.3中进行非线性拟合。我没有在网上找到任何简单的例子。我不太了解这些拟合技术。

欢迎任何帮助!

提前致谢。

1 个答案:

答案 0 :(得分:6)

举一个简单的例子,访问http://www.walkingrandomly.com/?p=5215

以下是解释的代码!

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

xdata = np.array([-2,-1.64,-1.33,-0.7,0,0.45,1.2,1.64,2.32,2.9])
ydata = np.array([0.69,0.70,0.69,1.0,1.9,2.4,1.9,0.9,-0.7,-1.4])

def func(x, p1,p2):
  return p1*np.cos(p2*x) + p2*np.sin(p1*x)

# Here you give the initial parameters for p0 which Python then iterates over
# to find the best fit
popt, pcov = curve_fit(func,xdata,ydata,p0=(1.0,0.3))

print(popt) # This contains your two best fit parameters

# Performing sum of squares
p1 = popt[0]
p2 = popt[1]
residuals = ydata - func(xdata,p1,p2)
fres = sum(residuals**2)

print(fres)

xaxis = np.linspace(-2,3,100) # we can plot with xdata, but fit will not look good 
curve_y = func(xaxis,p1,p2)
plt.plot(xdata,ydata,'*')
plt.plot(xaxis,curve_y,'-')
plt.show()

enter image description here