用python写含注释的c4.5决策树代码

时间: 2024-05-05 10:21:14 浏览: 16
这里提供一个简单的Python实现C4.5决策树的示例代码,包含注释,希望对您有帮助。代码如下: ```python import numpy as np import pandas as pd import math class C45DecisionTree: def __init__(self, epsilon=0.1): self.epsilon = epsilon # 停止划分阈值 self.tree = {} # 计算数据集的经验熵 def calc_entropy(self, y): n = len(y) label_count = {} for label in y: if label not in label_count: label_count[label] = 0 label_count[label] += 1 entropy = 0.0 for label in label_count: prob = float(label_count[label]) / n entropy -= prob * math.log2(prob) return entropy # 计算条件熵 def calc_cond_entropy(self, x, y): n = len(y) feature_count = {} for i in range(n): feature = x[i] label = y[i] if feature not in feature_count: feature_count[feature] = {} if label not in feature_count[feature]: feature_count[feature][label] = 0 feature_count[feature][label] += 1 cond_entropy = 0.0 for feature in feature_count: feature_prob = sum(feature_count[feature].values()) / n feature_cond_entropy = 0.0 for label in feature_count[feature]: prob = float(feature_count[feature][label]) / feature_prob feature_cond_entropy -= prob * math.log2(prob) cond_entropy += feature_prob * feature_cond_entropy return cond_entropy # 计算信息增益率 def calc_info_gain_ratio(self, x, y): entropy = self.calc_entropy(y) cond_entropy = self.calc_cond_entropy(x, y) info_gain = entropy - cond_entropy # 计算分裂信息 split_info = 0.0 n = len(y) feature_count = {} for feature in x: if feature not in feature_count: feature_count[feature] = 0 feature_count[feature] += 1 for feature in feature_count: prob = float(feature_count[feature]) / n split_info -= prob * math.log2(prob) # 计算信息增益率 if split_info == 0: return 0 else: return info_gain / split_info # 选择最优划分特征 def choose_best_feature(self, X, y): m = len(X[0]) best_feature = -1 best_info_gain_ratio = 0.0 for i in range(m): x_i = [X[j][i] for j in range(len(X))] info_gain_ratio = self.calc_info_gain_ratio(x_i, y) if info_gain_ratio > best_info_gain_ratio: best_info_gain_ratio = info_gain_ratio best_feature = i return best_feature # 获取标签中出现次数最多的值 def get_majority_label(self, y): label_count = {} for label in y: if label not in label_count: label_count[label] = 0 label_count[label] += 1 sorted_label_count = sorted(label_count.items(), key=lambda x: x[1], reverse=True) return sorted_label_count[0][0] # 递归构建决策树 def create_tree(self, X, y, feature_names): # 如果只有一个类别,返回这个类别 if len(set(y)) == 1: return y[0] # 如果特征集为空,返回标签中出现次数最多的类别 if len(X[0]) == 0: return self.get_majority_label(y) # 如果数据集中的样本都属于同一个类别,返回这个类别 if len(set([tuple(x) for x in X])) == 1: return y[0] # 选择最优划分特征 best_feature_index = self.choose_best_feature(X, y) best_feature_name = feature_names[best_feature_index] tree = {best_feature_name: {}} # 删除已选择的特征 del feature_names[best_feature_index] # 划分子集 feature_values = [example[best_feature_index] for example in X] unique_feature_values = set(feature_values) for feature_value in unique_feature_values: sub_feature_names = feature_names[:] sub_X = [] sub_y = [] for i in range(len(X)): if X[i][best_feature_index] == feature_value: sub_X.append(X[i][:best_feature_index] + X[i][best_feature_index+1:]) sub_y.append(y[i]) sub_tree = self.create_tree(sub_X, sub_y, sub_feature_names) tree[best_feature_name][feature_value] = sub_tree return tree # 训练决策树 def fit(self, X, y, feature_names): self.tree = self.create_tree(X, y, feature_names) # 预测单个样本 def predict_single(self, X_sample): tree = self.tree while type(tree) == dict: feature_name = list(tree.keys())[0] feature_value = X_sample[feature_name] tree = tree[feature_name][feature_value] return tree # 预测多个样本 def predict(self, X): y_pred = [] for sample in X: y_pred.append(self.predict_single(sample)) return y_pred ``` 使用示例: ```python # 读取数据 data = pd.read_csv('data.csv') X = data.iloc[:, :-1].to_dict(orient='records') y = data.iloc[:, -1].tolist() feature_names = list(data.columns[:-1]) # 构建决策树 tree = C45DecisionTree(epsilon=0.1) tree.fit(X, y, feature_names) # 预测单个样本 X_sample = {'age': 'middle_aged', 'income': 'high', 'student': 'no', 'credit_rating': 'fair'} y_pred = tree.predict_single(X_sample) print(y_pred) # 预测多个样本 X_test = [{'age': 'youth', 'income': 'low', 'student': 'no', 'credit_rating': 'fair'}, {'age': 'middle_aged', 'income': 'high', 'student': 'no', 'credit_rating': 'fair'}, {'age': 'senior', 'income': 'low', 'student': 'no', 'credit_rating': 'fair'}, {'age': 'youth', 'income': 'low', 'student': 'yes', 'credit_rating': 'fair'}, {'age': 'youth', 'income': 'low', 'student': 'yes', 'credit_rating': 'excellent'}] y_pred = tree.predict(X_test) print(y_pred) ```

