如何在python中实现线性回归

作者:刘早起 时间:2022-03-29 00:24:30 

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

本文主要介绍如何逐步在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]

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

来源:https://cloud.tencent.com/developer/article/1618713

标签:Python,线性回归
0
投稿

猜你喜欢

  • css元素层叠级别及z-index剖析

    2008-08-29 12:41:00
  • Python中关于使用模块的基础知识

    2022-11-10 04:11:21
  • python如何查看系统网络流量的信息

    2022-11-03 13:54:08
  • Python 代码性能优化技巧分享

    2023-10-15 05:00:56
  • CSS双线边框研究

    2009-09-03 12:12:00
  • python实现求最长回文子串长度

    2022-09-29 13:56:32
  • oracle sys_connect_by_path 函数 结果集连接

    2009-07-12 18:48:00
  • go中的unsafe包及使用详解

    2023-10-13 17:07:27
  • PyQt5 closeEvent关闭事件退出提示框原理解析

    2022-10-18 05:51:17
  • 有趣的python小程序分享

    2023-11-27 20:31:55
  • JsonServer安装及启动过程图解

    2023-08-12 20:06:02
  • Python实现的将文件每一列写入列表功能示例【测试可用】

    2022-12-05 15:12:31
  • Python实现批量word文档转pdf并统计其页码

    2023-08-19 13:29:40
  • 用Css来制作一个漂亮的多选列表框

    2008-05-29 12:45:00
  • python将txt文件读入为np.array的方法

    2023-07-23 08:10:29
  • 深入讲解Go语言中函数new与make的使用和区别

    2023-06-16 17:52:29
  • PyTorch 如何将CIFAR100数据按类标归类保存

    2023-01-10 06:01:03
  • 在Django的URLconf中进行函数导入的方法

    2023-07-10 10:46:26
  • python中subplot大小的设置步骤

    2021-07-30 08:59:37
  • Javascript typeof 用法

    2013-10-20 20:49:40
  • asp之家 网络编程 m.aspxhome.com