用Python实现线性回归与决策树:机器学习基础算法代码详解
用Python实现线性回归与决策树:机器学习基础算法代码详解。本文深入剖析线性回归与决策树的核心数学原理,提供从零手写NumPy源码与Scikit-Learn标准工程实现,并对算法结构、节点分裂与模型评估进行多维度对比。
一、算法原理与核心机制解析
监督学习的核心任务是基于特征矩阵 \(X \in \mathbb{R}^{m \times n}\) 与标签向量 \(y\) 构建映射函数 \(f(X) \approx y\)。线性回归与决策树在拟合数据分布时采用了完全不同的几何与数学路径。
1.1 线性回归:全局线性超平面与最小二乘目标
线性回归假设目标变量 \(y\) 与特征向量 \(x = [x_1, x_2, \dots, x_n]^T\) 之间存在线性相关关系,其数学模型表示为:
$$\hat{y} = w_1 x_1 + w_2 x_2 + \dots + w_n x_n + b = w^T x + b$$
其中 \(w\) 为权重向量,\(b\) 为偏置项(截距)。为了衡量预测值与真实值之间的偏差,线性回归采用均方误差(Mean Squared Error, MSE)作为损失函数:
$$J(w, b) = \frac{1}{2m} \sum_{i=1}^{m} \left( \hat{y}^{(i)} - y^{(i)} \right)^2 = \frac{1}{2m} \| X w + b \mathbf{1} - y \|^2$$
求解该凸优化问题有两种经典路径:一是利用正规方程(Normal Equation)通过矩阵求逆直接获取全局解析最优解;二是在数据规模较大或矩阵不可逆时,采用梯度下降算法逐步迭代更新权重参数。
1.2 决策树:空间正交切分与节点纯度优化
与线性回归的全局连续拟合不同,决策树是一种基于“分而治之”策略的非参数模型。决策树从根节点开始,每次选取一个最优特征及其切分阈值,将样本集合二分为两个互斥的子集,从而在几何空间中生成一系列与坐标轴平行的正交决策边界。
衡量节点切分优劣的核心指标是不纯度(Impurity)。在 CART 分类树中,通常采用基尼不纯度(Gini Impurity)度量:
$$\text{Gini}(D) = 1 - \sum_{k=1}^{K} p_k^2$$
其中 \(p_k\) 为样本集合 \(D\) 中第 \(k\) 类样本的占比。当所有样本属于同一类别时,基尼值为 0,代表纯度最高;在回归任务中,则以切分后各子集的方差加权和最小化作为划分准则。
二、Python实现线性回归:从数学推导到完整代码
为了使读者彻底掌握线性回归的数值计算过程,本节先使用 NumPy 实现正规方程与批量梯度下降,再展示 Scikit-Learn 的工程化规范流程。
2.1 基于 NumPy 的正规方程与梯度下降手写实现
将截距项合并入权重向量后,增广特征矩阵表示为 \(\tilde{X} = [\mathbf{1}, X]\),增广参数为 \(\tilde{w} = [b, w_1, \dots, w_n]^T\)。正规方程解析解公式为:
$$\tilde{w} = (\tilde{X}^T \tilde{X})^{-1} \tilde{X}^T y$$
在工程实现中,为避免矩阵奇异不可逆,建议采用 Moore-Penrose 伪逆函数 np.linalg.pinv 替代常规逆矩阵函数 np.linalg.inv。完整手写代码如下:
import numpy as np
class ScratchLinearRegression:
def __init__(self, method="normal_equation", learning_rate=0.01, epochs=1000):
"""
参数说明:
method: 'normal_equation'(正规方程) 或 'gradient_descent'(梯度下降)
learning_rate: 梯度下降学习率
epochs: 梯度下降迭代轮数
"""
self.method = method
self.lr = learning_rate
self.epochs = epochs
self.weights = None
self.bias = None
def fit(self, X, y):
n_samples, n_features = X.shape
if self.method == "normal_equation":
# 添加偏置列全 1
X_b = np.c_[np.ones((n_samples, 1)), X]
# 计算增广参数 (X^T * X)^(-1) * X^T * y
params = np.linalg.pinv(X_b.T @ X_b) @ X_b.T @ y
self.bias = params[0]
self.weights = params[1:]
elif self.method == "gradient_descent":
self.weights = np.zeros(n_features)
self.bias = 0.0
for _ in range(self.epochs):
# 计算预测值与残差
y_pred = X @ self.weights + self.bias
error = y_pred - y
# 计算梯度并同步更新权重与偏置
grad_w = (1 / n_samples) * (X.T @ error)
grad_b = (1 / n_samples) * np.sum(error)
self.weights -= self.lr * grad_w
self.bias -= self.lr * grad_b
else:
raise ValueError("不支持的求解方法: " + str(self.method))
return self
def predict(self, X):
return X @ self.weights + self.bias
2.2 基于 Scikit-Learn 的工程化训练与指标评估
在实际生产环境中,线性回归依赖严格的数据准备流程,包括训练集与测试集划分、特征标准化以及定量评估指标的计算。
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
# 1. 生成可复现的连续回归模拟数据集
X, y = make_regression(n_samples=200, n_features=3, noise=15.0, random_state=42)
# 2. 划分训练集与测试集(8:2 分割)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 3. 特征标准化(在训练集上拟合,严防测试集数据穿越)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# 4. 模型实例化与拟合
lr_model = LinearRegression()
lr_model.fit(X_train_scaled, y_train)
# 5. 预测推断与性能评估
y_pred = lr_model.predict(X_test_scaled)
mse = mean_squared_error(y_test, y_pred)
rmse = np.sqrt(mse)
r2 = r2_score(y_test, y_pred)
print(f"拟合权重系数: {lr_model.coef_}")
print(f"截距偏置: {lr_model.intercept_:.4f}")
print(f"均方误差 MSE: {mse:.4f}")
print(f"均方根误差 RMSE: {rmse:.4f}")
print(f"决定系数 R2: {r2:.4f}")
三、Python实现决策树:二叉切分算法与调库实战
决策树的构建是一个递归生成二叉树的过程。其核心算法(CART)在每一个非叶节点上遍历所有特征和可能的分裂阈值,选取使子节点不纯度加权和最小的切分点。
3.1 基于 NumPy 的简易二叉分类决策树手写实现
以下代码完整展示了二叉树节点结构定义、基尼系数计算、最佳切分点寻找以及递归建树的全过程:
import numpy as np
class TreeNode:
"""决策树节点数据结构"""
def __init__(self, feature=None, threshold=None, left=None, right=None, *, value=None):
self.feature = feature # 分裂特征索引
self.threshold = threshold # 分裂数值阈值
self.left = left # 左子树节点
self.right = right # 右子树节点
self.value = value # 叶节点的预测类别
@property
def is_leaf(self):
return self.value is not None
class ScratchDecisionTreeClassifier:
def __init__(self, max_depth=3, min_samples_split=2):
self.max_depth = max_depth
self.min_samples_split = min_samples_split
self.root = None
def _gini(self, y):
"""计算样本标签集合的基尼不纯度"""
if len(y) == 0:
return 0.0
counts = np.bincount(y)
probabilities = counts / len(y)
return 1.0 - np.sum(probabilities ** 2)
def _best_split(self, X, y):
"""遍历所有特征与候选阈值,寻找信息增益最大的最佳切分"""
best_gain = -1.0
best_feat, best_thresh = None, None
current_gini = self._gini(y)
n_samples, n_features = X.shape
for feat in range(n_features):
thresholds = np.unique(X[:, feat])
for thresh in thresholds:
left_mask = X[:, feat] <= thresh
right_mask = ~left_mask
if np.sum(left_mask) == 0 or np.sum(right_mask) == 0:
continue
# 计算左右子节点的加权基尼值
gini_left = self._gini(y[left_mask])
gini_right = self._gini(y[right_mask])
weighted_gini = (np.sum(left_mask) / n_samples) * gini_left + (np.sum(right_mask) / n_samples) * gini_right
gain = current_gini - weighted_gini
if gain > best_gain:
best_gain = gain
best_feat = feat
best_thresh = thresh
return best_feat, best_thresh
def _grow_tree(self, X, y, depth=0):
"""递归构建二叉决策树"""
n_samples, n_features = X.shape
n_labels = len(np.unique(y))
# 停止生长条件:达到最大深度、节点已纯净、或样本量小于分裂阈值
if depth >= self.max_depth or n_labels == 1 or n_samples < self.min_samples_split:
leaf_value = np.bincount(y).argmax()
return TreeNode(value=leaf_value)
feat, thresh = self._best_split(X, y)
if feat is None:
leaf_value = np.bincount(y).argmax()
return TreeNode(value=leaf_value)
left_mask = X[:, feat] <= thresh
right_mask = ~left_mask
left_child = self._grow_tree(X[left_mask], y[left_mask], depth + 1)
right_child = self._grow_tree(X[right_mask], y[right_mask], depth + 1)
return TreeNode(feature=feat, threshold=thresh, left=left_child, right=right_child)
def fit(self, X, y):
self.root = self._grow_tree(X, y)
return self
def _predict_sample(self, x, node):
"""单样本自顶向下沿树搜索"""
if node.is_leaf:
return node.value
if x[node.feature] <= node.threshold:
return self._predict_sample(x, node.left)
return self._predict_sample(x, node.right)
def predict(self, X):
return np.array([self._predict_sample(x, self.root) for x in X])
3.2 基于 Scikit-Learn 的实践与防止过拟合调优
单棵决策树如果自由生长,叶节点会持续细分直至样本完全纯净,从而对训练集的随机噪声产生严重过拟合。在 Scikit-Learn 中,通过预剪枝(Pre-pruning)超参数能够有效控制树的结构复杂度:
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier, export_text
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, accuracy_score
# 1. 加载经典鸢尾花多分类数据集
iris = load_iris()
X_iris, y_iris = iris.data, iris.target
# 2. 划分测试集与训练集
X_tr, X_te, y_tr, y_te = train_test_split(X_iris, y_iris, test_size=0.3, random_state=42)
# 3. 构建决策树并显式配置预剪枝参数
# - max_depth: 限制树深度,防止分支过深
# - min_samples_split: 限制分裂所需最小样本量
# - min_samples_leaf: 限制叶节点保有的最小样本量
clf = DecisionTreeClassifier(
criterion="gini",
max_depth=3,
min_samples_split=4,
min_samples_leaf=2,
random_state=42
)
clf.fit(X_tr, y_tr)
# 4. 预测与评估
y_pred_tree = clf.predict(X_te)
print(f"测试集准确率: {accuracy_score(y_te, y_pred_tree):.4f}")
print("分类详细报告:\n", classification_report(y_te, y_pred_tree, target_names=iris.target_names))
# 5. 打印易于理解的文本决策规则
tree_rules = export_text(clf, feature_names=iris.feature_names)
print("模型生成的规则文本:\n", tree_rules)
四、两大算法核心特性对比与工程选型指南
在实际工程选型中,线性回归与决策树代表了两种完全不同的建模哲学。正确评估业务场景、数据分布与解释性要求,是算法选型的关键依据。
| 对比维度 | 线性回归 (Linear Regression) | 决策树 (Decision Tree) |
|---|---|---|
| 数学与几何模型 | 全局线性超平面,假设特征与标签呈线性相关 | 多维正交阶梯超平面,将特征空间递归细分为超矩形 |
| 特征工程要求 | 高度依赖标准化(Z-score)、多重共线性剔除 | 对特征单调变换与尺度不敏感,免标准化 |
| 异常值抗干扰度 | 极度敏感,离群点会剧烈扭曲回归直线斜率 | 鲁棒性强,数值微小扰动不影响切分阈值的相对排序 |
| 非线性拟合能力 | 弱,需手动构造多项式或交互项才能捕获非线性 | 强,通过多次深层切分天然能够拟合高阶非线性与特征交互 |
| 业务解释形式 | 系数形式(若 x 增加 1 单位,y 平均变动 w 单位) | 规则形式(if 特征 A <= 阈值 and 特征 B > 阈值 then 输出类别) |
| 过拟合与欠拟合倾向 | 容易欠拟合,通过增加高阶特征或降低正则化调整 | 极易过拟合,必须强制配置 max_depth 等预剪枝参数 |
五、常见问题排查与工程实践细节
在编写与部署线性回归与决策树算法时,有几个容易引发训练崩溃或评估失真的关键细节需要特别注意:
- 矩阵求逆时的奇异性(Singular Matrix):当特征矩阵存在完全共线性的特征列(例如特征 1 与特征 2 存在严格倍数关系)或者样本数小于特征数时,\(X^T X\) 的行列式为 0,导致常规求逆失败。在手写实现中,必须使用
np.linalg.pinv求解伪逆,或在 Scikit-Learn 中引入岭回归(Ridge Regression)加入 L2 正则化项。 - 数据预处理阶段的信息泄露(Data Leakage):标准化器(如
StandardScaler)只能在训练集X_train上调用fit_transform,测试集X_test必须严格调用transform。如果在划分测试集之前对全量数据计算均值与方差,会将测试集的统计信息提前泄露给模型,造成过于乐观的错误评估。 - 决策树轴对齐限制带来的斜向边界缺陷:决策树的分裂边界始终与坐标轴平行。如果真实数据的分类边界是一条倾斜的 45 度对角线,决策树必须分裂非常多次、形成密集的“阶梯状”锯齿才能逼近。在这种场景下,可先通过主成分分析(PCA)旋转坐标轴,或者结合线性分类器弥补缺陷。
通过本文的代码推导与工程实践可以看出,掌握线性回归的正规方程和决策树的递归划分逻辑,能够为深入理解更高级的模型(如岭回归、ElasticNet、随机森林和梯度提升树 XGBoost/LightGBM)打下扎实的基础。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









