第5集:决策树与随机森林——直观的分类与回归方法

在机器学习中,决策树(Decision Tree)随机森林(Random Forest) 是两种直观且强大的算法,广泛应用于分类和回归任务。决策树通过一系列规则对数据进行划分,而随机森林则是由多棵决策树组成的集成模型,能够显著提升预测性能。今天我们将深入探讨这两种算法的原理,并通过实践部分使用 Wine Quality 数据集 进行分类预测。


决策树的工作机制

什么是决策树?

决策树是一种基于树形结构的监督学习算法,其核心思想是递归地将数据划分为更小的子集,直到满足某种停止条件。每个内部节点表示一个特征测试,每个分支表示测试结果,每个叶节点表示一个类别或输出值。

决策树的构建过程

  1. 选择最佳划分特征:根据某种准则(如信息增益或基尼指数)选择最优特征。
  2. 递归划分:对每个子集重复上述过程,直到满足停止条件(如达到最大深度或节点纯度足够高)。
  3. 生成叶节点:当划分停止时,生成叶节点并赋予类别或输出值。

信息增益与基尼指数

1. 信息增益

信息增益衡量划分前后数据集的不确定性减少程度。公式如下:
Information Gain = H ( D ) − ∑ v ∈ V ∣ D v ∣ ∣ D ∣ H ( D v ) \text{Information Gain} = H(D) - \sum_{v \in V} \frac{|D_v|}{|D|} H(D_v) Information Gain=H(D)vVDDvH(Dv)
其中:
H ( D ) 是数据集 D 的熵。 H(D) 是数据集 D 的熵。 H(D)是数据集D的熵。
D v 是划分后的子集。 D_v 是划分后的子集。 Dv是划分后的子集。

熵的计算公式为:
H ( D ) = − ∑ i = 1 n p i log ⁡ 2 ( p i ) H(D) = -\sum_{i=1}^{n} p_i \log_2(p_i) H(D)=i=1npilog2(pi)
其中 p i 是第 i 类样本的比例。 p_i 是第 i 类样本的比例。 pi是第i类样本的比例。

2. 基尼指数

基尼指数衡量数据集的不纯度,越小表示纯度越高。公式如下:
Gini Index = 1 − ∑ i = 1 n p i 2 \text{Gini Index} = 1 - \sum_{i=1}^{n} p_i^2 Gini Index=1i=1npi2


随机森林的概念及其优势

什么是随机森林?

随机森林是一种基于决策树的集成学习算法,通过构建多棵决策树并将它们的结果进行投票或平均来提高模型的稳定性和准确性。

随机森林的优势

  1. 减少过拟合:通过引入随机性(如随机选择特征和样本),降低单棵树的过拟合风险。
  2. 鲁棒性强:对噪声数据具有较好的容忍能力。
  3. 易于调参:超参数较少,且对默认值通常表现良好。

超参数调优

随机森林的性能受以下超参数影响:

  • n_estimators:森林中树的数量,越多通常效果越好,但会增加计算成本。
  • max_depth:每棵树的最大深度,控制模型复杂度。
  • min_samples_split:分裂节点所需的最小样本数。
  • max_features:每棵树分裂时考虑的最大特征数。

可以通过网格搜索(Grid Search)或随机搜索(Random Search)优化这些超参数。


实践部分:使用随机森林对 Wine Quality 数据集进行分类预测

数据集简介

Wine Quality 数据集包含葡萄酒的化学特性及其质量评分(从 0 到 10)。我们将使用该数据集进行二分类任务,目标是预测葡萄酒是否为高质量(评分 ≥ 7)。

完整代码

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
from sklearn.preprocessing import StandardScaler

# 加载数据
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv"
data = pd.read_csv(url, sep=';')

# 构建二分类目标变量
data['Quality'] = data['quality'].apply(lambda x: 1 if x >= 7 else 0)

# 提取特征和标签
X = data.drop(['quality', 'Quality'], axis=1)
y = data['Quality']

# 标准化特征
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# 分割数据集
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.3, random_state=42)

# 构建随机森林模型
model = RandomForestClassifier(random_state=42)

# 超参数调优
param_grid = {
    'n_estimators': [50, 100, 200],
    'max_depth': [None, 10, 20],
    'min_samples_split': [2, 5, 10]
}
grid_search = GridSearchCV(model, param_grid, cv=3, scoring='accuracy')
grid_search.fit(X_train, y_train)

# 最佳模型
best_model = grid_search.best_estimator_

# 预测
y_pred = best_model.predict(X_test)

# 评估模型性能
accuracy = accuracy_score(y_test, y_pred)
conf_matrix = confusion_matrix(y_test, y_pred)
class_report = classification_report(y_test, y_pred)

print("最佳超参数:", grid_search.best_params_)
print(f"Accuracy: {accuracy:.2f}")
print("Confusion Matrix:")
print(conf_matrix)
print("Classification Report:")
print(class_report)

