【scikit-learn】scikit-learn的线性回归模型
内容概要
- 怎样使用pandas读入数据
- 怎样使用seaborn进行数据的可视化
- scikit-learn的线性回归模型和用法
- 线性回归模型的评估測度
- 特征选择的方法
作为有监督学习,分类问题是预測类别结果,而回归问题是预測一个连续的结果。
1. 使用pandas来读取数据
Pandas是一个用于数据探索、数据处理、数据分析的Python库
import pandas as pd
# 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()
| 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组成的字典。
# display the last 5 rows
data.tail()
| 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 |
# check the shape of the DataFrame(rows, colums)
data.shape
(200, 4)
特征:
- TV:对于一个给定市场中单一产品。用于电视上的广告费用(以千为单位)
- Radio:在广播媒体上投资的广告费用
- Newspaper:用于报纸媒体的广告费用
响应:
- Sales:相应产品的销量
在这个案例中。我们通过不同的广告投入,预測产品销量。由于响应变量是一个连续的值,所以这个问题是一个回归问题。数据集一共同拥有200个观測值,每一组观測相应一个市场的情况。
import seaborn as sns %matplotlib inline
# 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)
<seaborn.axisgrid.PairGrid at 0x82dd890>
seaborn的pairplot函数绘制X的每一维度和相应Y的散点图。通过设置size和aspect參数来调节显示的大小和比例。能够从图中看出,TV特征和销量是有比較强的线性关系的,而Radio和Sales线性关系弱一些。Newspaper和Sales线性关系更弱。通过加入一个參数kind='reg'。seaborn能够加入一条最佳拟合直线和95%的置信带。
sns.pairplot(data, x_vars=['TV','Radio','Newspaper'], y_vars='Sales', size=7, aspect=0.8, kind='reg')
<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能够理解这样的结构
# 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()
| 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 |
# check the type and shape of X
print type(X)
print X.shape
<class 'pandas.core.frame.DataFrame'>
(200, 3)
# 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()
1 22.1
2 10.4
3 9.3
4 18.5
5 12.9
Name: Sales, dtype: float64
print type(y)
print y.shape
<class 'pandas.core.series.Series'>
(200,)
(2)构造训练集和測试集
from sklearn.cross_validation import train_test_split
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
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的线性回归
from sklearn.linear_model import LinearRegression linreg = LinearRegression() linreg.fit(X_train, y_train)
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)
print linreg.intercept_
print linreg.coef_
2.87696662232
[ 0.04656457 0.17915812 0.00345046]
# pair the feature names with the coefficients
zip(feature_cols, linreg.coef_)
[('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)预測
y_pred = linreg.predict(X_test)
3. 回归问题的评价測度
对于分类问题,评价測度是准确率,但这样的方法不适用于回归问题。
我们使用针对连续数值的评价測度(evaluation metrics)。
以下介绍三种经常使用的针对回归问题的评价測度
# 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−−−−−−−−−−−−−√
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
print np.sqrt(metrics.mean_squared_error(y_test, y_pred))
1.40465142303
4. 特征选择
在之前展示的数据中,我们看到Newspaper和销量之间的线性关系比較弱,如今我们移除这个特征。看看线性回归预測的结果的RMSE怎样?
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的线性回归模型的更多相关文章
- (原创)(三)机器学习笔记之Scikit Learn的线性回归模型初探
一.Scikit Learn中使用estimator三部曲 1. 构造estimator 2. 训练模型:fit 3. 利用模型进行预测:predict 二.模型评价 模型训练好后,度量模型拟合效果的 ...
- R语言解读多元线性回归模型
转载:http://blog.fens.me/r-multi-linear-regression/ 前言 本文接上一篇R语言解读一元线性回归模型.在许多生活和工作的实际问题中,影响因变量的因素可能不止 ...
- R语言解读一元线性回归模型
转载自:http://blog.fens.me/r-linear-regression/ 前言 在我们的日常生活中,存在大量的具有相关性的事件,比如大气压和海拔高度,海拔越高大气压强越小:人的身高和体 ...
- 多元线性回归 ——模型、估计、检验与预测
一.模型假设 传统多元线性回归模型 最重要的假设的原理为: 1. 自变量和因变量之间存在多元线性关系,因变量y能够被x1,x2-.x{k}完全地线性解释:2.不能被解释的部分则为纯粹的无法观测到的误差 ...
- 一元线性回归模型与最小二乘法及其C++实现
原文:http://blog.csdn.net/qll125596718/article/details/8248249 监督学习中,如果预测的变量是离散的,我们称其为分类(如决策树,支持向量机等), ...
- R与数据分析旧笔记(⑨)广义线性回归模型
广义线性回归模型 广义线性回归模型 例题1 R.Norell实验 为研究高压电线对牲畜的影响,R.Norell研究小的电流对农场动物的影响.他在实验中,选择了7头,6种电击强度, 0,1,2,3,4, ...
- 多元线性回归模型的特征压缩:岭回归和Lasso回归
多元线性回归模型中,如果所有特征一起上,容易造成过拟合使测试数据误差方差过大:因此减少不必要的特征,简化模型是减小方差的一个重要步骤.除了直接对特征筛选,来也可以进行特征压缩,减少某些不重要的特征系数 ...
- TensorFlow从1到2(七)线性回归模型预测汽车油耗以及训练过程优化
线性回归模型 "回归"这个词,既是Regression算法的名称,也代表了不同的计算结果.当然结果也是由算法决定的. 不同于前面讲过的多个分类算法或者逻辑回归,线性回归模型的结果是 ...
- 机器学习---最小二乘线性回归模型的5个基本假设(Machine Learning Least Squares Linear Regression Assumptions)
在之前的文章<机器学习---线性回归(Machine Learning Linear Regression)>中说到,使用最小二乘回归模型需要满足一些假设条件.但是这些假设条件却往往是人们 ...
随机推荐
- jQuery的extend方法
jq中的extend在面试中经常会被问道,今天我总结一个下有关于extend的用法三种进行对比,可能不全,希望大家指点, 用法一: $.extend({}) ,为jQuery类添加方法,可以理解为扩 ...
- 1Z0-053 争议题目解析692
1Z0-053 争议题目解析692 考试科目:1Z0-053 题库版本:V13.02 题库中原题为: 692.Your company wants to upgrade the production ...
- [AngularJS] AngularJS系列(7) 进阶篇之promise
目录 使用promise 补充说明 $q.all $q.when 在上节中,我们在http中使用了then 和 在ngResource中返回了一个'延迟对象'. 本节介绍一下angular中的prom ...
- 《Head First 设计模式》之装饰者模式
作者:Grey 原文地址:http://www.cnblogs.com/greyzeng/p/5922248.html 模式名称 装饰者模式(Decorator Pattern) 需求 定义咖啡厅中的 ...
- javascript图片展示墙特效
查看效果:http://hovertree.com/code/javascript/pwl4bhoi.htm 代码如下: <!DOCTYPE html> <html> < ...
- css3全屏背景图片切换特效
效果体验:http://hovertree.com/texiao/css3/10/ 一般做图片切换效果,都会使用JS或者jQuery脚本,今天发现,其实只用CSS也可以实现.试试效果吧. 效果图: 代 ...
- 异步与并行~ReaderWriterLockSlim实现的共享锁和互斥锁
返回目录 在System.Threading.Tasks命名空间下,使用ReaderWriterLockSlim对象来实现多线程并发时的锁管理,它比lock来说,性能更好,也并合理,我们都知道lock ...
- 引用Microsoft.Office.Interop.Excel出现的问题
引用Microsoft.Office.Interop.Excel出现的问题 转自:http://www.hccar.com/Content,2008,6,11,75.aspx,作者:方继祥 操作背 ...
- 关于大数据企业信息查询的API该怎么写
最近在看API相关的案例,做的是.net开发的工作 对API开发这块很是迷茫,不知道从哪入手,园子里面的朋友有没有研究这块的给点建议 公司目前准备做一款企业数据查询的网站,让我负责API接口这块,基于 ...
- Xml的简单介绍和Xml格式
XML 被设计用来结构化.存储以及传输信息.HTML 被设计用来显示数据. 1.XML是什么? 1)XML 指可扩展标记语言(EXtensible Markup Language) 2)XML 是一种 ...