线性回归是机器学习中最基础且重要的算法之一。本文将介绍如何在 Python 中实现线性回归。

简介

线性回归用于预测一个连续变量的值。它通过找到最佳拟合线来预测目标变量。

准备工作

在开始之前,请确保您已经安装了以下 Python 库:

  • NumPy
  • Matplotlib
  • Scikit-learn

您可以通过以下命令安装这些库:

pip install numpy matplotlib scikit-learn

示例数据

为了演示,我们将使用以下示例数据:

x y
1 2
2 3
3 5
4 4
5 6

实现步骤

  1. 导入库
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
  1. 创建数据
X = np.array([1, 2, 3, 4, 5]).reshape(-1, 1)
y = np.array([2, 3, 5, 4, 6])
  1. 创建线性回归模型
model = LinearRegression()
  1. 训练模型
model.fit(X, y)
  1. 预测
y_pred = model.predict(X)
  1. 绘制结果
plt.scatter(X, y, color='blue')
plt.plot(X, y_pred, color='red')
plt.xlabel('x')
plt.ylabel('y')
plt.title('线性回归')
plt.show()

扩展阅读

如果您想深入了解线性回归,可以阅读以下文章:

希望这个教程能帮助您入门线性回归!🎉