您的当前位置:首页Python编程实现多项式拟合
Python编程实现多项式拟合
来源:锐游网
Python编程实现多项式拟合
初学机器学习,看到书中讲线性拟合,便试着用Python编程实现。所要拟合的函数为:
f(x)=sin(x)+ξ,x∈(0,20)
f
(
x
)
=
sin
(
x
)
+
ξ
,
x
∈
(
0
,
20
)
其中, ξ ξ 服从均差为0.3的高斯分布。
实现代码如下:
import numpy as np
import matplotlib.pyplot as plt
import math
class PolynomialFitting(object):
def __init__(self,degree=5,scale=50):
self.degree=degree
self.scale=scale
# 生成特征矩阵X
def generatingX(self):
self.x=np.arange(0,20,20/self.scale)
self.X=np.ones((self.scale,self.degree+1))
for i in range(self.scale):
for j in range(self.degree+1):
self.X[i,j]=math.pow(self.x[i],j)
# 生成矩阵Y
def generatingY(self):
self.Y=np.sin(self.x)+np.random.normal(scale=0.1,size=len(self.x))
self.Y=self.Y.reshape(self.scale,1)
# 求系数A
def generatingA(self):
self.A=np.linalg.inv(np.dot(self.X.T,self.X)).dot(self.X.T).dot(self.Y)
print("系数矩阵为:")
print(self.A)
# 测试
def test(self):
plt.plot(self.x,self.X.dot(self.A),'r')
plt.plot(self.x,self.Y,'g.')
plt.title("degree="+str(self.degree))
plt.show()
def main():
p=PolynomialFitting(degree=25,scale=1000)
p.generatingX()
p.generatingY()
p.generatingA()
p.test()
if __name__=="__main__":
main()
多次改变次数degree,所得结果如下(其中绿点为数据点,红线为拟合曲线):
因篇幅问题不能全部显示,请点此查看更多更全内容