Python 一元线性回归及画图代码示例
以下是 Python 中使用 sklearn 库进行一元线性回归和画图的代码示例:
# 导入必要的库
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
# 创建数据集
x = np.array([1, 2, 3, 4, 5])
y = np.array([3, 5, 7, 9, 11])
# 一元线性回归
model = LinearRegression()
x_reshape = x.reshape(-1, 1)
model.fit(x_reshape, y)
# 计算斜率和截距
slope = model.coef_[0]
intercept = model.intercept_
# 绘制数据点和回归直线
plt.scatter(x, y)
plt.plot(x, slope*x+intercept, color='red')
plt.show()
输出结果为一张散点图和回归直线,如下图所示:

代码解释:
- 导入必要的库: 导入 numpy 用于数值计算,matplotlib.pyplot 用于画图,sklearn.linear_model 用于线性回归模型。
- 创建数据集: 创建两个 numpy 数组 x 和 y,分别代表自变量和因变量。
- 一元线性回归: 创建一个 LinearRegression 对象,使用 fit() 方法拟合数据集,将 x 转换为二维数组。
- 计算斜率和截距: 使用 coef_ 属性获取斜率,使用 intercept_ 属性获取截距。
- 绘制数据点和回归直线: 使用 scatter() 方法绘制数据点,使用 plot() 方法绘制回归直线。
代码示例展示了如何使用 Python 的 sklearn 库进行一元线性回归和画图,并提供详细的代码解释,方便读者理解和应用。
原文地址: https://www.cveoy.top/t/topic/mYEc 著作权归作者所有。请勿转载和采集!