python 实现decision tree决策树算法

news/2024/10/5 2:07:21/

decision tree决策树算法介绍

决策树算法(Decision Tree Algorithm)是一种基于输入特征对实例进行分类的树结构模型,主要用于分类和回归任务。其基本原理是根据训练数据的特征属性和类别标签之间的关系,生成一个能够对新样本进行分类或回归的模型。以下是对决策树算法的详细解释:

一、基本概念

决策树:一种树形结构,每个非叶子节点表示一个特征或划分实例类别的条件,每个叶子节点表示一个类别或回归值。
分类与回归:决策树既可用于分类问题,也可用于回归问题。
典型算法:ID3、C4.5、CART等。

二、基本原理

数据预处理:对原始数据进行处理,如特征选择、数据清洗等。
决策树的生成:
使用训练数据集,根据特征属性和类别标签之间的关系,构建决策树
决策树的生成过程通常包括特征选择、节点分裂等步骤。
决策树的剪枝:对生成的决策树进行检验、校正和修剪,以提高模型的泛化能力。

三、应用领域

决策树算法广泛应用于各个领域,如:

金融风险评估:通过对客户的信用、还款能力等特征进行分析,识别高风险客户。
疾病诊断:根据病人的症状和检查结果,辅助医生进行疾病的诊断。
营销推荐:根据用户的历史消费行为和个人特征,推荐感兴趣的产品或服务。
网络安全:通过对网络流量数据的分析,检测和预防网络攻击和滥用。

四、优缺点

优点:
模型具有可读性,分类速度快。
能够处理多种类型的数据,包括数值型和类别型。
对异常值不敏感。
缺点:
容易过拟合,需要通过剪枝等技术进行处理。
对缺失值敏感,需要进行适当的处理。

五、总结

决策树算法是一种有效的分类和回归方法,通过构建树形结构来对数据进行分类或预测。在实际应用中,需要注意选择合适的算法参数和进行必要的预处理工作,以提高模型的性能和泛化能力。

python_39">decision tree决策树算法python实现样例

下面是一个使用Python实现决策树算法的示例代码:

python">import pandas as pd
import numpy as npdef entropy(y):"""计算给定数据集的熵:param y: 数据集标签:return: 熵"""_, counts = np.unique(y, return_counts=True)probabilities = counts / len(y)entropy = -np.sum(probabilities * np.log2(probabilities))return entropydef information_gain(X, y, split_feature):"""计算给定特征对应的信息增益:param X: 数据集特征:param y: 数据集标签:param split_feature: 待计算信息增益的特征:return: 信息增益"""total_entropy = entropy(y)feature_values = np.unique(X[:, split_feature])feature_entropy = 0for value in feature_values:y_subset = y[X[:, split_feature] == value]subset_entropy = entropy(y_subset)weight = len(y_subset) / len(y)feature_entropy += weight * subset_entropyinformation_gain = total_entropy - feature_entropyreturn information_gaindef get_best_split(X, y):"""在给定的数据集上找到最佳分裂特征:param X: 数据集特征:param y: 数据集标签:return: 最佳分裂特征的索引"""num_features = X.shape[1]best_info_gain = -1best_feature = -1for i in range(num_features):info_gain = information_gain(X, y, i)if info_gain > best_info_gain:best_info_gain = info_gainbest_feature = ireturn best_featuredef create_decision_tree(X, y, feature_names):"""创建决策树:param X: 数据集特征:param y: 数据集标签:param feature_names: 特征名称列表:return: 决策树"""# 如果数据集只包含一个类别,则返回该类别if len(set(y)) == 1:return y[0]# 如果数据集的特征为空,则返回出现次数最多的类别if X.shape[1] == 0:return np.argmax(np.bincount(y))best_feature = get_best_split(X, y)best_feature_name = feature_names[best_feature]decision_tree = {best_feature_name: {}}feature_values = np.unique(X[:, best_feature])for value in feature_values:value_indices = np.where(X[:, best_feature] == value)[0]subset_X = X[value_indices]subset_y = y[value_indices]subset_feature_names = feature_names[:best_feature] + feature_names[best_feature+1:]decision_tree[best_feature_name][value] = create_decision_tree(subset_X, subset_y, subset_feature_names)return decision_treedef predict(X, decision_tree):"""使用决策树进行预测:param X: 待预测的样本:param decision_tree: 决策树:return: 预测结果"""if not isinstance(decision_tree, dict):return decision_treeroot = next(iter(decision_tree))subtree = decision_tree[root]feature_index = feature_names.index(root)feature_value = X[feature_index]if feature_value in subtree:return predict(X, subtree[feature_value])else:return np.argmax(np.bincount(y))# 构造示例数据集
data = np.array([[1, 1, 1],[1, 1, 0],[1, 0, 1],[0, 1, 0],[0, 0, 1]])
X = data[:, :-1]
y = data[:, -1]
feature_names = ['feature1', 'feature2']# 创建决策树
decision_tree = create_decision_tree(X, y, feature_names)# 预测样本
sample = np.array([1, 0])
prediction = predict(sample, decision_tree)
print(f"预测结果:{prediction}")

