sklearn+python:线性回归案例


Posted in Python onFebruary 24, 2020

使用一阶线性方程预测波士顿房价

载入的数据是随sklearn一起发布的,来自boston 1993年之前收集的506个房屋的数据和价格。load_boston()用于载入数据。

from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
import time
from sklearn.linear_model import LinearRegression


boston = load_boston()

X = boston.data
y = boston.target

print("X.shape:{}. y.shape:{}".format(X.shape, y.shape))
print('boston.feature_name:{}'.format(boston.feature_names))

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=3)

model = LinearRegression()

start = time.clock()
model.fit(X_train, y_train)

train_score = model.score(X_train, y_train)
cv_score = model.score(X_test, y_test)

print('time used:{0:.6f}; train_score:{1:.6f}, sv_score:{2:.6f}'.format((time.clock()-start),
                                    train_score, cv_score))

输出内容为:

X.shape:(506, 13). y.shape:(506,)
boston.feature_name:['CRIM' 'ZN' 'INDUS' 'CHAS' 'NOX' 'RM' 'AGE' 'DIS' 'RAD' 'TAX' 'PTRATIO'
 'B' 'LSTAT']
time used:0.012403; train_score:0.723941, sv_score:0.794958

可以看到测试集上准确率并不高,应该是欠拟合。

使用多项式做线性回归

上面的例子是欠拟合的,说明模型太简单,无法拟合数据的情况。现在增加模型复杂度,引入多项式。

打个比方,如果原来的特征是[a, b]两个特征,

在degree为2的情况下, 多项式特征变为[1, a, b, a^2, ab, b^2]。degree为其它值的情况依次类推。

多项式特征相当于增加了数据和模型的复杂性,能够更好的拟合。

下面的代码使用Pipeline把多项式特征和线性回归特征连起来,最终测试degree在1、2、3的情况下的得分。

from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
import time
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import Pipeline

def polynomial_model(degree=1):
  polynomial_features = PolynomialFeatures(degree=degree, include_bias=False)

  linear_regression = LinearRegression(normalize=True)
  pipeline = Pipeline([('polynomial_features', polynomial_features),
             ('linear_regression', linear_regression)])
  return pipeline

boston = load_boston()
X = boston.data
y = boston.target
print("X.shape:{}. y.shape:{}".format(X.shape, y.shape))
print('boston.feature_name:{}'.format(boston.feature_names))

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=3)

for i in range(1,4):
  print( 'degree:{}'.format( i ) )
  model = polynomial_model(degree=i)

  start = time.clock()
  model.fit(X_train, y_train)

  train_score = model.score(X_train, y_train)
  cv_score = model.score(X_test, y_test)

  print('time used:{0:.6f}; train_score:{1:.6f}, sv_score:{2:.6f}'.format((time.clock()-start),
                                    train_score, cv_score))

输出结果为:

X.shape:(506, 13). y.shape:(506,)
boston.feature_name:['CRIM' 'ZN' 'INDUS' 'CHAS' 'NOX' 'RM' 'AGE' 'DIS' 'RAD' 'TAX' 'PTRATIO'
 'B' 'LSTAT']
degree:1
time used:0.003576; train_score:0.723941, sv_score:0.794958
degree:2
time used:0.030123; train_score:0.930547, sv_score:0.860465
degree:3
time used:0.137346; train_score:1.000000, sv_score:-104.429619

可以看到degree为1和上面不使用多项式是一样的。degree为3在训练集上的得分为1,在测试集上得分是负数,明显过拟合了。

所以最终应该选择degree为2的模型。

二阶多项式比一阶多项式好的多,但是测试集和训练集上的得分仍有不少差距,这可能是数据不够的原因,需要更多的讯据才能进一步提高模型的准确度。

正规方程解法和梯度下降的比较

除了梯度下降法来逼近最优解,也可以使用正规的方程解法直接计算出最终的解来。

根据吴恩达的课程,线性回归最优解为:

theta = (X^T * X)^-1 * X^T * y

其实两种方法各有优缺点:

梯度下降法:

缺点:需要选择学习率,需要多次迭代

优点:特征值很多(1万以上)时仍然能以不错的速度工作

正规方程解法:

优点:不需要设置学习率,不需要多次迭代

