如何在python中实现线性回归


Posted in Python onAugust 10, 2020

线性回归是基本的统计和机器学习技术之一。经济,计算机科学,社会科学等等学科中,无论是统计分析,或者是机器学习,还是科学计算,都有很大的机会需要用到线性模型。建议先学习它,然后再尝试更复杂的方法。

本文主要介绍如何逐步在Python中实现线性回归。而至于线性回归的数学推导、线性回归具体怎样工作,参数选择如何改进回归模型将在以后说明。

回归

回归分析是统计和机器学习中最重要的领域之一。有许多可用的回归方法。线性回归就是其中之一。而线性回归可能是最重要且使用最广泛的回归技术之一。这是最简单的回归方法之一。它的主要优点之一是线性回归得到的结果十分容易解释。那么回归主要有:

  • 简单线性回归
  • 多元线性回归
  • 多项式回归

如何在python中实现线性回归

用到的packages

  • NumPy

NumPy是Python的基础科学软件包,它允许在单维和多维数组上执行许多高性能操作。

  • scikit-learn

scikit-learn是在NumPy和其他一些软件包的基础上广泛使用的Python机器学习库。它提供了预处理数据,减少维数,实现回归,分类,聚类等的方法。

  • statsmodels

如果要实现线性回归并且需要功能超出scikit-learn的范围,则应考虑使用statsmodels可以用于估算统计模型,执行测试等。

scikit-learn的简单线性回归

1.导入用到的packages和类

import numpy as np
from sklearn.linear_model import LinearRegression

2.创建数据

x = np.array([5, 15, 25, 35, 45, 55]).reshape((-1, 1))
y = np.array([5, 20, 14, 32, 22, 38])

现在就生成了两个数组:输入x(回归变量)和输出y(预测变量),来看看

>>> print(x)
[[ 5]
 [15]
 [25]
 [35]
 [45]
 [55]]
>>> print(y)
[ 5 20 14 32 22 38]

可以看到x是二维的而y是一维的,因为在复杂一点的模型中,系数不只一个。这里就用到了.reshape()来进行转换。

3.建立模型

创建一个类的实例LinearRegression,它将代表回归模型:

model = LinearRegression()

现在开始拟合模型,首先可以调用.fit()函数来得到优的?₀和?₁,具体有下面两种等价方法

model.fit(x, y)
model = LinearRegression().fit(x, y)

4.查看结果

拟合模型之后就是查看与模型相关的各项参数

>>> r_sq = model.score(x, y)
>>> print('coefficient of determination:', r_sq)
coefficient of determination: 0.715875613747954

.score()函数可以获得模型的?²,再看看系数

>>> print('intercept:', model.intercept_)
intercept: 5.633333333333329
>>> print('slope:', model.coef_)
slope: [0.54]

可以看到系数和截距分别为[0.54]和5.6333,注意系数是一个二维数组哦。

5.预测效果

一般而言,线性模型最后就是用来预测,我们来看下预测效果

>>> y_pred = model.predict(x)
>>> print('predicted response:', y_pred, sep='\n')
predicted response:
[ 8.33333333 13.73333333 19.13333333 24.53333333 29.93333333 35.33333333]

当然也可以使用下面的方法

>>> y_pred = model.intercept_ + model.coef_ * x
>>> print('predicted response:', y_pred, sep='\n')
predicted response:
[[ 8.33333333]
 [13.73333333]
 [19.13333333]
 [24.53333333]
 [29.93333333]
 [35.33333333]]

除了可以利用样本内的数据进行预测,也可以用样本外的数据进行预测。

>>> x_new = np.arange(5).reshape((-1, 1))
>>> print(x_new)
[[0]
 [1]
 [2]
 [3]
 [4]]
>>> y_new = model.predict(x_new)
>>> print(y_new)
[5.63333333 6.17333333 6.71333333 7.25333333 7.79333333]

至此,一个简单的线性回归模型就建立起来了。

scikit-learn的多元线性回归

直接开始吧

1.导入包和类,并创建数据

import numpy as np
from sklearn.linear_model import LinearRegression

x = [[0, 1], [5, 1], [15, 2], [25, 5], [35, 11], [45, 15], [55, 34], [60, 35]]
y = [4, 5, 20, 14, 32, 22, 38, 43]
x, y = np.array(x), np.array(y)

看看数据

>>> print(x)
[[ 0 1]
 [ 5 1]
 [15 2]
 [25 5]
 [35 11]
 [45 15]
 [55 34]
 [60 35]]
>>> print(y)
[ 4 5 20 14 32 22 38 43]

2.建立多元回归模型

model = LinearRegression().fit(x, y)

3.查看结果

>>> r_sq = model.score(x, y)
>>> print('coefficient of determination:', r_sq)
coefficient of determination: 0.8615939258756776
>>> print('intercept:', model.intercept_)
intercept: 5.52257927519819
>>> print('slope:', model.coef_)
slope: [0.44706965 0.25502548]

4.预测

#样本内
>>> y_pred = model.predict(x)
>>> print('predicted response:', y_pred, sep='\n')
predicted response:
[ 5.77760476 8.012953  12.73867497 17.9744479 23.97529728 29.4660957
 38.78227633 41.27265006]
#样本外
>>> x_new = np.arange(10).reshape((-1, 2))
>>> print(x_new)
[[0 1]
 [2 3]
 [4 5]
 [6 7]
 [8 9]]