# 特征重要性可视化
feature_importances = best_model.feature_importances_
features = data.drop(['quality', 'Quality'], axis=1).columns

plt.figure(figsize=(10, 6))
plt.barh(features, feature_importances, color='skyblue')
plt.title('Feature Importances in Random Forest', fontsize=16)
plt.xlabel('Importance Score', fontsize=12)
plt.ylabel('Features', fontsize=12)
plt.show()

运行结果

输出结果:
最佳超参数: {'max_depth': None, 'min_samples_split': 2, 'n_estimators': 100}
Accuracy: 0.91
Confusion Matrix:
[[408   6]
 [ 37  19]]
Classification Report:
              precision    recall  f1-score   support
           0       0.92      0.99      0.95       414
           1       0.76      0.34      0.47        56
    accuracy                           0.91       470
   macro avg       0.84      0.66      0.71       470
weighted avg       0.90      0.91      0.89       470

总结

本文介绍了决策树和随机森林的基本原理,并通过实践部分展示了如何使用随机森林对 Wine Quality 数据集进行分类预测。希望这篇文章能帮助你更好地理解这两种算法!


参考资料

第5集:决策树与随机森林——直观的分类与回归方法

在机器学习中,决策树(Decision Tree)随机森林(Random Forest) 是两种直观且强大的算法,广泛应用于分类和回归任务。决策树通过一系列规则对数据进行划分,而随机森林则是由多棵决策树组成的集成模型,能够显著提升预测性能。今天我们将深入探讨这两种算法的原理,并通过实践部分使用 Wine Quality 数据集 进行分类预测。


决策树的工作机制

什么是决策树?

决策树是一种基于树形结构的监督学习算法,其核心思想是递归地将数据划分为更小的子集,直到满足某种停止条件。每个内部节点表示一个特征测试,每个分支表示测试结果,每个叶节点表示一个类别或输出值。

决策树的构建过程

  1. 选择最佳划分特征:根据某种准则(如信息增益或基尼指数)选择最优特征。
  2. 递归划分:对每个子集重复上述过程,直到满足停止条件(如达到最大深度或节点纯度足够高)。
  3. 生成叶节点:当划分停止时,生成叶节点并赋予类别或输出值。

信息增益与基尼指数

1. 信息增益

信息增益衡量划分前后数据集的不确定性减少程度。公式如下:
Information Gain = H ( D ) − ∑ v ∈ V ∣ D v ∣ ∣ D ∣ H ( D v ) \text{Information Gain} = H(D) - \sum_{v \in V} \frac{|D_v|}{|D|} H(D_v) Information Gain=H(D)vVDDvH(Dv)
其中:

  • $ H(D) $ 是数据集 $ D $ 的熵。
  • $ D_v $ 是划分后的子集。

熵的计算公式为:
H ( D ) = − ∑ i = 1 n p i log ⁡ 2 ( p i ) H(D) = -\sum_{i=1}^{n} p_i \log_2(p_i) H(D)=i=1npilog2(pi)
其中 $ p_i $ 是第 $ i $ 类样本的比例。

2. 基尼指数

基尼指数衡量数据集的不纯度,越小表示纯度越高。公式如下:
Gini Index = 1 − ∑ i = 1 n p i 2 \text{Gini Index} = 1 - \sum_{i=1}^{n} p_i^2 Gini Index=1i=1npi2

案例:基于信息增益的决策树案例

数据集描述

我们使用一个简单的数据集来说明如何构建决策树。假设我们有以下数据:

计算信息增益

我们以“天气”为例,计算信息增益。

  1. 整体熵
    H ( D ) = − ( 9 14 log ⁡ 2 9 14 + 5 14 log ⁡ 2 5 14 ) ≈ 0.94 H(D) = -\left(\frac{9}{14} \log_2 \frac{9}{14} + \frac{5}{14} \log_2 \frac{5}{14}\right) \approx 0.94 H(D)=(149log2149+145log2145)0.94

  2. 按“天气”划分后熵

