Python实现线性回归:从简单到多项式的完整指南
本文详细讲解如何在Python中使用Scikit-learn实现线性回归。内容涵盖简单线性回归、多元线性回归及多项式回归的具体代码实现,包括数据预处理、模型拟合、参数查看及预测步骤,帮助开发者快速掌握线性模型的核心应用。
线性回归概述
线性回归是统计学与机器学习领域的基础技术之一。在经济学、计算机科学和社会科学等多个学科中,无论是进行统计分析、机器学习建模还是科学计算,线性模型的应用场景极为广泛。建议初学者先掌握这一基础方法,再逐步尝试更复杂的算法。
本文旨在逐步演示如何在Python环境中实现线性回归。关于线性回归背后的数学推导、具体运作机制以及如何通过参数优化来提升模型表现,将在后续内容中另行阐述。
回归
回归分析是统计与机器学习中至关重要的领域,存在多种可用的回归方法,线性回归便是其中之一。作为最简单且应用最广泛的回归技术之一,线性回归的主要优势在于其结果易于解释。常见的回归类型主要包括:
- 简单线性回归
- 多元线性回归
- 多项式回归
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实现线性回归的资料请关注本站其它相关文章!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









