Scikit Learn - 决策树
Scikit-Learn - 决策树
Section titled “Scikit-Learn - 决策树”本章介绍 Decision Trees(决策树),这是 Scikit-Learn 中可用的一种基础的非参数监督学习方法,用于分类和回归任务。
Decision Trees (DTs) 是通用的机器学习算法,通过从数据特征中学习简单的决策规则来预测目标变量的值。它们创建一个类似于树结构的模型。树中的每个内部节点表示对一个属性的“测试”(例如,特征 X <= 值 Y 吗?),每个分支表示测试的结果,每个叶节点表示一个类别标签(在分类中)或一个连续值(在回归中)。从根节点到叶节点的路径代表分类或回归规则。
决策树算法概述
Section titled “决策树算法概述”存在几种用于构建决策树的算法。一些具有历史意义的算法包括:
ID3 (Iterative Dichotomiser 3)
Section titled “ID3 (Iterative Dichotomiser 3)”由 Ross Quinlan 开发,ID3 通常使用 Information Gain(信息增益)来选择每个节点上的最佳分裂特征。它主要为分类特征和目标设计。
ID3 的后续版本,同样由 Quinlan 开发。C4.5 可以处理连续和分类特征,处理缺失值,并使用 Gain Ratio(增益率)作为分裂准则,以减轻对具有多值的特征的偏倚。它还在构建后修剪树。
Quinlan 后来的商业版本,通常比 C4.5 更准确且内存效率更高,支持 boosting 等高级功能。
CART (Classification and Regression Trees)
Section titled “CART (Classification and Regression Trees)”由 Breiman、Friedman、Olshen 和 Stone 开发。CART 构建二叉树(每个内部节点恰好有两个出边)。对于分类,它通常使用 Gini impurity(基尼不纯度)作为分裂准则;对于回归,它通常使用方差减少(例如 Mean Squared Error)。Scikit-Learn 的决策树实现是 CART 的优化版本。
决策树分类器 (DecisionTreeClassifier)
Section titled “决策树分类器 (DecisionTreeClassifier)”对于分类任务,Scikit-Learn 提供了 sklearn.tree.DecisionTreeClassifier。它能够处理多类别分类。
sklearn.tree.DecisionTreeClassifier 的重要参数:
| Parameter | Description |
|---|---|
| criterion | {‘gini’, ‘entropy’, ‘log_loss’},default=‘gini’。衡量分裂质量的函数。‘gini’ 用于 Gini impurity(基尼不纯度),‘entropy’ 或 ‘log_loss’ 用于 Information gain(信息增益)。 |
| splitter | {‘best’, ‘random’},default=‘best’。选择每个节点分裂策略。‘best’ 在所有特征中选择最佳分裂;‘random’ 在特征的随机子集中选择最佳分裂。 |
| max_depth | int, default=None。树的最大深度。如果为 None,节点将扩展直到所有叶节点是纯的或包含少于 min_samples_split 样本。 |
| min_samples_split | int 或 float, default=2。分裂内部节点所需的最小样本数。 |
| min_samples_leaf | int 或 float, default=1。位于叶节点所需的最小样本数。 |
| min_weight_fraction_leaf | float, default=0.0。位于叶节点所需的总权重加权比例的最小值。 |
| max_features | int, float 或 {‘auto’, ‘sqrt’, ‘log2’},default=None。寻找最佳分裂时要考虑的特征数量。如果为 None,则 max_features=n_features。 |
| random_state | int, RandomState 实例或 None,default=None。控制估计器的随机性(例如,对于 splitter='random' 或 max_features < n_features)。 |
| max_leaf_nodes | int, default=None。以最优优先的方式生长树,使其具有 max_leaf_nodes 个叶节点。如果为 None,则叶节点数量无限制。 |
| min_impurity_decrease | float, default=0.0。如果分裂导致不纯度降低大于或等于此值,则将分裂该节点。 |
| class_weight | dict, list of dicts, ‘balanced’ 或 None,default=None。与类别相关的权重。如果为 ‘balanced’,权重与类别频率成反比。 |
| ccp_alpha | non-negative float, default=0.0。用于 Minimal Cost-Complexity Pruning(最小成本-复杂度剪枝)的复杂度参数。将选择成本复杂度小于 ccp_alpha 的最大子树。 |
拟合 DecisionTreeClassifier 后:
| Attribute | Description |
|---|---|
| classes_ | shape 为 (n_classes,) 的 array 或此类 array 的列表。类别标签。 |
| feature_importances_ | shape 为 (n_features,) 的 array。特征的 Gini importance(基尼重要性)(或基于不纯度的重要性)。 |
| max_features_ | int。推断出的 max_features 值。 |
| n_classes_ | int 或 int 列表。类别数量。 |
| n_features_in_ | int。在 fit 期间看到的特征数量。 |
| n_outputs_ | int。执行 fit 时的输出数量。 |
| tree_ | Tree object。底层的 Tree 对象。提供对树结构的低级别访问。 |
常见方法:
| Method | Description |
|---|---|
| fit(X, y[, sample_weight]) | 从训练集 (X, y) 构建决策树分类器。 |
| predict(X) | 预测 X 的类别值。 |
| predict_proba(X) | 预测输入样本 X 的类别概率。 |
| predict_log_proba(X) | 预测输入样本 X 的类别对数概率。 |
| score(X, y[, sample_weight]) | 返回在给定测试数据和标签上的平均准确率。 |
| apply(X) | 返回每个样本被预测到的叶节点的索引。 |
| decision_path(X) | 返回树中每个样本的决策路径。 |
| get_depth() | 返回决策树的深度。 |
| get_n_leaves() | 返回决策树的叶节点数量。 |
| get_params([deep]) | 获取此估计器的参数。 |
| set_params(**params) | 设置此估计器的参数。 |
实现示例:Iris 数据集
Section titled “实现示例:Iris 数据集”from sklearn.tree import DecisionTreeClassifierfrom sklearn.model_selection import train_test_splitfrom sklearn.datasets import load_irisfrom sklearn.metrics import accuracy_score
# Load Iris datasetiris = load_iris()X, y = iris.data, iris.targetfeature_names = iris.feature_namestarget_names = iris.target_names
# Split dataX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# Initialize and fit Decision Tree Classifierdt_clf = DecisionTreeClassifier(max_depth=3, random_state=42)dt_clf.fit(X_train, y_train)
# Make predictionsy_pred = dt_clf.predict(X_test)print(f"Accuracy on test set: {accuracy_score(y_test, y_pred):.4f}")
# Predict probability for a sample pointsample_point_proba = dt_clf.predict_proba(X_test[:1])print(f"Predicted probabilities for first test sample: {sample_point_proba}")print(f"Actual class for first test sample: {target_names[y_test[0]]}")print(f"Predicted class for first test sample: {target_names[y_pred[0]]}")Accuracy on test set: 0.9778Predicted probabilities for first test sample: [[0. 0.90697674 0.09302326]]Actual class for first test sample: versicolorPredicted class for first test sample: versicolor可以使用 sklearn.tree.plot_tree(需要 Matplotlib)来可视化决策树。
import matplotlib.pyplot as pltfrom sklearn.tree import plot_tree
# plt.figure(figsize=(15,10))# plot_tree(dt_clf, filled=True, feature_names=feature_names, class_names=list(target_names), rounded=True)# plt.title("Decision Tree for Iris Dataset")# plt.show()该图将显示树结构,包括决策节点(关于特征的条件)、分支和叶节点(预测的类别和样本分布)。
决策树回归器 (DecisionTreeRegressor)
Section titled “决策树回归器 (DecisionTreeRegressor)”对于目标变量是连续值的回归任务,Scikit-Learn 提供了 sklearn.tree.DecisionTreeRegressor。
参数与 DecisionTreeClassifier 大致相似。主要区别:
- criterion: {‘squared_error’, ‘friedman_mse’, ‘absolute_error’, ‘poisson’},default=‘squared_error’。衡量分裂质量的函数。‘squared_error’ (MSE,均方误差),‘friedman_mse’ (MSE with Friedman’s improvement score),‘absolute_error’ (MAE,平均绝对误差),‘poisson’ (Poisson deviance,泊松偏差)。
- 没有
class_weight参数。
类似于 DecisionTreeClassifier,但缺少 classes_ 和 n_classes_ 属性。
类似于 DecisionTreeClassifier,但缺少 predict_proba() 和 predict_log_proba() 方法。
实现示例:简单回归
Section titled “实现示例:简单回归”from sklearn.tree import DecisionTreeRegressorimport numpy as np
# Sample data for regressionrng = np.random.RandomState(1)X_reg = np.sort(5 * rng.rand(80, 1), axis=0)y_reg = np.sin(X_reg).ravel() + rng.randn(80) * 0.1 # y = sin(x) + noisey_reg[::5] += 3 * (0.5 - rng.rand(16)) # Add some noise/outliers
# Fit Decision Tree Regressordt_reg = DecisionTreeRegressor(max_depth=4, random_state=42)dt_reg.fit(X_reg, y_reg)
# Predict on new data pointsX_test_reg = np.arange(0.0, 5.0, 0.01)[:, np.newaxis]y_pred_reg = dt_reg.predict(X_test_reg)
print(f"Shape of X_test_reg: {X_test_reg.shape}")print(f"Shape of y_pred_reg: {y_pred_reg.shape}")print(f"Prediction for X=2.5: {dt_reg.predict([[2.5]])}")
# Visualize the results (optional)# plt.figure(figsize=(10,6))# plt.scatter(X_reg, y_reg, s=20, edgecolor="black", c="darkorange", label="data")# plt.plot(X_test_reg, y_pred_reg, color="cornflowerblue", label="max_depth=4", linewidth=2)# plt.xlabel("data")# plt.ylabel("target")# plt.title("Decision Tree Regression")# plt.legend()# plt.show()Shape of X_test_reg: (500, 1)Shape of y_pred_reg: (500,)Prediction for X=2.5: [0.70817608]回归的图会显示原始数据点和一个代表决策树预测结果的阶梯函数。
决策树直观且易于可视化。然而,单个树容易过拟合。集成方法如 Random Forests(随机森林)和 Gradient Boosting Trees(梯度提升树),它们以决策树为基础构建,通常能产生更好的性能。Minimal Cost-Complexity Pruning(最小成本-复杂度剪枝,ccp_alpha)是控制树大小和防止过拟合的重要技术。更多信息,请参阅 Scikit-Learn 决策树文档。