多元线性回归的python实现

来源:互联网 发布:mac桌面出现ds store 编辑:程序博客网 时间:2024/05/16 09:59

1、什么是多元线性回归模型?

y值的影响因素唯一时,用多元线性回归模型

  y =y=β0+β1x1+β2x2+...+βnxn 

例如商品的销售额可能不电视广告投入,收音机广告投入,报纸广告投入有关系,可以有 sales =β0+β1*TV+β2* radio+β3*newspaper.


2、使用pandas来读取数据

pandas 是一个用于数据探索、数据分析和数据处理的Python库

[python] view plain copy
 print?
  1. import pandas as pd  

[html] view plain copy
 print?
  1. <pre name="code" class="python"># read csv file directly from a URL and save the results    
  2. data = pd.read_csv('/home/lulei/Advertising.csv')  
  3.   
  4. # display the first 5 rows  
  5. data.head()  



这里的Advertising.csv是来自http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv。大家可以自己下载。

上面代码的运行结果:

     TV  Radio  Newspaper  Sales0  230.1   37.8       69.2   22.11   44.5   39.3       45.1   10.42   17.2   45.9       69.3    9.33  151.5   41.3       58.5   18.54  180.8   10.8       58.4   12.9

上面显示的结果类似一个电子表格,这个结构称为Pandas的数据帧(data frame),类型全称:pandas.core.frame.DataFrame.

pandas的两个主要数据结构:Series和DataFrame:

  • Series类似于一维数组,它有一组数据以及一组与之相关的数据标签(即索引)组成。
  • DataFrame是一个表格型的数据结构,它含有一组有序的列,每列可以是不同的值类型。DataFrame既有行索引也有列索引,它可以被看做由Series组成的字典。

[python] view plain copy
 print?
  1. # display the last 5 rows  
  2. data.tail()  
只显示结果的末尾5行

        TV  Radio  Newspaper  Sales195   38.2    3.7       13.8    7.6196   94.2    4.9        8.1    9.7197  177.0    9.3        6.4   12.8198  283.6   42.0       66.2   25.5199  232.1    8.6        8.7   13.4
[html] view plain copy
 print?
  1. # check the shape of the DataFrame(rows, colums)  
  2. data.shape  
查看DataFrame的形状,注意第一列的叫索引,和数据库某个表中的第一列类似。

(200,4) 


3、分析数据

特征:

  • TV:对于一个给定市场中单一产品,用于电视上的广告费用(以千为单位)
  • Radio:在广播媒体上投资的广告费用
  • Newspaper:用于报纸媒体的广告费用

响应:

  • Sales:对应产品的销量

在这个案例中,我们通过不同的广告投入,预测产品销量。因为响应变量是一个连续的值,所以这个问题是一个回归问题。数据集一共有200个观测值,每一组观测对应一个市场的情况。

注意:这里推荐使用的是seaborn包。网上说这个包的数据可视化效果比较好看。其实seaborn也应该属于matplotlib的内部包。只是需要再次的单独安装。

[python] view plain copy
 print?
  1. import seaborn as sns  
  2. import matplotlib.pyplot as plt   
  3. # visualize the relationship between the features and the response using scatterplots  
  4. sns.pairplot(data, x_vars=['TV','Radio','Newspaper'], y_vars='Sales', size=7, aspect=0.8)  
  5. plt.show()#注意必须加上这一句,否则无法显示。  

[html] view plain copy
 print?
  1. 这里选择TV、Radio、Newspaper 作为特征,Sales作为观测值  
[html] view plain copy
 print?
  1. 返回的结果:  

seaborn的pairplot函数绘制X的每一维度和对应Y的散点图。通过设置size和aspect参数来调节显示的大小和比例。可以从图中看出,TV特征和销量是有比较强的线性关系的,而Radio和Sales线性关系弱一些,Newspaper和Sales线性关系更弱。通过加入一个参数kind='reg',seaborn可以添加一条最佳拟合直线和95%的置信带。