相关推荐

最新推荐

recommend-type

决策树剪枝算法的python实现方法详解

主要介绍了决策树剪枝算法的python实现方法,结合实例形式较为详细的分析了决策树剪枝算法的概念、原理并结合实例形式分析了Python相关实现技巧,需要的朋友可以参考下
recommend-type

python使用sklearn实现决策树的方法示例

主要介绍了python使用sklearn实现决策树的方法示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
recommend-type

Python机器学习之决策树算法实例详解

主要介绍了Python机器学习之决策树算法,较为详细的分析了实例详解机器学习中决策树算法的概念、原理及相关Python实现技巧,需要的朋友可以参考下
recommend-type

Python决策树之基于信息增益的特征选择示例

主要介绍了Python决策树之基于信息增益的特征选择,结合实例形式分析了决策树中基于信息增益的特征选择原理、计算公式、操作流程以及具体实现技巧,需要的朋友可以参考下
recommend-type

QT5开发及实例配套源代码.zip

QT5开发及实例配套[源代码],Qt是诺基亚公司的C++可视化开发平台,本书以Qt 5作为平台,每个章节在简单介绍开发环境的基础上,用一个小实例,介绍Qt 5应用程序开发各个方面,然后系统介绍Qt 5应用程序的开发技术,一般均通过实例介绍和讲解内容。最后通过三个大实例,系统介绍Qt 5综合应用开发。光盘中包含本书教学课件和书中所有实例源代码及其相关文件。通过学习本书,结合实例上机练习,一般能够在比较短的时间内掌握Qt 5应用技术。本书既可作为Qt 5的学习和参考用书,也可作为大学教材或Qt 5培训用书。
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

MATLAB柱状图在信号处理中的应用:可视化信号特征和频谱分析

![matlab画柱状图](https://img-blog.csdnimg.cn/3f32348f1c9c4481a6f5931993732f97.png) # 1. MATLAB柱状图概述** MATLAB柱状图是一种图形化工具,用于可视化数据中不同类别或组的分布情况。它通过绘制垂直条形来表示每个类别或组中的数据值。柱状图在信号处理中广泛用于可视化信号特征和进行频谱分析。 柱状图的优点在于其简单易懂,能够直观地展示数据分布。在信号处理中,柱状图可以帮助工程师识别信号中的模式、趋势和异常情况,从而为信号分析和处理提供有价值的见解。 # 2. 柱状图在信号处理中的应用 柱状图在信号处理
recommend-type

用Spring boot和vue写一个登录注册界面

好的,这是一个比较常见的技术问题,我可以为您提供一些参考资料和思路。首先,您可以使用Spring Boot作为后端框架来处理用户认证和注册的逻辑,比如使用Spring Security实现用户登录认证。同时,您还需要设计相应的数据模型和数据库表结构来存储用户信息。在前端方面,您可以使用Vue.js作为框架来构建登录注册页面,使用Axios来发起API请求并和后端进行交互。当然,在实现过程中,还需要考虑一些具体细节,比如数据校验、安全性和用户体验等方面。希望这些信息能够帮助到您。
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。