最小二乘法多项式曲线拟合及其python实现

多项式曲线拟合问题描述

在这里插入图片描述问题描述:给定一些数据点,用一个多项式尽可能好的拟合出这些点排布的轨迹,并给出解析解
判断拟合的好坏常用的误差衡量方法是均方根误差,要求均方根误差先要求平方和误差:
在这里插入图片描述然后计算均方根误差:
在这里插入图片描述多项式拟合问题本质是一个优化问题,目标函数是使RMS误差最小。
本文关注于最小二乘法优化。

最小二乘法

在这里插入图片描述最小二乘法推导:RMS误差与E(W)成正比,E(W)最优等价于RMS最优
E(W):
在这里插入图片描述
对E(W)求导:
在这里插入图片描述
令导数=0:
在这里插入图片描述
通过给定X和T,可以直接求得W,W就是多项式拟合中的系数矩阵。

针对overfitting,加入正则项

在这里插入图片描述求导:
在这里插入图片描述
求出W:
在这里插入图片描述

python实现

import numpy as np
import math
import matplotlib.pyplot as plt
SAMPLE_NUM=200#要生成的sample个数
M=9#多项式阶数

#产生带有高斯噪声的信号
mid, sigma = 0, 0.3 # 设置均值和方差
noise = np.random.normal(mid, sigma, SAMPLE_NUM).reshape(SAMPLE_NUM,1) #生成SAMPLE_NUM个数据

#产生SAMPLE_NUM个序号(范围是2pi)
x = np.arange(0, SAMPLE_NUM).reshape(SAMPLE_NUM,1)/(SAMPLE_NUM-1)*(2*math.pi)

#generate y and y_noise, and both y's and y_noise's shape is (SAMPLE_NUM*1)
y=np.sin(x)
y_noise=np.sin(x)+noise

#绿色曲线显示x - y,散点显示x - y_noise
plt.title("")
plt.plot(x,y,'g',lw=4.0)
plt.plot(x,y_noise,'bo')
 

#generate Matrix X which has M order
X=x
for i in range(2,M+1):
         X = np.column_stack((X, pow(x,i)))

#add 1 on the first column of X, now X's shape is (SAMPLE_NUM*(M+1))
X = np.insert(X,0,[1],1)
#print(X)

#calculate W, W's shape is ((M+1)*1)#
#W=np.linalg.inv((X.T.dot(X))).dot(X.T).dot(y_noise)#have no regularization
W=np.linalg.inv((X.T.dot(X))+np.exp(-8) * np.eye(M+1)).dot(X.T).dot(y_noise)#introduce regularization
y_estimate=X.dot(W)

#红色曲线显示x - y_estimate
plt.plot(x,y_estimate,'r',lw=4.0)
plt.show()  

运行结果

绿色曲线 x-y
蓝色散点 x-y_noise
红色曲线 x-y_eatimate

  1. sample number=10,3th
    在这里插入图片描述

  2. sample number=10,9th
    在这里插入图片描述

  3. sample number=15,9th
    在这里插入图片描述

  4. sample number=100,9th
    在这里插入图片描述

  5. sample number=10,9th 加入正则项
    在这里插入图片描述
    加入正则项会有效缓解overfitting问题。

  • 34
    点赞
  • 238
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值