[python] view plain copy
 print?
  1. sns.pairplot(data, x_vars=['TV','Radio','Newspaper'], y_vars='Sales', size=7, aspect=0.8, kind='reg')  
  2. plt.show()  

结果显示如下:


4、线性回归模型

优点:快速;没有调节参数;可轻易解释;可理解。

缺点:相比其他复杂一些的模型,其预测准确率不是太高,因为它假设特征和响应之间存在确定的线性关系,这种假设对于非线性的关系,线性回归模型显然不能很好的对这种数据建模。

线性模型表达式: y=β0+β1x1+β2x2+...+βnxn 其中

  • y是响应
  • β0
  • β1x1

在这个案例中: y=β0+β1TV+β2Radio+...+βnNewspaper

(1)、使用pandas来构建X(特征向量)和y(标签列)

scikit-learn要求X是一个特征矩阵,y是一个NumPy向量。

pandas构建在NumPy之上。

因此,X可以是pandas的DataFrame,y可以是pandas的Series,scikit-learn可以理解这种结构。

[python] view plain copy
 print?
  1. #create a python list of feature names  
  2. feature_cols = ['TV''Radio''Newspaper']  
  3. # use the list to select a subset of the original DataFrame  
  4. X = data[feature_cols]  
  5. # equivalent command to do this in one line  
  6. X = data[['TV''Radio''Newspaper']]  
  7. # print the first 5 rows  
  8. print X.head()  
  9. # check the type and shape of X  
  10. print type(X)  
  11. print X.shape  
输出结果如下:

      TV  Radio  Newspaper0  230.1   37.8       69.21   44.5   39.3       45.12   17.2   45.9       69.33  151.5   41.3       58.54  180.8   10.8       58.4<class 'pandas.core.frame.DataFrame'>(200, 3)
[python] view plain copy
 print?
  1. # select a Series from the DataFrame  
  2. y = data['Sales']  
  3. # equivalent command that works if there are no spaces in the column name  
  4. y = data.Sales  
  5. # print the first 5 values  
  6. print y.head()  
输出的结果如下:

0    22.11    10.42     9.33    18.54    12.9Name: Sales

(2)、构建训练集与测试集

[html] view plain copy
 print?
  1. <pre name="code" class="python"><span style="font-size:14px;">##构造训练集和测试集  
  2. from sklearn.cross_validation import train_test_split  #这里是引用了交叉验证  
  3. X_train,X_test, y_train, y_test = train_test_split(X, y, random_state=1)  


#default split is 75% for training and 25% for testing
[html] view plain copy
 print?
  1. print X_train.shape  
  2. print y_train.shape  
  3. print X_test.shape  
  4. print y_test.shape  

输出结果如下:

(150, 3)(150,)(50, 3)(50,)
注:上面的结果是由train_test_spilit()得到的,但是我不知道为什么我的版本的sklearn包中居然报错:
ImportError                               Traceback (most recent call last)<ipython-input-182-3eee51fcba5a> in <module>()      1 ###构造训练集和测试集----> 2 from sklearn.cross_validation import train_test_split      3 #import sklearn.cross_validation      4 X_train,X_test, y_train, y_test = train_test_split(X, y, random_state=1)      5 # default split is 75% for training and 25% for testingImportError: cannot import name train_test_split
处理方法:1、我后来重新安装sklearn包。再一次调用时就没有错误了。
                  2、自己写函数来认为的随机构造训练集和测试集。(这个代码我会在最后附上。)
(3)sklearn的线性回归

[html] view plain copy
 print?
  1. from sklearn.linear_model import LinearRegression  
  2. linreg = LinearRegression()  
  3. model=linreg.fit(X_train, y_train)  
  4. print model  
  5. print linreg.intercept_  
  6. print linreg.coef_  

输出的结果如下:

LinearRegression(copy_X=True, fit_intercept=True, normalize=False)2.66816623043[ 0.04641001  0.19272538 -0.00349015]

[html] view plain copy
 print?
  1. # pair the feature names with the coefficients  
  2. zip(feature_cols, linreg.coef_)  
输出如下:

[('TV', 0.046410010869663267), ('Radio', 0.19272538367491721), ('Newspaper', -0.0034901506098328305)]


