李航《统计学习方法》最小二乘法代码

李航《统计学习方法》最小二乘法代码

import numpy as np 
import scipy as sp
from scipy.optimize import leastsq
import matplotlib.pyplot as plt

#目标函数
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

def fitting(M = 0):
    #使用np.linspace生成从0到1的10个数
    x = np.linspace(0,1,10)
    #生成x_points数据用于绘制拟合曲线图
    x_points = np.linspace(0,1,1000)
    #生成目标函数真值
    y_ = real_func(x)
    #给目标函数真值加入噪声点
    y = [np.random.normal(0,0.1) + y1 for y1 in y_]

    #M是N次多项式中的N,N次多项式对应的参数为N+1个
    p_init = np.random.rand(M+1)
    #调用Scipy.optimize中的最小二乘函数leastsq(残差函数,多项式函数参数,数据点)
    p_lsq = leastsq(residuals_func, p_init,args = (x,y))
    #leastsq函数返回结果的第一行才是拟合曲线的参数列表
    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()
    plt.show()
    return p_lsq


if __name__ == "__main__":
    M = 3
    p_lsq_2 = fitting(M)
    print('end')

猜你喜欢

转载自blog.csdn.net/m0_45388819/article/details/113757999