线性回归知识点总结

线性回归的定义

线性回归是利用数理统计中回归分析,来确定两种或两种以上变量间相互依赖的定量关系的一种统计分析方法,运用十分广泛。其表达形式为y = w’x+e,e为误差服从均值为0的正态分布。

一元线性回归

回归分析中,只包括一个自变量和一个因变量,且二者的关系可用一条直线近似表示,这种回归分析称为一元线性回归分析。

多元线性回归

如果回归分析中包括两个或两个以上的自变量,且因变量和自变量之间是线性关系,则称为多元线性回归分析。

线性回归拟合方程

最小二乘法

最小二乘法又称最小平方法,它通过最小化误差的平方和寻找数据的最佳函数匹配。利用最小二乘法可以简便地求得未知的数据,并使得这些求得的数据与实际数据之间误差的平方和为最小。最小二乘法还可用于曲线拟合。

一般来说,线性回归都可以通过最小二乘法求出其方程,可以计算出对于y=bx+a的直线。一般地,影响y的因素往往不止一个,假设有x1,x2,…,xk,k个因素,通常可考虑如下的线性关系式:
y = β 0 + β 1 x 1 + β 2 x 2 + . . . . . . + β k x k + ε y=β_0+β_1x_1+β_2x_2+......+β_kx_k+ε y=β0+β1x1+β2x2+......+βkxk+ε
对y与 x 1 , x 2 , . . . . . . , x k , x_1,x_2,......,x_k, x1,x2,......,xk,同时作为n次独立观察得n组观测值 ( x t 1 , x t 2 , . . . . . . , x t k ) , t = 1 , 2 , . . . . . . n ( n > k + 1 ) , (x_{t1},x_{t2},......,x_{tk}),t=1,2,......n(n>k+1), xt1xt2......xtk,t=1,2,......n(n>k+1),同时他们能满足关系:
y = β 0 + β 1 x t 1 + β 2 x t 2 + . . . . . . + β k x t k + ε t y=β_0+β_1x_{t1}+β_2x_{t2}+......+β_kx_{tk}+ε_t y=β0+β1xt1+β2xt2+......+βkxtk+εt
其中 ε 1 , ε 2 , . . . . . . , ε n ε_1,ε_2,......,ε_n ε1,ε2,......,εn互不相关均是与ε同分布的随机变量。为了用矩阵表示上式,于是有了Y=Xβ+ε,使用最小二乘法得到β的解 β − = ( X T X ) − 1 X T Y 。 β^-=(X^TX)^{-1}X^TY。 β=(XTX)1XTY
其中, ( X T X ) − 1 X T (X^TX)^{-1}X^T (XTX)1XT称为X的逆。

回归系数

一般地,要求这个值大于5%。
对大部分的行为研究者来讲,最重要的是回归系数。
年龄增加1个单位,文档的质量就下降 -.1020986个单位,表明年长的人对文档质量的评价会更低。这个变量相应的t值是 -2.10,绝对值大于2,p值也<0.05,所以是显著的。
结论是,年长的人对文档质量的评价会更低,这个影响是显著的。相反,领域知识越丰富的人,对文档的质量评估会更高,但是这个影响不是显著的。这种对回归系数的理解就是使用回归分析进行假设检验的过程。

回归方程误差

离差平方和

y = b x + a + ε , ε   N ( 0 , δ 2 ) , δ 2 = S S E n − 2 = S y y n − 2 ( 1 − r 2 ) y=bx+a+ε,ε~N(0,δ^2),δ^2=\frac{SSE}{n-2}=\frac{S_{yy}}{n-2}(1-r^2) y=bx+a+ε,ε N(0,δ2),δ2=n2SSE=n2Syy(1r2)
其中, S y y = ∑ ( y − y − ) 2 S_{yy}=\sum (y-y^-)^2 Syy=(yy)2
代表y的平方和;r 是相关系数,代表变异被回归直线解释的比例 S y y ( 1 − r 2 ) S_{yy}(1-r^2) Syy(1r2) 就是不能被回归直线解释的变异,即SSE。

利用预测值

δ 2 = ( Y i − y i ) 2 n − 2 δ^2=\frac{(Y_i-y_i)^2}{n-2} δ2=n2(Yiyi)2 其中y_i是实际测量值,Y_i是根据直线方程算出来的预测值。

实际线性回归时候的数据使用

此处分析不仅仅局限于线性回归。

实际中可以把数据分为训练数据和测试数据,然后根据不同模型在测试数据上的表现来选择模型。

另外一些情况,比如上边加上正则化之后,我们不能由训练数据得到lambda,那么我们需要把训练数据进一步划分为训练数据和验证数据。在训练数据上学习theta和lambda,然后在验证数据上选择lambda,然后再在测试数据上验证选择不同模型。

实际中采用交叉验证充分利用数据,例如五折交叉验证。
在这里插入图片描述

代码实现

线性回归库的调用