y=2.668+0.0464TV+0.192Radio-0.00349Newspaper
如何解释各个特征对应的系数的意义?

对于给定了Radio和Newspaper的广告投入,如果在TV广告上每多投入1个单位,对应销量将增加0.0466个单位。就是加入其它两个媒体投入固定,在TV广告上每增加1000美元(因为单位是1000美元),销量将增加46.6(因为单位是1000)。但是大家注意这里的newspaper的系数居然是负数,所以我们可以考虑不使用newspaper这个特征。这是后话,后面会提到的。

(4)、预测

[python] view plain copy
 print?
  1. y_pred = linreg.predict(X_test)  
  2. print y_pred  
[python] view plain copy
 print?
  1. print type(y_pred)  

输出结果如下:

[ 14.58678373   7.92397999  16.9497993   19.35791038   7.36360284   7.35359269  16.08342325   9.16533046  20.35507374  12.63160058  22.83356472   9.66291461   4.18055603  13.70368584  11.4533557   4.16940565  10.31271413  23.06786868  17.80464565  14.53070132  15.19656684  14.22969609   7.54691167  13.47210324  15.00625898  19.28532444  20.7319878   19.70408833  18.21640853   8.50112687   9.8493781    9.51425763   9.73270043  18.13782015  15.41731544   5.07416787  12.20575251  14.05507493  10.6699926    7.16006245  11.80728836  24.79748121  10.40809168  24.05228404  18.44737314  20.80572631   9.45424805  17.00481708   5.78634105   5.10594849]<type 'numpy.ndarray'>

5、回归问题的评价测度

(1) 评价测度

对于分类问题,评价测度是准确率,但这种方法不适用于回归问题。我们使用针对连续数值的评价测度(evaluation metrics)。
这里介绍3种常用的针对线性回归的测度。

1)平均绝对误差(Mean Absolute Error, MAE)

(2)均方误差(Mean Squared Error, MSE)

(3)均方根误差(Root Mean Squared Error, RMSE)

这里我使用RMES。

[python] view plain copy
 print?
  1. <pre name="code" class="python">#计算Sales预测的RMSE  
  2. print type(y_pred),type(y_test)  
  3. print len(y_pred),len(y_test)  
  4. print y_pred.shape,y_test.shape  
  5. from sklearn import metrics  
  6. import numpy as np  
  7. sum_mean=0  
  8. for i in range(len(y_pred)):  
  9.     sum_mean+=(y_pred[i]-y_test.values[i])**2  
  10. sum_erro=np.sqrt(sum_mean/50)  
  11. # calculate RMSE by hand  
  12. print "RMSE by hand:",sum_erro  

最后的结果如下:

<type 'numpy.ndarray'> <class 'pandas.core.series.Series'>50 50(50,) (50,)RMSE by hand: 1.42998147691
(2)做ROC曲线