S u n n y : H ( S u n n y ) = − ( 2 5 log ⁡ 2 2 5 + 3 5 log ⁡ 2 3 5 ) ≈ 0.97 Sunny: H(Sunny) = -\left(\frac{2}{5} \log_2 \frac{2}{5} + \frac{3}{5} \log_2 \frac{3}{5}\right) \approx 0.97 SunnyH(Sunny)=(52log252+53log253)0.97
O v e r c a s t : H ( O v e r c a s t ) = 0 (全部为 Y e s ) Overcast: H(Overcast) = 0 (全部为 Yes) OvercastH(Overcast)=0(全部为Yes
R a i n : H ( R a i n ) = − ( 3 5 log ⁡ 2 3 5 + 2 5 log ⁡ 2 2 5 ) ≈ 0.97 Rain: H(Rain) = -\left(\frac{3}{5} \log_2 \frac{3}{5} + \frac{2}{5} \log_2 \frac{2}{5}\right) \approx 0.97 RainH(Rain)=(53log253+52log252)0.97

平均熵:
H ( D ∣ O u t l o o k ) = 5 14 ⋅ 0.97 + 4 14 ⋅ 0 + 5 14 ⋅ 0.97 ≈ 0.69 H(D|Outlook) = \frac{5}{14} \cdot 0.97 + \frac{4}{14} \cdot 0 + \frac{5}{14} \cdot 0.97 \approx 0.69 H(DOutlook)=1450.97+1440+1450.970.69

  1. 信息增益
    I G ( O u t l o o k ) = H ( D ) − H ( D ∣ O u t l o o k ) ≈ 0.94 − 0.69 = 0.25 IG(Outlook) = H(D) - H(D|Outlook) \approx 0.94 - 0.69 = 0.25 IG(Outlook)=H(D)H(DOutlook)0.940.69=0.25

决策树描述

根据信息增益,选择“天气”作为根节点,进一步划分其他特征,最终得到如下决策树:


随机森林的概念及其优势

什么是随机森林?

随机森林是一种基于决策树的集成学习算法,通过构建多棵决策树并将它们的结果进行投票或平均来提高模型的稳定性和准确性。

随机森林的优势

  1. 减少过拟合:通过引入随机性(如随机选择特征和样本),降低单棵树的过拟合风险。
  2. 鲁棒性强:对噪声数据具有较好的容忍能力。
  3. 易于调参:超参数较少,且对默认值通常表现良好。

超参数调优

随机森林的性能受以下超参数影响:

  • n_estimators:森林中树的数量,越多通常效果越好,但会增加计算成本。
  • max_depth:每棵树的最大深度,控制模型复杂度。
  • min_samples_split:分裂节点所需的最小样本数。
  • max_features:每棵树分裂时考虑的最大特征数。

可以通过网格搜索(Grid Search)或随机搜索(Random Search)优化这些超参数。


实践部分:使用随机森林对 Wine Quality 数据集进行分类预测

数据集简介

Wine Quality 数据集包含葡萄酒的化学特性及其质量评分(从 0 到 10)。我们将使用该数据集进行二分类任务,目标是预测葡萄酒是否为高质量(评分 ≥ 7)。

完整代码

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
from sklearn.preprocessing import StandardScaler

# 加载数据
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv"
data = pd.read_csv(url, sep=';')

# 构建二分类目标变量
data['Quality'] = data['quality'].apply(lambda x: 1 if x >= 7 else 0)

# 提取特征和标签
X = data.drop(['quality', 'Quality'], axis=1)
y = data['Quality']

# 标准化特征
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# 分割数据集
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.3, random_state=42)

# 构建随机森林模型
model = RandomForestClassifier(random_state=42)

# 超参数调优
param_grid = {
    'n_estimators': [50, 100, 200],
    'max_depth': [None, 10, 20],
    'min_samples_split': [2, 5, 10]
}
grid_search = GridSearchCV(model, param_grid, cv=3, scoring='accuracy')
grid_search.fit(X_train, y_train)

# 最佳模型
best_model = grid_search.best_estimator_

# 预测
y_pred = best_model.predict(X_test)

# 评估模型性能
accuracy = accuracy_score(y_test, y_pred)
conf_matrix = confusion_matrix(y_test, y_pred)
class_report = classification_report(y_test, y_pred)

print("最佳超参数:", grid_search.best_params_)
print(f"Accuracy: {accuracy:.2f}")
print("Confusion Matrix:")
print(conf_matrix)
print("Classification Report:")
print(class_report)

# 特征重要性可视化
feature_importances = best_model.feature_importances_
features = data.drop(['quality', 'Quality'], axis=1).columns

plt.figure(figsize=(10, 6))
plt.barh(features, feature_importances, color='skyblue')
plt.title('Feature Importances in Random Forest', fontsize=16)
plt.xlabel('Importance Score', fontsize=12)
plt.ylabel('Features', fontsize=12)
plt.show()

运行结果

输出结果:
最佳超参数: {'max_depth': None, 'min_samples_split': 2, 'n_estimators': 100}
Accuracy: 0.91
Confusion Matrix:
[[408   6]
 [ 37  19]]
Classification Report:
              precision    recall  f1-score   support
           0       0.92      0.99      0.95       414
           1       0.76      0.34      0.47        56
    accuracy                           0.91       470
   macro avg       0.84      0.66      0.71       470
weighted avg       0.90      0.91      0.89       470

总结

本文介绍了决策树和随机森林的基本原理,并通过实践部分展示了如何使用随机森林对 Wine Quality 数据集进行分类预测。希望这篇文章能帮助你更好地理解这两种算法!

下集预告:第6集:支持向量机(SVM)——强大的非线性分类器


参考资料

02-19 10:01