标签:
知道函数形式,python用最小二乘法拟合函数参数
例子:
#-*- coding: utf-8 -*- #最小二乘拟合 #知道函数形式了,拟合函数的参数 #通过leastsq函数对带噪声的实验数据x, y1进行数据拟合,可以找到x和真实数据y0之间的正弦关系的三个参数: A, k, theta import numpy as np from scipy.optimize import leastsq import matplotlib.pyplot as pl def func(x,p): """ 拟合函数A*sin(2*pi*k*x +theta) """ A, k, theta = p #print A, k, theta return A*np.sin(2*np.pi*k*x+theta) def residuals(p, y, x): return y-func(x, p) x = np.linspace(0, -2*np.pi, 100) A, k, theta = 10, 0.34, np.pi/6 #真实数据函数参数 y0 = func(x, [A, k, theta]) y1 = y0 + 2*np.random.randn(len(x)) p0 = [7, 0.2, 0] #函数拟合参数 plsq = leastsq(residuals, p0, args=(y1, x)) print u"真实参数:", [A, k, theta] print u"拟合参数:", plsq[0] pl.clf() pl.plot(x, y0, label=u"真实数据:") pl.plot(x, y1, label=u"噪声数据") pl.plot(x, func(x, plsq[0]), label=u"拟合数据") pl.legend() pl.show()
参考:
标签:
原文地址:http://www.cnblogs.com/zlreco/p/4276755.html