[python] view plain copy
 print?
  1. import matplotlib.pyplot as plt  
  2. plt.figure()  
  3. plt.plot(range(len(y_pred)),y_pred,'b',label="predict")  
  4. plt.plot(range(len(y_pred)),y_test,'r',label="test")  
  5. plt.legend(loc="upper right"#显示图中的标签  
  6. plt.xlabel("the number of sales")  
  7. plt.ylabel('value of sales')  
  8. plt.show()  

显示结果如下:(红色的线是真实的值曲线,蓝色的是预测值曲线)


直到这里整个的一次多元线性回归的预测就结束了。

6、改进特征的选择
在之前展示的数据中,我们看到Newspaper和销量之间的线性关系竟是负关系(不用惊讶,这是随机特征抽样的结果。换一批抽样的数据就可能为正了),现在我们移除这个特征,看看线性回归预测的结果的RMSE如何?

依然使用我上面的代码,但只需修改下面代码中的一句即可:

[python] view plain copy
 print?
  1. #create a python list of feature names  
  2. feature_cols = ['TV''Radio''Newspaper']  
  3. # use the list to select a subset of the original DataFrame  
  4. X = data[feature_cols]  
  5. # equivalent command to do this in one line  
  6. #X = data[['TV', 'Radio', 'Newspaper']]#只需修改这里即可<pre name="code" class="python" style="font-size: 15px; line-height: 35px;">X = data[['TV', 'Radio']]  #去掉newspaper其他的代码不变  
# print the first 5 rowsprint X.head()# check the type and shape of Xprint type(X)print X.shape

最后的到的系数与测度如下:

LinearRegression(copy_X=True, fit_intercept=True, normalize=False)

2.81843904823[ 0.04588771  0.18721008]RMSE by hand: 1.28208957507
然后再次使用ROC曲线来观测曲线的整体情况。我们在将Newspaper这个特征移除之后,得到RMSE变小了,说明Newspaper特征可能不适合作为预测销量的特征,于是,我们得到了新的模型。我们还可以通过不同的特征组合得到新的模型,看看最终的误差是如何的。

备注:

之前我提到了这种错误:

注:上面的结果是由train_test_spilit()得到的,但是我不知道为什么我的版本的sklearn包中居然报错:
ImportError                               Traceback (most recent call last)<ipython-input-182-3eee51fcba5a> in <module>()      1 ###构造训练集和测试集----> 2 from sklearn.cross_validation import train_test_split      3 #import sklearn.cross_validation      4 X_train,X_test, y_train, y_test = train_test_split(X, y, random_state=1)      5 # default split is 75% for training and 25% for testingImportError: cannot import name train_test_split
处理方法:1、我后来重新安装sklearn包。再一次调用时就没有错误了。
                  2、自己写函数来认为的随机构造训练集和测试集。(这个代码我会在最后附上。)
这里我给出我自己写的函数:

[python] view plain copy
 print?
  1. import random   
[python] view plain copy
 print?
  1. <span style="font-family:microsoft yahei;">######自己写一个随机分配数的函数,分成两份,并将数值一次存储在对应的list中##########  
  2. def train_test_split(ylabel, random_state=1):  
  3.     import random   
  4.     index=random.sample(range(len(ylabel)),50*random_state)  
  5.     list_train=[]  
  6.     list_test=[]  
  7.     i=0  
  8.     for s in range(len(ylabel)):  
  9.         if i in index:  
  10.             list_test.append(i)  
  11.         else:  
  12.             list_train.append(i)  
  13.         i+=1  
  14.     return list_train,list_test  
  15.  ###############对特征进行分割#############################  
  16. feature_cols = ['TV''Radio','Newspaper']  
  17. X1 = data[feature_cols]  
  18. y1 = data.Sales  
  19. list_train,list_test=train_test_split(y1)#random_state的默认值是1  
  20.   
  21. X1_train=X1.ix[list_train] #这里使用来DataFrame的ix()函数,可以将指定list中的索引的记录全部放在一起  
  22. X1_test=X1.ix[list_test]  
  23. y1_train=y1.ix[list_train]  
  24. y1_test=y1.ix[list_test]  
  25. #######################开始进行模型的训练########################################  
  26. linreg.fit(X1_train, y1_train)</span>  
[python] view plain copy
 print?
  1. <span style="font-family:microsoft yahei;">######################预测#############</span>  
[python] view plain copy
 print?
  1. <span style="font-family:microsoft yahei;">y1_pred = linreg.predict(X1_test)  
  2. print model  
  3. print linreg.intercept_  
  4. print linreg.coef_  
  5. #################评价测度##############</span>  
[python] view plain copy
 print?
  1. <span style="font-family:microsoft yahei;">sum_mean1=0  
  2. for i in range(len(y1_pred)):  
  3.     sum_mean1+=(y1_pred[i]-y1_test.values[i])**2  
  4. sum_erro1=np.sqrt(sum_mean1/50)  
  5. # calculate RMSE by hand  
  6. print "RMSE by hand:",sum_erro1</span>  
运算结果如下:

LinearRegression(copy_X=True, fit_intercept=True, normalize=False)3.1066750253[ 0.04588016  0.18078772 -0.00187699]RMSE by hand: 1.39068687332
0 0