决策树中熵、条件熵、信息增益及信息增益比的python实现

简介: 决策树中熵、条件熵、信息增益及信息增益比的python实现

有关熵、条件熵、信息增益及信息增益比的概念可以在网上搜索或者在博客:决策树 Decision Tree 上查看


假设我们有一份CSV文件(以部分为例):car.csv


0a2653c851af460fa595bd959398a8f1.png


其中我们把最后一列视为标签,其余列视为特征计算其熵、条件熵、信息增益及信息增益比:


import numpy as np
import pandas as pd
import math
class InformationGain():
    def __init__(self, feature, label):
        feature = np.array(feature)
        num_of_feature = np.shape(feature)[1]
        num_of_label = len(label)
        temp_ent = 0
        temp_condition_ent = 0
        information_gain_ratio = 0
        shanno_ent = []
        condition_ent = []
        information_gain_list = []
        information_gain_ratio_list = []
        for i in set(label):
            temp_ent += -(label.count(i) / num_of_label) * math.log(label.count(i) / num_of_label)
        for i in range(num_of_feature):
            feature1 = feature[:, i]
            sorted_feature = sorted(feature1)
            threshold = [(sorted_feature[inde - 1] + sorted_feature[inde]) / 2 for inde in range(len(feature1)) if
                         inde != 0]
            thre_set = set(threshold)
            if float(max(feature1)) in thre_set:
                thre_set.remove(float(max(feature1)))
            if min(feature1) in thre_set:
                thre_set.remove(min(feature1))
            information_gain = 0
            for thre in thre_set:
                lower = [label[s] for s in range(len(feature1)) if feature1[s] < thre]
                highter = [label[s] for s in range(len(feature1)) if feature1[s] > thre]
                H_l = 0
                for l in set(lower):
                    H_l += -(lower.count(l) / len(lower)) * math.log(lower.count(l) / len(lower))
                H_h = 0
                for h in set(highter):
                    H_h += -(highter.count(h) / len(highter)) * math.log(highter.count(h) / len(highter))
                temp_condition_ent = len(lower) / num_of_label * H_l + len(highter) / num_of_label * H_h
                gain = temp_ent - temp_condition_ent
                information_gain = max(information_gain, gain)
                information_gain_ratio = information_gain / temp_ent
            shanno_ent.append(temp_ent)
            condition_ent.append(temp_condition_ent)
            information_gain_list.append(information_gain)
            information_gain_ratio_list.append(information_gain_ratio)
        self.shannoEnt = shanno_ent[0]
        self.conditionEnt = condition_ent
        self.InformationGain = information_gain_list
        self.InformationGainRatio = information_gain_ratio_list
    def getEnt(self):
        return self.shannoEnt
    def getConditionEnt(self):
        return self.conditionEnt
    def getInformationGain(self):
        return self.InformationGain
    def getInformationGainRatio(self):
        return self.InformationGainRatio
def read_dataset(fname = u"/car.csv"):
    data = pd.read_csv(fname, index_col=0,encoding="utf-8",nrows=300)
    data = data.fillna(0)
    temp_col_list = ["",""] # ""中填特征的列名
    for i in temp_col_list:
        lables = data[i].unique().tolist()
        data[i] = data[i].apply(lambda n: lables.index(n))
    return data
train = read_dataset()
# ""中填标签的列名
y = train[""].values.tolist()
X = train.drop([""], axis=1).values.tolist()
print(InformationGain(X, y).getEnt())
print(InformationGain(X, y).getConditionEnt())
print(InformationGain(X, y).getInformationGain())
print(InformationGain(X, y).getInformationGainRatio())


输出:


[0.5004024235381879, 0.5004024235381879, 0.5004024235381879, 0.5004024235381879, 0.5004024235381879, 0.5004024235381879, 0.5004024235381879, 0.5004024235381879, 0.5004024235381879, 0.5004024235381879, 0.5004024235381879, 0.5004024235381879, 0.5004024235381879, 0.5004024235381879, 0.5004024235381879, 0.5004024235381879, 0.5004024235381879, 0.5004024235381879, 0.5004024235381879, 0.5004024235381879, 0.5004024235381879, 0.5004024235381879, 0.5004024235381879, 0.5004024235381879, 0.5004024235381879]
[0.47402237066078146, 0.4974047292018396, 0.5003219957256428, 0.01700877327081982, 0.49501525883766634, 0.4849811557452448, 0.48958274254946765, 0.49965721932952717, 0.49965721932952717, 0.49890921637157837, 0.496769162198576, 0.49890921637157837, 0.49570780362218425, 0.49965721932952717, 0.5003025880631119, 0.4983744219282678, 0.49888633644322344, 0.5001635072186842, 0.4895266089201389, 0.4965707224581661, 0.4857229010143407, 0.5003025880631119, 0.4975942392452718, 0.49965721932952717, 0.49965721932952717]
[0.19328787090455724, 0.03982075923669709, 0.016307095137454486, 0.483393650267368, 0.483393650267368, 0.03869166516981126, 0.03440958975003933, 0.04275228841357964, 0.04193841009210453, 0.23089594240377442, 0.019548136350570233, 0.07962341285100738, 0.004694619916003617, 0.09934963217845783, 0.36824744710714663, 0.0020280016099200604, 0.32361566193699254, 0.03647188721007644, 0.010875814618048985, 0.0038317010800217877, 0.014679522523847188, 0.2609054406254804, 0.08540895349851685, 0.06672032313842502, 0.007831909930446801]
[0.3862648576677139, 0.07957747077869258, 0.032587961949009266, 0.9660098103631151, 0.9660098103631151, 0.07732109867940824, 0.06876383512841516, 0.08543581406199371, 0.0838093664606403, 0.46142051185760047, 0.03906483148573007, 0.15911875943368803, 0.009381689007038454, 0.19853947044458314, 0.7359026051540377, 0.004052741382786878, 0.6467108205607962, 0.07288511305000327, 0.021734136579814156, 0.007657239253417353, 0.0293354345089956, 0.5213912410349658, 0.17068053526722962, 0.13333333333333328, 0.015651223019804407]


