美文网首页
2020-05-15 第七章 线性回归模型

2020-05-15 第七章 线性回归模型

作者: 程凉皮儿 | 来源:发表于2020-05-15 14:33 被阅读0次

线性回归模型

内容目录

[TOC]

01 一元线性回归模型的介绍与应用

相关分析

image.png
image.png

回归分析

image.png

1、两边变量之间存在明显的线性关系;
2、根据常识,工作年限是因,薪资水平是果;
3、是否存在某个模型(即图中的一次函数)可以刻画两个变量之间的关系呢?

一元线性回归模型

image.png

1、模型中的x称为自变量,y 称为因变量;
2、 a为模型的截距项,b为模型的斜率项,ε为模型的误差项;
3、误差项ε的存在主要是为了平衡等号两边的值,通常被称为模型无法解释的部分;

参数a和b的求解

image.png

求解思路:
1、如果拟合线能够精确地捕捉到每一个点(即所有散点全部落在拟合线上),那么对应的误差项ε应该为0;
2、所以,模型拟合的越好,则误差项ε应该越小。进而可以理解为:求解参数的问题便是求解误差平方和最小的问题;

公式推导过程就不展示了,重要的是应用
模型应用

# 导入第三方模块
import statsmodels.api as sm

ols(formula, data, subset=None, drop_cols=None)

formula:以字符串的形式指定线性回归模型的公式,如'y~x'就表示简单线性回归模型
data:指定建模的数据集
subset:通过bool类型的数组对象,获取data的子集用于建模
drop_cols:指定需要从data中删除的变量

应用示例

# 工作年限与收入之间的散点图
# 导入第三方模块
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# 导入数据集
income = pd.read_csv('./第7章 线性回归模型/Salary_Data.csv')
# 绘制散点图
sns.lmplot(x = 'YearsExperience', y = 'Salary', data = income, ci = None)
# 显示图形
plt.show()
回归参数a的值: 25792.200198668666
回归参数b的值: 9449.962321455081

02 多元线性回归模型的系数推导

多元回归模型的预测

image.png
示例数据集包含5个变量,分别是产品的研发成本、管理成本、市场营销成本、销售市场和销售利润。
多元回归模型的预测示例
In [9]: # 导入第三方模块
   ...: import statsmodels.api as sm
   ...: # 利用收入数据集,构建回归模型
   ...: fit = sm.formula.ols('Salary ~ YearsExperience', data = income).fit()
   ...: # 返回模型的参数值
   ...: fit.params
Out[9]:
Intercept          25792.200199
YearsExperience     9449.962321
dtype: float64