>>> y_new = model.predict(x_new)
>>> print(y_new)
[ 5.77760476 7.18179502 8.58598528 9.99017554 11.3943658 ]

所有的结果都在结果里,就不再过多解释。再看看多项式回归如何实现。

多项式回归

导入包和创建数据

import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
x = np.array([5, 15, 25, 35, 45, 55]).reshape((-1, 1))
y = np.array([15, 11, 2, 8, 25, 32])

多项式回归和之前不一样的是需要对数据转换,因为模型里包含?²等变量,所以在创建数据之后要将x转换为?²。

transformer = PolynomialFeatures(degree=2, include_bias=False)

再看看数据

>>> print(x_)
[[  5.  25.]
 [ 15. 225.]
 [ 25. 625.]
 [ 35. 1225.]
 [ 45. 2025.]
 [ 55. 3025.]]

建模

接下来的步骤就和之前的类似了。其实多项式回归只是多了个数据转换的步骤,因此从某种意义上,多项式回归也算是线性回归。

model = LinearRegression().fit(x_, y)

查看结果

>>> r_sq = model.score(x_, y)
>>> print('coefficient of determination:', r_sq)
coefficient of determination: 0.8908516262498564
>>> print('intercept:', model.intercept_)
intercept: 21.372321428571425
>>> print('coefficients:', model.coef_)
coefficients: [-1.32357143 0.02839286]

预测

>>> y_pred = model.predict(x_)
>>> print('predicted response:', y_pred, sep='\n')
predicted response:
[15.46428571 7.90714286 6.02857143 9.82857143 19.30714286 34.46428571]

那么本次多项式回归的所有结果都在上面了,一目了然。

以上就是如何在python中实现线性回归的详细内容,更多关于Python实现线性回归的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
python备份文件的脚本
Aug 11 Python
python实现划词翻译
Apr 23 Python
python与C互相调用的方法详解
Jul 14 Python
python利用正则表达式搜索单词示例代码
Sep 24 Python
python实现图像识别功能
Jan 29 Python
Python Requests模拟登录实现图书馆座位自动预约
Apr 27 Python
python DataFrame 取差集实例
Jan 30 Python
Python3中的bytes和str类型详解
May 02 Python
浅谈Python中(&,|)和(and,or)之间的区别
Aug 07 Python
python 定义类时,实现内部方法的互相调用
Dec 25 Python
Python计算信息熵实例
Jun 18 Python
Keras loss函数剖析
Jul 06 Python
Python多线程的退出控制实现
Aug 10 #Python
Python进行统计建模
Aug 10 #Python
Python如何爬取b站热门视频并导入Excel
Aug 10 #Python
拿来就用!Python批量合并PDF的示例代码
Aug 10 #Python
Python 发送邮件方法总结
Aug 10 #Python
Python getattr()函数使用方法代码实例
Aug 10 #Python
Python matplotlib模块及柱状图用法解析
Aug 10 #Python
You might like
基于mysql的论坛(4)
2006/10/09 PHP
PHP在特殊字符前加斜杠的实现代码
2011/07/17 PHP
Yii2主题(Theme)用法详解
2016/07/23 PHP
php 判断页面或图片是否经过gzip压缩的方法
2017/04/05 PHP
使用js获取地址栏中传递的值
2013/07/02 Javascript
FF(火狐)浏览器无法执行window.close()解决方案
2014/11/13 Javascript
Angularjs中使用Filters详解
2016/03/11 Javascript
javascript基本语法
2016/05/31 Javascript
JQuery遍历元素的父辈和祖先的方法
2016/09/18 Javascript
js实现百度地图定位于地址逆解析,显示自己当前的地理位置
2016/12/08 Javascript
layer弹窗插件操作方法详解
2017/05/19 Javascript
BootStrap Table 后台数据绑定、特殊列处理、排序功能
2017/05/27 Javascript
微信小程序开发之animation循环动画实现的让云朵飘效果
2017/07/14 Javascript
React Native仿美团下拉菜单的实例代码
2017/08/08 Javascript
nodejs结合Socket.IO实现的即时通讯功能详解
2018/01/12 NodeJs
微信小程序实现卡片层叠滑动效果
2019/06/21 Javascript
jquery实现点击弹出对话框
2020/02/08 jQuery
使用python检测主机存活端口及检查存活主机
2015/10/12 Python
简析Python的闭包和装饰器
2016/02/26 Python
使用python遍历指定城市的一周气温
2017/03/31 Python
如何在django里上传csv文件并进行入库处理的方法
2019/01/02 Python
python3实现斐波那契数列(4种方法)
2019/07/15 Python
关于pytorch中网络loss传播和参数更新的理解
2019/08/20 Python
Python高级特性——详解多维数组切片(Slice)
2019/11/26 Python
Python reshape的用法及多个二维数组合并为三维数组的实例
2020/02/07 Python
浅析Python迭代器的高级用法
2020/07/16 Python
美国知名眼镜网站:Target Optical
2020/04/04 全球购物
传播学专业毕业生自荐书
2014/07/01 职场文书
抄袭同学作业检讨书1000字
2014/11/20 职场文书
奖学金感谢信
2015/01/21 职场文书
环卫工作个人总结
2015/03/04 职场文书
酒会开场白大全
2015/06/01 职场文书
清明扫墓感想
2015/08/11 职场文书
大学三好学生主要事迹范文
2015/11/03 职场文书
新手必备Python开发环境搭建教程
2021/05/28 Python
动画电影《擅长捉弄人的高木同学》6月10日上映!
2022/03/20 日漫