来自 http://blog.csdn.net/jasonding1354/article/details/46340729

内容概要

  • 如何使用pandas读入数据
  • 如何使用seaborn进行数据的可视化
  • scikit-learn的线性回归模型和使用方法
  • 线性回归模型的评估测度
  • 特征选择的方法
 

作为有监督学习,分类问题是预测类别结果,而回归问题是预测一个连续的结果。

 

1. 使用pandas来读取数据

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

In [1]:
import pandas as pd
In [2]:
# read csv file directly from a URL and save the results
data = pd.read_csv('http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv', index_col=0) # display the first 5 rows
data.head()
Out[2]:
  TV Radio Newspaper Sales
1 230.1 37.8 69.2 22.1
2 44.5 39.3 45.1 10.4
3 17.2 45.9 69.3 9.3
4 151.5 41.3 58.5 18.5
5 180.8 10.8 58.4 12.9
 

上面显示的结果类似一个电子表格,这个结构称为Pandas的数据帧(data frame)。

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

  • Series类似于一维数组,它有一组数据以及一组与之相关的数据标签(即索引)组成。
  • DataFrame是一个表格型的数据结构,它含有一组有序的列,每列可以是不同的值类型。DataFrame既有行索引也有列索引,它可以被看做由Series组成的字典。
In [3]:
# display the last 5 rows
data.tail()
Out[3]:
  TV Radio Newspaper Sales
196 38.2 3.7 13.8 7.6
197 94.2 4.9 8.1 9.7
198 177.0 9.3 6.4 12.8
199 283.6 42.0 66.2 25.5
200 232.1 8.6 8.7 13.4
In [4]:
# check the shape of the DataFrame(rows, colums)
data.shape
Out[4]:
(200, 4)
 

特征:

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

响应:

  • Sales:对应产品的销量

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

In [5]:
import seaborn as sns

%matplotlib inline
In [6]:
# visualize the relationship between the features and the response using scatterplots
sns.pairplot(data, x_vars=['TV','Radio','Newspaper'], y_vars='Sales', size=7, aspect=0.8)
Out[6]:
<seaborn.axisgrid.PairGrid at 0x82dd890>
 
 

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

In [7]:
sns.pairplot(data, x_vars=['TV','Radio','Newspaper'], y_vars='Sales', size=7, aspect=0.8, kind='reg')
Out[7]:
<seaborn.axisgrid.PairGrid at 0x83b76f0>
 
 

2. 线性回归模型

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

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

 

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

  • y是响应
  • β0是截距
  • β1是x1的系数,以此类推

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

 

(1)使用pandas来构建X和y

  • scikit-learn要求X是一个特征矩阵,y是一个NumPy向量
  • pandas构建在NumPy之上
  • 因此,X可以是pandas的DataFrame,y可以是pandas的Series,scikit-learn可以理解这种结构
In [8]:
# create a python list of feature names
feature_cols = ['TV', 'Radio', 'Newspaper'] # use the list to select a subset of the original DataFrame
X = data[feature_cols] # equivalent command to do this in one line
X = data[['TV', 'Radio', 'Newspaper']] # print the first 5 rows
X.head()
Out[8]:
  TV Radio Newspaper
1 230.1 37.8 69.2
2 44.5 39.3 45.1
3 17.2 45.9 69.3
4 151.5 41.3 58.5
5 180.8 10.8 58.4
In [9]:
# check the type and shape of X
print type(X)
print X.shape
 
<class 'pandas.core.frame.DataFrame'>
(200, 3)
In [10]:
# select a Series from the DataFrame
y = data['Sales'] # equivalent command that works if there are no spaces in the column name
y = data.Sales # print the first 5 values
y.head()
Out[10]:
1    22.1
2 10.4
3 9.3
4 18.5
5 12.9
Name: Sales, dtype: float64
In [11]:
print type(y)
print y.shape
 
<class 'pandas.core.series.Series'>
(200,)
 

(2)构造训练集和测试集

In [12]:
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)
In [14]:
# default split is 75% for training and 25% for testing
print X_train.shape
print y_train.shape
print X_test.shape
print y_test.shape
 
(150, 3)
(150,)
(50, 3)
(50,)
 

(3)Scikit-learn的线性回归

In [15]:
from sklearn.linear_model import LinearRegression

linreg = LinearRegression()