#!/usr/bin/python
# -*- coding:utf-8 -*-

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import Lasso, Ridge
from sklearn.model_selection import GridSearchCV


if __name__ == "__main__":
    # pandas读入
    data = pd.read_csv('8.Advertising.csv')    # TV、Radio、Newspaper、Sales
    x = data[['TV', 'Radio', 'Newspaper']]
    # x = data[['TV', 'Radio']]
    y = data['Sales']
    print x
    print y

    x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=1)
    # print x_train, y_train
    model = Lasso()
    # model = Ridge()

    alpha_can = np.logspace(-3, 2, 10)  #10^(-3) ~ 10^(2) 等比10个数
    lasso_model = GridSearchCV(model, param_grid={'alpha': alpha_can}, cv=5) #5折交叉验证
    lasso_model.fit(x, y)
    print '验证参数:\n', lasso_model.best_params_

    y_hat = lasso_model.predict(np.array(x_test))
    mse = np.average((y_hat - np.array(y_test)) ** 2)  # Mean Squared Error
    rmse = np.sqrt(mse)  # Root Mean Squared Error
    print mse, rmse

    t = np.arange(len(x_test))
    plt.plot(t, y_test, 'r-', linewidth=2, label='Test')
    plt.plot(t, y_hat, 'g-', linewidth=2, label='Predict')
    plt.legend(loc='upper right')
    plt.grid()
    plt.show()

线性回归多项式拟合

#!/usr/bin/python
# -*- coding:utf-8 -*-

import numpy as np
from sklearn.linear_model import LinearRegression, RidgeCV
from sklearn.preprocessing import PolynomialFeatures
import matplotlib.pyplot as plt
from sklearn.pipeline import Pipeline
import matplotlib as mpl


if __name__ == "__main__":
    np.random.seed(0) # 指定种子
    N = 9
    x = np.linspace(0, 6, N) + np.random.randn(N)
    x = np.sort(x)
    y = x**2 - 4*x - 3 + np.random.randn(N)
    # print x
    # print y
    x.shape = -1, 1
    y.shape = -1, 1
    # print x
    # print y

    model_1 = Pipeline([
        ('poly', PolynomialFeatures()),
        ('linear', LinearRegression(fit_intercept=False))])
    model_2 = Pipeline([
        ('poly', PolynomialFeatures()),
        ('linear', RidgeCV(alphas=np.logspace(-3, 2, 100), fit_intercept=False))])
    models = model_1, model_2
    mpl.rcParams['font.sans-serif'] = [u'simHei']
    mpl.rcParams['axes.unicode_minus'] = False
    np.set_printoptions(suppress=True)

    plt.figure(figsize=(9, 11), facecolor='w')
    d_pool = np.arange(1, N, 1)  # 阶
    m = d_pool.size
    clrs = []  # 颜色
    for c in np.linspace(16711680, 255, m):
        clrs.append('#%06x' % c)
    line_width = np.linspace(5, 2, m)
    titles = u'线性回归', u'Ridge回归'
    for t in range(2):
        model = models[t]
        plt.subplot(2, 1, t+1)
        plt.plot(x, y, 'ro', ms=10, zorder=N)
        for i, d in enumerate(d_pool):
            model.set_params(poly__degree=d)
            model.fit(x, y)
            lin = model.get_params('linear')['linear']
            if t == 0:
                print u'%d阶,系数为:' % d, lin.coef_.ravel()
            else:
                print u'%d阶,alpha=%.6f,系数为:' % (d, lin.alpha_), 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 s, '\n'
            zorder = N - 1 if (d == 2) else 0
            plt.plot(x_hat, y_hat, color=clrs[i], lw=line_width[i], label=(u'%d阶,score=%.3f' % (d, s)), zorder=zorder)
        plt.legend(loc='upper left')
        plt.grid(True)
        plt.title(titles[t], fontsize=16)
        plt.xlabel('X', fontsize=14)
        plt.ylabel('Y', fontsize=14)
    plt.tight_layout(1, rect=(0, 0, 1, 0.95))
    plt.suptitle(u'多项式曲线拟合', fontsize=18)
    plt.show()

线性回归代码

import numpy as np
import matplotlib.pyplot as plt
def regression(data, alpha, lamda ):
    n = len(data[0]) - 1
    theta = np.zeros(n)
    times = 1
    for i in range(times):
        for d in data:
            x = d[:-1]
            y = d[-1]
            h_theta = np.dot(theta, x) - y
            theta = theta - alpha * h_theta * x + lamda * theta
        #print i,theta
    return theta
def preduceData():
   x = []
   y = []
   for i in range(0, 50):
       x.append(i)
       y.append(3 * x[i] + np.random.random_sample()*3)
   data = np.array([x, y]).T
   theta = regression(data, 0.001, 0.1)
   return x, y, theta
def myplot(x, y, theta):
    plt.figure()
    plt.plot(x, y, 'go')
    plt.plot(x, theta * x, 'r')
    plt.show()
x, y, theta = preduceData()
myplot(x, y, theta)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值