《统计学习方法》学习笔记(第一章)

第一章 统计学习方法概论

使用最小二乘法拟和曲线

源代码出处:https://github.com/fengdu78/lihang-code/blob/master/code/第1章 统计学习方法概论(LeastSquaresMethod)/least_sqaure_method.ipynb

对于数据 ( x i , y i ) ( i = 1 , 2 , 3... , m ) (x_i, y_i)(i=1, 2, 3...,m)
拟合出函数 h ( x ) h(x)
有误差,即残差: r i = h ( x i ) y i r_i=h(x_i)-y_i
此时L2范数(残差平方和)最小时,h(x) 和 y 相似度最高,更拟合一般的H(x)为n次的多项式, H ( x ) = w 0 + w 1 x + w 2 x 2 + . . . w n x n H(x)=w_0+w_1x+w_2x^2+...w_nx^n
w ( w 0 , w 1 , w 2 , . . . , w n ) w(w_0,w_1,w_2,...,w_n) 为参数
最小二乘法就是要找到一组 w ( w 0 , w 1 , w 2 , . . . , w n ) w(w_0,w_1,w_2,...,w_n) 使得 i = 1 n ( h ( x i ) y i ) 2 \sum_{i=1}^n(h(x_i)-y_i)^2 (残差平方和) 最小,即,求 m i n i = 1 n ( h ( x i ) y i ) 2 min\sum_{i=1}^n(h(x_i)-y_i)^2

举例:我们用目标函数 y = s i n 2 π x y=sin2{\pi}x , 加上一个正太分布的噪音干扰,用多项式去拟合【例1.1 11页】

import numpy as np
import scipy as sp
from scipy.optimize import leastsq
import matplotlib.pyplot as plt
%matplotlib inline
# 目标函数
def real_func(x):
    return np.sin(2*np.pi*x)

# 多项式
def fit_func(p, x):
    f = np.poly1d(p)
    return f(x)

# 残差
def residuals_func(p, x, y):
    ret = fit_func(p, x) - y
    return ret
#十个点
x = np.linspace(0,1,10)
x_points = np.linspace(0,1,1000)

#加上正态分布噪声的目标函数值
y_=real_func(x)
y = [np.random.normal(0,0.1)+y1 for y1 in y_]

def fitting(M=0):
    #随机初始化多项式函数
    p_init = np.random.rand(M+1)
    #最小二乘法
    p_lsq = leastsq(residuals_func,p_init,args=(x,y))
    print('Fitting Parameters:',p_lsq[0])
    
    #可视化
    plt.plot(x_points,real_func(x_points),label='real')
    plt.plot(x_points,fit_func(p_lsq[0],x_points),label='fitted curve')
    plt.plot(x,y,'bo',label='noise')
    plt.legend()
    return p_lsq
# M=0
p_lsq_0 = fitting(M=0)
  • 问题1:np.poly1d()此函数用法

np.poly1d()此函数有两个参数
参数1:若没有参数2,参数1为数组,则生成一个多项式,
例如:   p = np.poly1d([2,5,3,1])
      print( p)==>>2x3 + 5x2 + 3x + 1
数组中的数值为系数,从后往前 0,1,2,3为对应的次数

参数2:若参数2为True,则表示把数组中的值作为根,然后反推多项式,例如:
      q = np.poly1d([2,3,5],True)
      print(q) ===>>(x - 2)(x - 3)(x - 5) = x3 - 10x2 + 31x -30

  • 问题2:使用jupyter notebook 画图时,可视化不显示

需要在你的程序中加一行代码

%matplotlib inline

%matplotlib具体作用是当你调用matplotlib.pyplot的绘图函数plot()进行绘图的时候,或者生成一个figure画布的时候,可以直接在你的python console里面生成图像

  • 问题3 :最优化函数库Optimization

优化是找到最小值或等式的数值解的问题。scipy.optimization子模块提供了函数最小值(标量或多维)、曲线拟合和寻找等式的根的有用算法。

在optimize模块中可以使用leastsq()对数据进行最小二乘拟合计算。leastsq() 只需要将计算误差的函数和待确定参数 的初始值传递给它即可。

p_lsq = leastsq(residuals_func,p_init,args=(x,y))

leastsq()函数传入误差计算函数和初始值,进行数据拟合, residuals为计算误差的函数,p_init为拟合参数的初始值,args为需要拟合的实验数据。调用args参数,用于指定residuals中使用到的其他参数,同样也返回一个元组,第一个元素为拟合后的参数数组,因此residuals()有三个参数,p是多项式的参数,y和x是表示实验数据的数组。

猜你喜欢

转载自blog.csdn.net/Hhhhuply/article/details/88256830