linreg.fit(X_train, y_train)
Out[15]:
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)
In [16]:
print linreg.intercept_
print linreg.coef_
 
2.87696662232
[ 0.04656457 0.17915812 0.00345046]
In [17]:
# pair the feature names with the coefficients
zip(feature_cols, linreg.coef_)
Out[17]:
[('TV', 0.046564567874150253),
('Radio', 0.17915812245088836),
('Newspaper', 0.0034504647111804482)]
 

y=2.88+0.0466∗TV+0.179∗Radio+0.00345∗Newspaper

 

如何解释各个特征对应的系数的意义?

  • 对于给定了Radio和Newspaper的广告投入,如果在TV广告上每多投入1个单位,对应销量将增加0.0466个单位
  • 更明确一点,加入其它两个媒体投入固定,在TV广告上没增加1000美元(因为单位是1000美元),销量将增加46.6(因为单位是1000)
 

(4)预测

In [18]:
y_pred = linreg.predict(X_test)
 

3. 回归问题的评价测度

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

 

下面介绍三种常用的针对回归问题的评价测度

In [21]:
# define true and predicted response values
true = [100, 50, 30, 20]
pred = [90, 50, 50, 30]
 

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

1n∑ni=1|yi−yi^|

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

1n∑ni=1(yi−yi^)2

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

1n∑ni=1(yi−yi^)2−−−−−−−−−−−−−√

In [24]:
from sklearn import metrics
import numpy as np
# calculate MAE by hand
print "MAE by hand:",(10 + 0 + 20 + 10)/4. # calculate MAE using scikit-learn
print "MAE:",metrics.mean_absolute_error(true, pred) # calculate MSE by hand
print "MSE by hand:",(10**2 + 0**2 + 20**2 + 10**2)/4. # calculate MSE using scikit-learn
print "MSE:",metrics.mean_squared_error(true, pred) # calculate RMSE by hand
print "RMSE by hand:",np.sqrt((10**2 + 0**2 + 20**2 + 10**2)/4.) # calculate RMSE using scikit-learn
print "RMSE:",np.sqrt(metrics.mean_squared_error(true, pred))
 
MAE by hand: 10.0
MAE: 10.0
MSE by hand: 150.0
MSE: 150.0
RMSE by hand: 12.2474487139
RMSE: 12.2474487139
 

计算Sales预测的RMSE

In [26]:
print np.sqrt(metrics.mean_squared_error(y_test, y_pred))
 
1.40465142303
 

4. 特征选择

在之前展示的数据中,我们看到Newspaper和销量之间的线性关系比较弱,现在我们移除这个特征,看看线性回归预测的结果的RMSE如何?

In [27]:
feature_cols = ['TV', 'Radio']

X = data[feature_cols]
y = data.Sales X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1) linreg.fit(X_train, y_train) y_pred = linreg.predict(X_test) print np.sqrt(metrics.mean_squared_error(y_test, y_pred))
 
1.38790346994
 

我们将Newspaper这个特征移除之后,得到RMSE变小了,说明Newspaper特征不适合作为预测销量的特征,于是,我们得到了新的模型。我们还可以通过不同的特征组合得到新的模型,看看最终的误差是如何的。

转载请注明:人人都是数据咖 » scikit-learn的线性回归模型

