# -*- coding: utf-8 -*-
"""
Created on Tue May 21 13:20:10 2013
@author: tokyo
"""
import numpy as np #惯例
from scipy.optimize import leastsq #这里就是我们要使用的最小二乘的函数
import pylab as pl
ORDER = 9 #多项式的次数
def real_func(x):
return np.sin(x) #sin(x)
def fake_func(p, x):
f = np.poly1d(p) #多项式分布的函数
return f(x)
#残差函数
#def residuals(p, y, x):
# return y - fake_func(p, x)
#正则化
def residuals(p, y, x):
ret = y - fake_func(p, x)
ret = np.append(ret, np.sqrt(0.5)*p) #将lambda^(1/2)p加在了返回的array的后面
return ret
#随机选了9个点,作为x
x = np.linspace(-3.14, 3.14, 10)
#画图的时候需要的“连续”的很多个点
x_show = np.linspace(-3.14, 3.14, 1000)
y0 = real_func(x)
#加入正态分布噪音后的y
y1 = [np.random.normal(0, 0.15) + y for y in y0]
#先随机产生一组多项式分布的参数
p0 = np.random.randn(ORDER+1)
plsq = leastsq(residuals, p0, args=(y1, x))
print 'Fitting Parameters :', plsq[0] #输出拟合参数
pl.plot(x_show, real_func(x_show), label='real')
pl.plot(x_show, fake_func(plsq[0], x_show), label='fitted curve')
pl.plot(x, y1, 'bo', label='with noise')
tlabel="M="+str(ORDER)
pl.title(tlabel)
pl.xlabel(u'X')
pl.ylabel(u'Y')
pl.legend()
pl.show()
05-24
05-24
04-18
08-28