简单线性回归的应用及画图(一)

       本文采用线性回归的模型进行了练习。使用的模型的损失函数如下:

        代码首先生成了一些用于使用线性回归的数据然后加上了一些噪声,然后使用简单的线性回归和多项式回归进行拟合,画图计算的得分值并画图来判断拟合的效果:

import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
import matplotlib.pyplot as plt
from sklearn.pipeline import Pipeline
from sklearn.exceptions import ConvergenceWarning
import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = [u'simHei']
mpl.rcParams['axes.unicode_minus'] = False
import warnings

warnings.filterwarnings(action='ignore', category=ConvergenceWarning)
np.random.seed(0)
np.set_printoptions(linewidth=1000)
N = 7
x = np.linspace(0, 6, N) +  0.5 * np.random.randn(N)
x = np.sort(x)
y = x ** 2 - 4 * x - 3 +  2 * np.random.randn(N)
x.shape = -1, 1 # 将一维转换成二维
y.shape = -1, 1
model = Pipeline([('poly', PolynomialFeatures()), ('linear', LinearRegression(fit_intercept=False))])

np.set_printoptions(suppress=True)
plt.figure(figsize=(15, 12), facecolor='w')
d_pool = np.arange(1, N, 1)  # 阶
m = d_pool.size
title = '简单线性回归'
plt.figure(figsize=(12, 10), facecolor='w')
plt.plot(x, y, 'ro', ms=20, zorder=N)
for i, d in enumerate(d_pool):
    print()
    model.set_params(poly__degree=d)
    model.fit(x, y.ravel())
    lin = model.get_params('linear')['linear']
    output = '%s:%d阶,系数为:' % (title, d)
    print(output, lin.coef_.ravel()) # 偏置项和权重向量
    x_hat = np.linspace(x.min(), x.max(), num=100)
    x_hat.shape = -1, 1
    y_hat = model.predict(x_hat)
    s = model.score(x, y)
    print('预测性能得分(其实就是R^2):', s, '\n')
    z = N - 1 if (d == 2) else 0 
    # z是下面画图中的zorder参数的值,是指该线在图中的级别,数值越大,级别越高,
    # 在多线交叉时会显示在最上面,也就是会压住其他的线显示在最前面,这里是设置二阶拟合的级别最高
    label = '%d阶,$R^2$=%.3f' % (d, s)
    plt.plot(x_hat, y_hat, lw=5, alpha=1, label=label, zorder=z)

plt.legend(loc='upper left')
plt.grid(True)
plt.title(title, fontsize=18)
plt.xlabel('X', fontsize=16)
plt.ylabel('Y', fontsize=16)

plt.tight_layout(1, rect=(0, 0, 1, 0.95))
plt.suptitle('多项式曲线拟合比较', fontsize=22)
plt.show()

结果如下:

简单线性回归:1阶,系数为: [-11.59955139   3.21128547]
预测性能得分(其实就是R^2): 0.8473850440881161 


简单线性回归:2阶,系数为: [-4.759704   -2.40817855  0.80729147]
预测性能得分(其实就是R^2): 0.9881672192691497 


简单线性回归:3阶,系数为: [-3.10639837 -4.54966796  1.47170329 -0.05828197]
预测性能得分(其实就是R^2): 0.9894603396317786 


简单线性回归:4阶,系数为: [-7.11535811  2.57656227 -2.37520833  0.73370352 -0.05455689]
预测性能得分(其实就是R^2): 0.9903631737208167 


简单线性回归:5阶,系数为: [-3.60369003 -5.05417412  3.35121182 -1.18063556  0.23715757 -0.01645443]
预测性能得分(其实就是R^2): 0.9905487914062026 


简单线性回归:6阶,系数为: [  98.23215938 -304.34304116  330.18128658 -170.09864181   44.43797392   -5.66618534    0.27949474]
预测性能得分(其实就是R^2): 1.0 

画出的图线如下:

一共有七个点,因此最高能够生成一个六次方程完全通过这些点,但是这条线已经出现了严重的龙格现象。从二次到五次的差别都不大。

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值