缺点:需要计算X的转置和逆,复杂度O3;特征值很多(1万以上)时特变慢

在分类等非线性计算中,正规方程解法并不适用,所以梯度下降法适用范围更广。

以上这篇sklearn+python:线性回归案例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
简单的通用表达式求10乘阶示例
Mar 03 Python
列举Python中吸引人的一些特性
Apr 09 Python
Python中struct模块对字节流/二进制流的操作教程
Jan 21 Python
Python实现树莓派WiFi断线自动重连的实例代码
Mar 16 Python
Python编程之变量赋值操作实例分析
Jul 24 Python
python使用Apriori算法进行关联性解析
Dec 21 Python
python使用turtle绘制国际象棋棋盘
May 23 Python
python程序快速缩进多行代码方法总结
Jun 23 Python
python代码实现逻辑回归logistic原理
Aug 07 Python
关于Python形参打包与解包小技巧分享
Aug 24 Python
Python中常用的高阶函数实例详解
Feb 21 Python
PyTorch如何搭建一个简单的网络
Aug 24 Python
深入理解Tensorflow中的masking和padding
Feb 24 #Python
K最近邻算法(KNN)---sklearn+python实现方式
Feb 24 #Python
Python3.6 + TensorFlow 安装配置图文教程(Windows 64 bit)
Feb 24 #Python
Python enumerate内置库用法解析
Feb 24 #Python
Python模块/包/库安装的六种方法及区别
Feb 24 #Python
python之MSE、MAE、RMSE的使用
Feb 24 #Python
Python接口自动化判断元素原理解析
Feb 24 #Python
You might like
php框架Phpbean说明
2008/01/10 PHP
了解PHP的返回引用和局部静态变量
2015/06/04 PHP
PHP Cookei记录用户历史浏览信息的代码
2016/02/03 PHP
Yii实现Command任务处理的方法详解
2016/07/14 PHP
PHP与SQL语句常用大全
2016/12/10 PHP
PHP符合PSR编程规范的实例分享
2016/12/21 PHP
tp5(thinkPHP5)框架实现多数据库查询的方法
2019/01/10 PHP
使用jQuery设置disabled属性与移除disabled属性
2014/08/21 Javascript
javascript字符串替换函数如何一次性全部替换掉
2015/10/30 Javascript
jquery UI Datepicker时间控件的使用方法(终结版)
2015/11/07 Javascript
Js类的静态方法与实例方法区分及jQuery拓展的两种方法
2016/06/03 Javascript
vue 项目常用加载器及配置详解
2018/01/22 Javascript
javaScript中"=="和"==="的区别详解
2018/03/16 Javascript
express如何解决ajax跨域访问session失效问题详解
2019/06/20 Javascript
vue实现tab栏点击高亮效果
2020/08/19 Javascript
Linux下使用python调用top命令获得CPU利用率
2015/03/10 Python
详解Python3中的Sequence type的使用
2015/08/01 Python
深入理解python对json的操作总结
2017/01/05 Python
Python实现的求解最大公约数算法示例
2018/05/03 Python
解决使用PyCharm时无法启动控制台的问题
2019/01/19 Python
面向对象学习之pygame坦克大战
2019/09/11 Python
Python 实现自动导入缺失的库
2019/10/29 Python
Python版中国省市经纬度
2020/02/11 Python
Python连接Mysql进行增删改查的示例代码
2020/08/03 Python
诺心蛋糕官网:LE CAKE
2018/08/25 全球购物
戴尔新西兰官网:Dell New Zealand
2020/01/07 全球购物
Shopping happy life西班牙:以最优惠的价格提供最好的时尚配饰
2020/03/13 全球购物
介绍Java的内部类
2012/10/27 面试题
linux面试题参考答案(7)
2014/07/24 面试题
兰兰过桥教学反思
2014/02/08 职场文书
春季运动会广播稿大全
2014/02/19 职场文书
珠宝店促销方案
2014/03/21 职场文书
公司酒会主持词
2015/07/02 职场文书
Python爬虫入门案例之回车桌面壁纸网美女图片采集
2021/10/16 Python
MySQL七大JOIN的具体使用
2022/02/28 MySQL
DQL数据查询语句使用示例
2022/12/24 MySQL