相关文章
|
存储 算法 API
【01】整体试验思路,如何在有UID的情况下获得用户手机号信息,python开发之理论研究试验,如何通过抖音视频下方的用户的UID获得抖音用户的手机号-本系列文章仅供学习研究-禁止用于任何商业用途-仅供学习交流-优雅草卓伊凡
【01】整体试验思路,如何在有UID的情况下获得用户手机号信息,python开发之理论研究试验,如何通过抖音视频下方的用户的UID获得抖音用户的手机号-本系列文章仅供学习研究-禁止用于任何商业用途-仅供学习交流-优雅草卓伊凡
6546 82
|
数据采集 数据可视化 API
驱动业务决策:基于Python的App用户行为分析与可视化方案
驱动业务决策:基于Python的App用户行为分析与可视化方案
|
API Python
VIN码查询API的实战指南:获取二手车信息以Python为例
随着机动车保有量上升,中国二手车市场迎来发展机遇。本文介绍如何通过VIN码查询API获取车辆详细信息,提升交易透明度与安全性。
683 1
|
存储 监控 API
【Azure App Service】分享使用Python Code获取App Service的服务器日志记录管理配置信息
本文介绍了如何通过Python代码获取App Service中“Web服务器日志记录”的配置状态。借助`azure-mgmt-web` SDK,可通过初始化`WebSiteManagementClient`对象、调用`get_configuration`方法来查看`http_logging_enabled`的值,从而判断日志记录是否启用及存储方式(关闭、存储或文件系统)。示例代码详细展示了实现步骤,并附有执行结果与官方文档参考链接,帮助开发者快速定位和解决问题。
502 22
|
前端开发 数据安全/隐私保护 Python
虚拟物流单号生成器, 虚拟快递单号假物流信息, 虚拟快递单号在线生成【python框架】
这个虚拟物流单号生成系统包含以下功能:支持多种主流快递公司的单号生成
|
数据安全/隐私保护 数据格式 Python
快递单号模拟生成器, 虚拟物流信息在线生成,虚假快递单号生成器【python】
支持多种主流快递公司生成符合各快递公司规则的快递单号自动生成收发件人信息
|
JSON 前端开发 API
快递单号生成器在线, 快递单号模拟生成器, 虚拟物流信息在线生成【python】
项目包含三个主要模块:快递单号生成器核心逻辑、Flask Web应用程序和前端HTML页面
|
JSON API 数据安全/隐私保护
车辆五项信息查询 API 的实践指南:通过Python调用赋能车辆信息标准化
本API通过车牌号快速获取车辆五项核心信息,包括品牌、登记日期、车架号等,助力二手车评估、维修、保险等场景实现数字化转型。数据源自权威公安交管库,日更同步,毫秒级响应,满足高并发需求,符合隐私保护规范,是推动汽车后市场智能化的重要工具。
1087 0
|
算法 Java Python
使用Python来绘制樱花树
本文以林徽因的《你是人间的四月天》为引,将春日意象与现代职场编程艺术结合,通过Python的Turtle模块绘制分形树和花瓣图案。文章详细解析了Turtle模块的使用方法、递归算法及随机性在图形生成中的应用,展示了如何用代码创造自然美感。核心代码包含tree函数(绘制分形树)和petal函数(绘制花瓣),最终生成一幅生动的春日画卷。项目不仅帮助读者掌握Turtle绘图技巧,更激发对编程艺术的兴趣,鼓励探索数字世界的无限可能。
598 5
|
数据采集 存储 数据可视化
Python爬取招标信息并生成可视化分析报告
Python爬取招标信息并生成可视化分析报告

推荐镜像

更多