这个示例实现了决策树算法的基本功能。使用的数据集是一个简单的二分类问题,特征集合包含2个特征值。算法使用信息增益作为分裂准则来构建决策树,并使用预测函数对新样本进行预测。


http://www.ppmy.cn/news/1534692.html

相关文章

OSDU轻量化单机部署

首先更新系统 sudo apt update sudo apt upgrade -y安装docker sudo apt install -y docker.io sudo systemctl start docker sudo systemctl enable docker安装minikube curl -Lo minikube https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64 …

electron打包报错-winCodeSign无法下载

electron打包报错-winCodeSign下载问题 问题描述 downloaded urlhttps://registry.npmmirror.com/-/binary/electron-builder-binaries/winCodeSign-2.6.0/winCodeSign-2.6.0.7z duration1.577s⨯ cannot execute causeexit status 2outerrorOutERROR: Cannot create s…

使用ESPnet的 setup_anaconda.sh安装脚本一步到位,配置conda虚拟环境

使用ESPnet的 setup_anaconda.sh 安装脚本一步到位,配置conda虚拟环境 前言 ESPnet(End-to-End Speech Processing Toolkit)是一款用于语音识别、语音合成等任务的开源端到端语音处理工具包。为了在不同系统上快速配置ESPnet开发环境&#…

01_OpenCV图片读取与展示

import cv2 img cv2.imread(夕阳.jpg, 1) #cv2.imshow(image, img) #此行只能命令行处py文件执行,会弹出一个视频窗口 #cv2.waitKey (0)以下会在jupyter Lab控件中显示读取的图像 #bgr8转jpeg格式 import enum import cv2def bgr8_to_jpeg(value, quality75):ret…

CSP-J Day 4 模拟赛补题报告

姓名:王胤皓,校区:和谐校区,考试时间: 2024 2024 2024 年 10 10 10 月 4 4 4 日 9 : 00 : 00 9:00:00 9:00:00~ 12 : 30 : 00 12:30:00 12:30:00,学号: S 07738 S07738 S07738 请关注作者的…

GS-SLAM论文阅读笔记-CaRtGS

前言 这篇文章看起来有点像Photo-slam的续作,行文格式和图片类型很接近,而且貌似是出自同一所学校的,所以推测可能是Photo-slam的优化与改进方法,接下来具体看看改进了哪些地方。 文章目录 前言1.背景介绍GS-SLAM方法总结 2.关键…

使用CAPTCHA对反爬虫有优势吗

使用CAPTCHA对抗爬虫确实具有一些显著的优势,以下是主要优点和考虑因素: 优势 有效阻止自动化访问 人机验证:CAPTCHA设计用于区分人类用户与机器人,能够有效防止自动化爬虫访问网站内容。阻挡恶意行为:大多数爬虫无法…

【vs code(cursor) ssh连不上服务器】但是 Terminal 可以连上,问题解决 ✅

问题描述 通过 vs code 的 ssh 原本方式无法连接,但是通过 Terminal 使用相同的 bash 却可以连接上服务器。 ssh -p 4xx username14.xxx.3 问题解决方法 在 vs code 的 config 里,将该服务器(14.xxx.3)的相关配置全部清空或注释…