机器学习(四)——决策树

目录

一、决策树是什么

二、 决策树分类原理

决策树的划分依据

1.信息增益:

​编辑​编辑2.信息增益率:

​编辑3.基尼指数:

三、决策树实现

​编辑四、实验中的问题

五、实验总结


一、决策树是什么

决策树通常用于分类和回归问题。它通过对数据集进行递归地划分,最终生成一棵树状结构,其中每个内部节点表示一个特征,每个叶子节点表示一个类别或数值。

二、 决策树分类原理

决策树的划分依据

1.信息增益:

信息增益就是用来评估一个特征对于分类任务的贡献程度的指标

2.信息增益率:

信息增益率是一种改进的特征选择度量方法,用于解决信息增益对取值较多的特征有偏好的问题,通过对信息增益进行调整,考虑了特征的取值数量对信息增益的影响。

3.基尼指数:

基尼指数是一种衡量数据集纯度的度量方法,常用于决策树算法中的特征选择。基尼指数越小,表示数据集纯度越高。

三、决策树实现

构建模型

import numpy as np

class Node:
    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  # 叶子节点的预测值

class DecisionTree:
    def __init__(self, max_depth=None):
        self.max_depth = max_depth
        
    def fit(self, X, y):
        self.n_classes = len(set(y))
        self.n_features = X.shape[1]
        self.tree = self._grow_tree(X, y)
        
    def predict(self, X):
        return [self._predict(inputs) for inputs in X]
        
    def _grow_tree(self, X, y, depth=0):
        n_samples_per_class = [np.sum(y == i) for i in range(self.n_classes)]
        predicted_class = np.argmax(n_samples_per_class)
        
        node = Node(value=predicted_class)
        
        if depth < self.max_depth:
            best_gain = 0.0
            best_feature = None
            best_threshold = None
            
            for feature in range(self.n_features):
                thresholds = np.unique(X[:, feature])
                
                for threshold in thresholds:
                    gain = self._information_gain(X, y, feature, threshold)
                    
                    if gain > best_gain:
                        best_gain = gain
                        best_feature = feature
                        best_threshold = threshold
                        
            if best_gain > 0.0:
                left_indices = X[:, best_feature] <= best_threshold
                X_left, y_left = X[left_indices], y[left_indices]
                X_right, y_right = X[~left_indices], y[~left_indices]
                
                node.feature = best_feature
                node.threshold = best_threshold
                node.left = self._grow_tree(X_left, y_left, depth + 1)
                node.right = self._grow_tree(X_right, y_right, depth + 1)
        
        return node
    
    def _predict(self, inputs):
        node = self.tree
        
        while node.left:
            if inputs[node.feature] <= node.threshold:
                node = node.left
            else:
                node = node.right
                
        return node.value
    
    def _information_gain(self, X, y, feature, threshold):
        parent_entropy = self._entropy(y)
        
        left_indices = X[:, feature] <= threshold
        right_indices = X[:, feature] > threshold
        
        n = len(y)
        n_left = np.sum(left_indices)
        n_right = np.sum(right_indices)
        
        left_entropy = self._entropy(y[left_indices])
        right_entropy = self._entropy(y[right_indices])
        
        child_entropy = (n_left / n) * left_entropy + (n_right / n) * right_entropy
        
        return parent_entropy - child_entropy
    
    def _entropy(self, y):
        entropy = 0.0
        
        for c in range(self.n_classes):
            p = np.mean(y == c)
            
            if p > 0.0:
                entropy -= p * np.log2(p)
                
        return entropy

实例

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# 加载鸢尾花数据集
iris = load_iris()
X = iris.data
y = iris.target

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 创建决策树模型并拟合数据
tree = DecisionTree(max_depth=2)
tree.fit(X_train, y_train)

# 使用模型进行预测
pred_y = tree.predict(X_test)

print(pred_y)
# 计算准确率
accuracy = accuracy_score(y_test, pred_y)
print("Accuracy:", accuracy)

结果

四、实验中的问题​​​​​​​

决策树模型没有进行剪枝等优化处理,不适用于处理大规模数据集。

五、实验总结

决策树优点:简单易懂,能处理多种数据类型,能够同时处理多个目标变量,可应对缺失的数据, 不用归一化。

决策树缺点:容易过拟合,对输入数据的表示形式敏感,不稳定性,忽略特征相关性

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
决策树算法是一种广泛应用于分类和回归的机器学习算法,它基于树形结构对样本进行分类或预测。决策树算法的主要思想是通过一系列的判断来对样本进行分类或预测。在决策树中,每个节点表示一个属性或特征,每个分支代表该属性或特征的一个取值,而每个叶子节点代表一个分类或预测结果。 决策树算法的训练过程主要包括以下步骤: 1. 特征选择:根据某种指标(如信息增益或基尼系数)选择最优的特征作为当前节点的分裂属性。 2. 决策树生成:根据选择的特征将数据集分成若干个子集,并递归地生成决策树。 3. 剪枝:通过剪枝操作来提高决策树的泛化性能。 决策树算法的优点包括易于理解和解释、计算复杂度较低、对缺失值不敏感等。但是,决策树算法也存在一些缺点,如容易出现过拟合、对离散数据敏感等。 下面是一个决策树算法的案例:假设我们要根据一个人的年龄、性别、教育程度和职业预测其收入水平(高于或低于50K)。首先,我们需要将这些特征进行编码,将其转换为数值型数据。然后,我们可以使用决策树算法对这些数据进行训练,并生成一个决策树模型。最后,我们可以使用该模型对新的数据进行分类或预测。例如,根据一个人的年龄、性别、教育程度和职业,我们可以使用决策树模型预测该人的收入水平。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值