In [10]: # 多元线性回归模型的构建和预测
    ...: # 导入模块
    ...: from sklearn import model_selection
    ...: # 导入数据
    ...: Profit = pd.read_excel('Predict to Profit.xlsx')
    ...: # 将数据集拆分为训练集和测试集
    ...: train, test = model_selection.train_test_split(Profit, test_size = 0.2,
    ...:  random_state=1234)
    ...: # 根据train数据集建模
    ...: model = sm.formula.ols('Profit ~ RD_Spend + Administration + Marketing_
    ...: Spend + C(State)', data = train).fit()
    ...: print('模型的偏回归系数分别为:\n', model.params)
    ...: # 删除test数据集中的Profit变量,用剩下的自变量进行预测
    ...: test_X = test.drop(labels = 'Profit', axis = 1)
    ...: pred = model.predict(exog = test_X)
    ...: print('对比预测值和实际值的差异:\n',pd.DataFrame({'Prediction':pred,'R
    ...: eal':test.Profit}))
模型的偏回归系数分别为:
 Intercept               58581.516503
C(State)[T.Florida]       927.394424
C(State)[T.New York]     -513.468310
RD_Spend                    0.803487
Administration             -0.057792
Marketing_Spend             0.013779
dtype: float64
对比预测值和实际值的差异:
        Prediction       Real
8   150621.345802  152211.77
48   55513.218079   35673.41
14  150369.022458  132602.65
42   74057.015562   71498.49
29  103413.378282  101004.64
44   67844.850378   65200.33
4   173454.059692  166187.94
31   99580.888895   97483.56
13  128147.138397  134307.35
18  130693.433835  124266.90

In [11]: # 生成由State变量衍生的哑变量
    ...: dummies = pd.get_dummies(Profit.State)
    ...: # 将哑变量与原始数据集水平合并
    ...: Profit_New = pd.concat([Profit,dummies], axis = 1)
    ...: # 删除State变量和California变量(因为State变量已被分解为哑变量,New Yor
    ...: k变量需要作为参照组)
    ...: Profit_New.drop(labels = ['State','New York'], axis = 1, inplace = True
    ...: )
    ...:
    ...: # 拆分数据集Profit_New
    ...: train, test = model_selection.train_test_split(Profit_New, test_size =
    ...: 0.2, random_state=1234)
    ...: # 建模
    ...: model2 = sm.formula.ols('Profit ~ RD_Spend + Administration + Marketing
    ...: _Spend + Florida + California', data = train).fit()
    ...: print('模型的偏回归系数分别为:\n', model2.params)
模型的偏回归系数分别为:
 Intercept          58068.048193
RD_Spend               0.803487
Administration        -0.057792
Marketing_Spend        0.013779
Florida             1440.862734
California           513.468310
dtype: float64

默认情况下,对于离散变量State而言,模型选择California值作为对照组。上述模型是通过哑变量的方式,自定义离散变量StateNew York值作为参照组。

03 线性回归模型的假设检验

模型的F 检验

  • 提出问题的原假设和备择假设
  • 在原假设的条件下,构造统计量F
  • 根据样本信息,计算统计量的值
  • 对比统计量的值和理论F分布的值,当统计量值超过理论值时,拒绝原假设,否则接受原假设

计算统计量

In [12]: # 导入第三方模块
    ...: import numpy as np
    ...: # 计算建模数据中,因变量的均值
    ...: ybar = train.Profit.mean()
    ...: # 统计变量个数和观测个数
    ...: p = model2.df_model
    ...: n = train.shape[0]
    ...: # 计算回归离差平方和
    ...: RSS = np.sum((model2.fittedvalues-ybar) ** 2)
    ...: # 计算误差平方和
    ...: ESS = np.sum(model2.resid ** 2)
    ...: # 计算F统计量的值
    ...: F = (RSS/p)/(ESS/(n-p-1))
    ...: print('F统计量的值:',F)
F统计量的值: 174.63721716844694

In [13]: model2.fvalue
Out[13]: 174.63721715703545

对比结果下结论

In [14]: # 导入模块
    ...: from scipy.stats import f
    ...: # 计算F分布的理论值
    ...: F_Theroy = f.ppf(q=0.95, dfn = p,dfd = n-p-1)
    ...: print('F分布的理论值为:',F_Theroy)
F分布的理论值为: 2.502635007415366

计算出来的F统计量值174.64远远大于F分布的理论值2.50,所以应当拒绝原假设,即认为多元线性回归模型是显著的,也就是说回归模型的偏回归系数都不全为0。

参数的t 检验

计算统计量

In [15]: # 模型的概览信息
    ...: model2.summary()
Out[15]:
<class 'statsmodels.iolib.summary.Summary'>
"""
                            OLS Regression Results
==============================================================================
Dep. Variable:                 Profit   R-squared:                       0.964
Model:                            OLS   Adj. R-squared:                  0.958
Method:                 Least Squares   F-statistic:                     174.6
Date:                Fri, 15 May 2020   Prob (F-statistic):           9.74e-23
Time:                        13:34:32   Log-Likelihood:                -401.20
No. Observations:                  39   AIC:                             814.4
Df Residuals:                      33   BIC:                             824.4
Df Model:                           5
Covariance Type:            nonrobust
===================================================================================
                      coef    std err          t      P>|t|      [0.025      0.975]
-----------------------------------------------------------------------------------
Intercept        5.807e+04   6846.305      8.482      0.000    4.41e+04     7.2e+04
RD_Spend            0.8035      0.040     19.988      0.000       0.722       0.885
Administration     -0.0578      0.051     -1.133      0.265      -0.162       0.046
Marketing_Spend     0.0138      0.015      0.930      0.359      -0.016       0.044
Florida          1440.8627   3059.931      0.471      0.641   -4784.615    7666.340
California        513.4683   3043.160      0.169      0.867   -5677.887    6704.824
==============================================================================
Omnibus:                        1.721   Durbin-Watson:                   1.896
Prob(Omnibus):                  0.423   Jarque-Bera (JB):                1.148
Skew:                           0.096   Prob(JB):                        0.563
Kurtosis:                       2.182   Cond. No.                     1.60e+06
==============================================================================

Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 1.6e+06. This might indicate that there are
strong multicollinearity or other numerical problems.
"""

对比结果下结论
从返回的结果可知,只有截距项Intercept和研发成本RD_Spend对应的p值小于0.05,才说明其余变量都没有通过系数的显著性检验,即在模型中这些变量不是影响利润的重要因素。

模型的假设前提

  • 误差项ε服从正态分布
  • 自变量之间无多重共线性
  • 因变量与自变量之间应存在线性相关性
  • 误差项ε的独立性
  • 误差项ε满足方差齐性

正态性检验

虽然模型的前提假设是对残差项要求服从正态分布,但是其实质就是要求因变量服从正态分布。对于多元线性回归模型y=Xβ+ε来说,等式右边的自变量属于已知变量,而等式左边的因变量为未知变量(故需要通过建模进行预测)。所以,要求误差项服从正态分布,就是要求因变量服从正态分布。

04 线性回归模型的诊断

正态性检验--图形法

In [16]: # 导入第三方模块
    ...: import scipy.stats as stats
    ...: # 中文和负号的正常显示
    ...: plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
    ...: plt.rcParams['axes.unicode_minus'] = False
    ...: # 绘制商品利润的直方图
    ...: sns.distplot(a = Profit_New.Profit, bins = 10, fit = stats.norm, norm_h
    ...: ist = True,
    ...:              hist_kws = {'color':'steelblue', 'edgecolor':'black'},
    ...:              kde_kws = {'color':'black', 'linestyle':'--', 'label':'den
    ...: sity'},
    ...:              fit_kws = {'color':'red', 'linestyle':':', 'label':'Normal
    ...:  distribution'})
    ...:
    ...: # 显示图例
    ...: plt.legend()
    ...: # 显示图形
    ...: plt.show()
image.png
In [17]: # 残差的正态性检验(PP图和QQ图法)
    ...: pp_qq_plot = sm.ProbPlot(Profit_New.Profit)
    ...: # 绘制PP图
    ...: pp_qq_plot.ppplot(line = '45')
    ...: plt.title('P-P plot')
    ...: # 绘制QQ图
    ...: pp_qq_plot.qqplot(line = 'q')
    ...: plt.title('Q-Q plot')
    ...:
    ...: # 显示图形
    ...: plt.show()
Figure_1.png Figure_2.png

正态性检验--非参数法

In [18]: # 导入模块
    ...: import scipy.stats as stats
    ...: # Shapiro检验
    ...: stats.shapiro(Profit_New.Profit)
Out[18]: (0.9793398380279541, 0.537902295589447)

Shapiro检验和K-S检验均属于非参数方法,它们的原假设被设定为变量服从正态分布,两者的最大区别在于适用的数据量不一样,若数据量低于5000,则使用Shapiro检验法比较合理,否则使用K-S检验法。

In [19]: # 生成正态分布和均匀分布随机数(样本量超过5000的情况)
    ...: rnorm = np.random.normal(loc = 5, scale=2, size = 10000)
    ...: runif = np.random.uniform(low = 1, high = 100, size = 10000)
    ...:
    ...: # 正态性检验
    ...: KS_Test1 = stats.kstest(rvs = rnorm, args = (rnorm.mean(), rnorm.std())
    ...: , cdf = 'norm')
    ...: KS_Test2 = stats.kstest(rvs = runif, args = (runif.mean(), runif.std())
    ...: , cdf = 'norm')
    ...: print(KS_Test1)
    ...: print(KS_Test2)
KstestResult(statistic=0.005564180034428545, pvalue=0.9162261273205484)
KstestResult(statistic=0.06025964224786401, pvalue=5.762552273231594e-32)

多重共线性检验

多重共线性是指模型中的自变量之间存在较高的线性相关关系,它的存在会给模型带来严重的后果,例如由“最小二乘法”得到的偏回归系数无效、增大偏回归系数的方差、模型缺乏稳定性等,所以,对模型的多重共线性检验就显得尤其重要了。

多重共线性检验--VIF方法

关于多重共线性的检验可以使用方差膨胀因子VIF来鉴定,如果VIF大于10,则说明变量间存在多重共线性;如果VIF大于100,则表名变量间存在严重的多重共线性。

多重共线性检验--VIF方法示例

In [20]: # 导入statsmodels模块中的函数
    ...: from statsmodels.stats.outliers_influence import variance_inflation_fac
    ...: tor
    ...:
    ...: # 自变量X(包含RD_Spend、Marketing_Spend和常数列1)
    ...: X = sm.add_constant(Profit_New.ix[:,['RD_Spend','Marketing_Spend']])
    ...:
    ...: # 构造空的数据框,用于存储VIF值
    ...: vif = pd.DataFrame()
    ...: vif["features"] = X.columns
    ...: vif["VIF Factor"] = [variance_inflation_factor(X.values, i) for i in ra
    ...: nge(X.shape[1])]
    ...: # 返回VIF值
    ...: vif
  File "<ipython-input-20-51ef0d8db197>", line 3

    ^
SyntaxError: invalid character in identifier


In [21]: # 导入statsmodels模块中的函数
    ...: from statsmodels.stats.outliers_influence import variance_inflation_fac
    ...: tor
    ...:
    ...: # 自变量X(包含RD_Spend、Marketing_Spend和常数列1)
    ...: X = sm.add_constant(Profit_New.ix[:,['RD_Spend','Marketing_Spend']])
    ...:
    ...: # 构造空的数据框,用于存储VIF值
    ...: vif = pd.DataFrame()
    ...: vif["features"] = X.columns
    ...: vif["VIF Factor"] = [variance_inflation_factor(X.values, i) for i in ra
    ...: nge(X.shape[1])]
    ...: # 返回VIF值
    ...: vif
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-21-63b09ec6d6b7> in <module>
      3
      4 # 自变量X(包含RD_Spend、Marketing_Spend和常数列1)
----> 5 X = sm.add_constant(Profit_New.ix[:,['RD_Spend','Marketing_Spend']])
      6
      7 # 构造空的数据框,用于存储VIF值

~/pandas-tutorial-master/venv/lib/python3.8/site-packages/pandas/core/generic.py in __getattr__(self, name)
   5272             if self._info_axis._can_hold_identifiers_and_holds_name(name):
   5273                 return self[name]
-> 5274             return object.__getattribute__(self, name)
   5275
   5276     def __setattr__(self, name: str, value) -> None:

AttributeError: 'DataFrame' object has no attribute 'ix'

In [22]: # 导入statsmodels模块中的函数
    ...: from statsmodels.stats.outliers_influence import variance_inflation_fac
    ...: tor
    ...:
    ...: # 自变量X(包含RD_Spend、Marketing_Spend和常数列1)
    ...: X = sm.add_constant(Profit_New.loc[:,['RD_Spend','Marketing_Spend']])
    ...:
    ...: # 构造空的数据框,用于存储VIF值
    ...: vif = pd.DataFrame()
    ...: vif["features"] = X.columns
    ...: vif["VIF Factor"] = [variance_inflation_factor(X.values, i) for i in ra
    ...: nge(X.shape[1])]
    ...: # 返回VIF值
    ...: vif
Out[22]:
          features  VIF Factor
0            const    4.540984
1         RD_Spend    2.026141
2  Marketing_Spend    2.026141

这里注意,复制代码的时候会不小心带入空字符,系统无法识别,另外由于Python更新速度较快,学习资料也显的有些老旧了,某些属性就发生了更改,凡遇报错就去搜索,都会找到答案的。

线性相关性检验

线性相关性检验,顾名思义,就是确保用于建模的自变量和因变量之间存在线性关系。关于线性关系的判断,可以使用Pearson相关系数和可视化方法进行识别。
线性相关性检验--相关系数法

In [23]: # 计算数据集Profit_New中每个自变量与因变量利润之间的相关系数
    ...: Profit_New.drop('Profit', axis = 1).corrwith(Profit_New.Profit)
Out[23]:
RD_Spend           0.978437
Administration     0.205841
Marketing_Spend    0.739307
California        -0.083258
Florida            0.088008
dtype: float64

线性相关性检验--图形法

In [24]: # 导入模块
    ...: import matplotlib.pyplot as plt
    ...: import seaborn
    ...:
    ...: # 绘制散点图矩阵
    ...: seaborn.pairplot(Profit_New.loc[:,['RD_Spend','Administration','Marketi
    ...: ng_Spend','Profit']])
    ...: # 显示图形
    ...: plt.show()
Figure_1.png
根据线性相关性检验的结果,选择两个与因变量最相关的自变量变量,重新建模:

异常值检验

由于多元线性回归模型容易受到极端值的影响,故需要利用统计方法对观测样本进行异常点检测。如果在建模过程中发现异常数据,需要对数据集进行整改,如删除异常值或衍生出是否为异常值的哑变量。

In [26]: # 模型修正
    ...: model3 = sm.formula.ols('Profit ~ RD_Spend + Marketing_Spend', data = t
    ...: rain).fit()
    ...: # 模型回归系数的估计值
    ...: model3.params
Out[26]:
Intercept          51902.112471
RD_Spend               0.785116
Marketing_Spend        0.019402
dtype: float64

In [27]: # 异常值检验
    ...: outliers = model3.get_influence()
    ...:
    ...: # 高杠杆值点(帽子矩阵)
    ...: leverage = outliers.hat_matrix_diag
    ...: # dffits值
    ...: dffits = outliers.dffits[0]
    ...: # 学生化残差
    ...: resid_stu = outliers.resid_studentized_external
    ...: # cook距离
    ...: cook = outliers.cooks_distance[0]

In [28]: # 合并各种异常值检验的统计量值
    ...: contat1 = pd.concat([pd.Series(leverage, name = 'leverage'),pd.Series(d
    ...: ffits, name = 'dffits'),pd.Series(resid_stu,name = 'resid_stu'),pd.Seri
    ...: es(cook, name = 'cook')],axis = 1)
    ...: # 重设train数据的行索引
    ...: train.index = range(train.shape[0])
    ...: # 将上面的统计量与train数据集合并
    ...: profit_outliers = pd.concat([train,contat1], axis = 1)
    ...: profit_outliers.head()
Out[28]:
    RD_Spend  Administration  Marketing_Spend  ...    dffits  resid_stu      cook
0   28663.76       127056.21        201126.82  ...  0.466410   1.747255  0.068601
1   15505.73       127382.30         35534.17  ...  0.221230   0.689408  0.016556
2   94657.16       145077.58        282574.31  ... -0.156225  -0.849138  0.008199
3  101913.08       110594.11        229160.95  ...  0.270677   1.332998  0.023906
4   78389.47       153773.43        299737.29  ... -0.228563  -1.078496  0.017335

[5 rows x 10 columns]

异常值处理

In [29]: # 计算异常值数量的比例
    ...: outliers_ratio = sum(np.where((np.abs(profit_outliers.resid_stu)>2),1,0
    ...: ))/ profit_outliers.shape[0]
    ...: outliers_ratio
Out[29]: 0.02564102564102564

In [30]: # 利用学生化残差挑选出非异常的观测点(由于异常比例非常小,故选择删除法
    ...: )
    ...: none_outliers = profit_outliers.ix[np.abs(profit_outliers.resid_stu)<=2
    ...: ,]
    ...: # 应用无异常值的数据集重新建模
    ...: model4 = sm.formula.ols ('Profit ~ RD_Spend + Marketing_Spend', data =
    ...: none_outliers).fit()
    ...: model4.params
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-30-83f9f1b79089> in <module>
      1 # 利用学生化残差挑选出非异常的观测点(由于异常比例非常小,故选择删除法)
----> 2 none_outliers = profit_outliers.ix[np.abs(profit_outliers.resid_stu)<=2,]
      3 # 应用无异常值的数据集重新建模
      4 model4 = sm.formula.ols ('Profit ~ RD_Spend + Marketing_Spend', data = none_outliers).fit()
      5 model4.params

~/pandas-tutorial-master/venv/lib/python3.8/site-packages/pandas/core/generic.py in __getattr__(self, name)
   5272             if self._info_axis._can_hold_identifiers_and_holds_name(name):
   5273                 return self[name]
-> 5274             return object.__getattribute__(self, name)
   5275
   5276     def __setattr__(self, name: str, value) -> None:

AttributeError: 'DataFrame' object has no attribute 'ix'

In [31]: # 利用学生化残差挑选出非异常的观测点(由于异常比例非常小,故选择删除法
    ...: )
    ...: none_outliers = profit_outliers.loc[np.abs(profit_outliers.resid_stu)<=
    ...: 2,]
    ...: # 应用无异常值的数据集重新建模
    ...: model4 = sm.formula.ols ('Profit ~ RD_Spend + Marketing_Spend', data =
    ...: none_outliers).fit()
    ...: model4.params
Out[31]:
Intercept          51827.416821
RD_Spend               0.797038
Marketing_Spend        0.017740
dtype: float64

Profit=51827.42+0.80RD_Spend+0.02Marketing_Spend

ε的独立性检验

残差的独立性检验,说白了也是对因变量y的独立性检验,因为在线性回归模型的等式左右只有y和残差项ε属于随机变量,如果再加上正态分布,就构成了残差项独立同分布于正态分布的假设。关于残差的独立性检验通常使用Durbin-Watson统计量值来测试。

In [33]: # 应用无异常值的数据集重新建模
    ...: model4 = sm.formula.ols('Profit ~ RD_Spend + Marketing_Spend', data = n
    ...: one_outliers).fit()
    ...: model4.params
Out[33]:
Intercept          51827.416821
RD_Spend               0.797038
Marketing_Spend        0.017740
dtype: float64

In [34]: # Durbin-Watson统计量
    ...: # 模型概览
    ...: model4.summary()
Out[34]:
<class 'statsmodels.iolib.summary.Summary'>
"""
                            OLS Regression Results
==============================================================================
Dep. Variable:                 Profit   R-squared:                       0.967
Model:                            OLS   Adj. R-squared:                  0.966
Method:                 Least Squares   F-statistic:                     520.7
Date:                Fri, 15 May 2020   Prob (F-statistic):           9.16e-27
Time:                        14:13:41   Log-Likelihood:                -389.18
No. Observations:                  38   AIC:                             784.4
Df Residuals:                      35   BIC:                             789.3
Df Model:                           2
Covariance Type:            nonrobust
===================================================================================
                      coef    std err          t      P>|t|      [0.025      0.975]
-----------------------------------------------------------------------------------
Intercept        5.183e+04   2501.192     20.721      0.000    4.67e+04    5.69e+04
RD_Spend            0.7970      0.034     23.261      0.000       0.727       0.867
Marketing_Spend     0.0177      0.013      1.391      0.173      -0.008       0.044
==============================================================================
Omnibus:                        7.188   Durbin-Watson:                   2.065
Prob(Omnibus):                  0.027   Jarque-Bera (JB):                2.744
Skew:                           0.321   Prob(JB):                        0.254
Kurtosis:                       1.851   Cond. No.                     5.75e+05
==============================================================================

Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 5.75e+05. This might indicate that there are
strong multicollinearity or other numerical problems.
"""

方差齐性检验

方差齐性是要求模型残差项的方差不随自变量的变动而呈现某种趋势,否则,残差的趋势就可以被自变量刻画。如果残差项不满足方差齐性(方差为一个常数),就会导致偏回归系数不具备有效性,甚至导致模型的预测也不准确。
方差齐性检验--图形法

In [35]: # 设置第一张子图的位置
    ...: ax1 = plt.subplot2grid(shape = (2,1), loc = (0,0))
    ...: # 绘制散点图
    ...: ax1.scatter(none_outliers.RD_Spend, (model4.resid-model4.resid.mean())/
    ...: model4.resid.std())
    ...: # 添加水平参考线
    ...: ax1.hlines(y = 0 ,xmin = none_outliers.RD_Spend.min(),
    ...: ^I^I  xmax = none_outliers.RD_Spend.max(), color = 'red', linestyles =
    ...: '--')
    ...: # 添加x轴和y轴标签
    ...: ax1.set_xlabel('RD_Spend')
    ...: ax1.set_ylabel('Std_Residual')
    ...:
    ...: # 设置第二张子图的位置
    ...: ax2 = plt.subplot2grid(shape = (2,1), loc = (1,0))

In [36]: # 绘制散点图
    ...: ax2.scatter(none_outliers.Marketing_Spend,
    ...: ^I^I   (model4.resid-model4.resid.mean())/model4.resid.std())
    ...: # 添加水平参考线
    ...: ax2.hlines(y = 0 ,xmin = none_outliers.Marketing_Spend.min(),
    ...: ^I^I  xmax = none_outliers.Marketing_Spend.max(), color = 'red', linest
    ...: yles = '--')
    ...: # 添加x轴和y轴标签
    ...: ax2.set_xlabel('Marketing_Spend')
    ...: ax2.set_ylabel('Std_Residual')
    ...:
    ...: # 调整子图之间的水平间距和高度间距
    ...: plt.subplots_adjust(hspace=0.6, wspace=0.3)
    ...: # 显示图形
    ...: plt.show()
Figure_1.png
方差齐性检验--统计法
In [42]: # BP检验
    ...: sm.stats.diagnostic.het_breuschpagan(model4.resid, exog_het = model4.mo
    ...: del.exog)
Out[42]:
(1.4675103668308342,
 0.48010272699006384,
 0.7029751237162462,
 0.5019659740962872)

参考资料中.het_breuschpagan,拼写错误。

如上结果所示,元组中一共包含四个值,

  • 第一个值1.468为LM统计量;
  • 第二个值是统计量对应的概率p值,该值大于0.05,说明接受残差方差为常数的原假设;
  • 第三个值为F统计量,用于检验残差平方项与自变量之间是否独立,如果独立则表明残差方差齐性;
  • 第四个值则为F统计量的概率p值,同样大于0.05,则进一步表示残差项满足方差齐性的假设。

05 线性回归模型的预测

预测案例

In [43]: # 模型预测
    ...: # model4对测试集的预测
    ...: pred4 = model4.predict(exog = test.loc[:,['RD_Spend','Marketing_Spend']
    ...: ])
    ...: # 对比预测值与实际值
    ...: pd.DataFrame({'Prediction':pred4,'Real':test.Profit})
Out[43]:
       Prediction       Real
8   153432.247049  152211.77
48   52259.451168   35673.41
14  151977.141752  132602.65
42   73295.606990   71498.49
29  106018.053241  101004.64
44   70006.559786   65200.33
4   171588.008207  166187.94
31  102120.376355   97483.56
13  129630.995695  134307.35
18  130186.711028  124266.90

In [44]: # model4对测试集的预测
    ...: pred4 = model4.predict(exog = test.loc[:,['RD_Spend','Marketing_Spend']
    ...: ])
    ...: # 绘制预测值与实际值的散点图
    ...: plt.scatter(x = test.Profit, y = pred4)
    ...: # 添加斜率为1、截距项为0的参考线
    ...: plt.plot([test.Profit.min(),test.Profit.max()],[test.Profit.min(),test.
    ...: Profit.max()],
    ...:         ^Icolor = 'red', linestyle = '--')
    ...:
    ...: # 添加轴标签
    ...: plt.xlabel('Actual value')
    ...: plt.ylabel('Predicted values')
    ...: # 显示图形
    ...: plt.show()
Figure_1.png

相关文章

  • 【机器学习实践】有监督学习:线性分类、回归模型

    线性模型 为线性模型 分类和回归的区别 分类:离散回归:连续本文主要关注线性回归模型 常用线性回归模型类型 OLS...

  • 算法笔记(6)-线性模型及Python代码实现

    线性模型不是特指某一个模型,而是一类模型,常用的线性模型包括线性回归、岭回归、套索回归、逻辑回归和线性SVC等。线...

  • logistics回归分类

    logistics回归分类模型和线性模型的关系非常密切;区分下线性回归模型和线性模型;线性模型:自变量和因变量之间...

  • 西瓜书 第3章 线性模型 学习笔记

    第3章 线性模型 3.1 基本形式 线性模型:向量形式表示线性模型: 3.2 线性回归 线性回归试图学得:均方误差...

  • 第一次打卡

    线性回归主要内容包括: 线性回归的基本要素线性回归模型从零开始的实现线性回归模型使用pytorch的简洁实现线性回...

  • 动手学深度学习(一) 线性回归

    线性回归 主要内容包括: 线性回归的基本要素 线性回归模型从零开始的实现 线性回归模型使用pytorch的简洁实现...

  • 线性回归

    线性回归 主要内容包括: 线性回归的基本要素 线性回归模型从零开始的实现 线性回归模型使用pytorch的简洁实现...

  • 第一天-线性回归,Softmax与分类模型,多层感知机

    线性回归 主要内容包括: 线性回归的基本要素 线性回归模型从零开始的实现 线性回归模型使用pytorch的简洁实现...

  • 数据挖掘3

    建模调参 内容介绍 线性回归模型:线性回归对于特征的要求;处理长尾分布;理解线性回归模型; 模型性能验证:评价函数...

  • 零基础入门数据挖掘-Task4 建模调参

    内容介绍 线性回归模型:线性回归对于特征的要求;处理长尾分布;理解线性回归模型; 模型性能验证:评价函数与目标函数...

网友评论

      本文标题:2020-05-15 第七章 线性回归模型

      本文链接:https://www.haomeiwen.com/subject/yjkcohtx.html