scikit-learn的线性回归模型的更多相关文章

  1. (原创)(三)机器学习笔记之Scikit Learn的线性回归模型初探

    一.Scikit Learn中使用estimator三部曲 1. 构造estimator 2. 训练模型:fit 3. 利用模型进行预测:predict 二.模型评价 模型训练好后,度量模型拟合效果的 ...

  2. 使用SKlearn(Sci-Kit Learn)进行SVR模型学习

    今天了解到sklearn这个库,简直太酷炫,一行代码完成机器学习. 贴一个自动生成数据,SVR进行数据拟合的代码,附带网格搜索(GridSearch, 帮助你选择合适的参数)以及模型保存.读取以及结果 ...

  3. Scikit Learn: 在python中机器学习

    转自:http://my.oschina.net/u/175377/blog/84420#OSC_h2_23 Scikit Learn: 在python中机器学习 Warning 警告:有些没能理解的 ...

  4. scikit learn 模块 调参 pipeline+girdsearch 数据举例:文档分类 (python代码)

    scikit learn 模块 调参 pipeline+girdsearch 数据举例:文档分类数据集 fetch_20newsgroups #-*- coding: UTF-8 -*- import ...

  5. (原创)(四)机器学习笔记之Scikit Learn的Logistic回归初探

    目录 5.3 使用LogisticRegressionCV进行正则化的 Logistic Regression 参数调优 一.Scikit Learn中有关logistics回归函数的介绍 1. 交叉 ...

  6. 【scikit-learn】scikit-learn的线性回归模型

     内容概要 怎样使用pandas读入数据 怎样使用seaborn进行数据的可视化 scikit-learn的线性回归模型和用法 线性回归模型的评估測度 特征选择的方法 作为有监督学习,分类问题是预 ...

  7. R语言解读多元线性回归模型

    转载:http://blog.fens.me/r-multi-linear-regression/ 前言 本文接上一篇R语言解读一元线性回归模型.在许多生活和工作的实际问题中,影响因变量的因素可能不止 ...

  8. R语言解读一元线性回归模型

    转载自:http://blog.fens.me/r-linear-regression/ 前言 在我们的日常生活中,存在大量的具有相关性的事件,比如大气压和海拔高度,海拔越高大气压强越小:人的身高和体 ...

  9. 多元线性回归 ——模型、估计、检验与预测

    一.模型假设 传统多元线性回归模型 最重要的假设的原理为: 1. 自变量和因变量之间存在多元线性关系,因变量y能够被x1,x2-.x{k}完全地线性解释:2.不能被解释的部分则为纯粹的无法观测到的误差 ...

  10. 一元线性回归模型与最小二乘法及其C++实现

    原文:http://blog.csdn.net/qll125596718/article/details/8248249 监督学习中,如果预测的变量是离散的,我们称其为分类(如决策树,支持向量机等), ...

随机推荐

  1. Android NDK编译之undefined reference to 'JNI_CreateJavaVM'

    利用Android NDK编译动态库,在C文件中调用了两个JNI函数:JNI_GetDefaultJavaVMInitArgs和JNI_CreateJavaVM.编译的时候始终报以下错误: XXX: ...

  2. JavaScript大杂烩4 - 理解JavaScript对象的继承机制

    JavaScript是单根的完全面向对象的语言 JavaScript是单根的面向对象语言,它只有单一的根Object,所有的其他对象都是直接或者间接的从Object对象继承.而在JavaScript的 ...

  3. MySQL——优化嵌套查询和分页查询

    优化嵌套查询 嵌套查询(子查询)可以使用SELECT语句来创建一个单列的查询结果,然后把这个结果作为过滤条件用在另一个查询中.嵌套查询写起来简单,也容易理解.但是,有时候可以被更有效率的连接(JOIN ...

  4. CentOS7安装搭建.Net Core 2.0环境-详细步骤

    一.构建.Net core 2的应用程web发布 因为是用来测试centos上的core 环境,先直接用vs17自带的core实例. 二.部署CentOS7的core环境 1.连接并启动之前安装的虚拟 ...

  5. 【PAT】1083 是否存在相等的差(20 分)

    //这题不是我耍流氓,实在太简单,只能直接贴代码了,凑个数 #include<stdio.h> int aaa[10005]={0}; int main(){ int N;scanf(&q ...

  6. .NET 序列化成XML, 并且格式化

    现有Person类: [Serializable] public class Person { public string Name; public string Info; public Perso ...

  7. MATLAB矩阵的LU分解及在解线性方程组中的应用

    作者:凯鲁嘎吉 - 博客园http://www.cnblogs.com/kailugaji/ 三.实验程序 五.解答(按如下顺序提交电子版) 1.(程序) (1)LU分解源程序: function [ ...

  8. JavaScipt中的Math.ceil() 、Math.floor() 、Math.round()、Math.pow() 三个函数的理解

    以前一直会三个函数的使用产生混淆,现在通过对三个函数的原型定义的理解,其实很容易记住三个函数. 现在做一个总结: 1. Math.ceil()用作向上取整. 2. Math.floor()用作向下取整 ...

  9. Android Activity学习笔记——Activity的启动和创建

    http://www.cnblogs.com/bastard/archive/2012/04/07/2436262.html 最近学习Android相关知识,感觉仅仅了解Activity几个生命周期函 ...

  10. centos7下安装docker(12.1bridge网络)

    容器默认使用的时bridge网络 docker安装时会创建一个 命令为docker0的linux bridge.如果不指定--network=,运行的容器会默认挂到docker0上 interface ...