一:数据集准备

如博主使用的是:

多层感知机(MLP)实现考勤预测二分类任务(sklearn)对应数据集

导入至工程下

Python实现计算信息熵的示例代码

二:信息熵计算

1 导包

from math import log
import pandas as pd

2 读取数据集

dataSet = pd.read_csv('dataSet.csv', header=None).values.tolist()

3 数据统计

numEntries = len(dataSet)  # 数据集大小
    labelCounts = {}
    for featVec in dataSet:  #
        currentLabel = featVec[-1]  # 获取分类标签
        if currentLabel not in labelCounts.keys(): labelCounts[currentLabel] = 0  # 字典值不等于0???
        labelCounts[currentLabel] += 1  # 每个类中数据个数统计

4 信息熵计算

    infoEnt = 0.0
    for key in labelCounts:  # 信息熵计算
        prob = float(labelCounts[key]) / numEntries
        infoEnt -= prob * log(prob, 2)
 
    return infoEnt
    # 返回值 infoEnt 为数据集的信息熵,表示为 float 类型

测试运行,得到 多层感知机(MLP)实现考勤预测二分类任务(sklearn)对应数据集  信息熵为0.5563916622348017

Python实现计算信息熵的示例代码

三:完整源码分享

from math import log
import pandas as pd
 
dataSet = pd.read_csv('dataSet.csv', header=None).values.tolist()
 
 
def calcInfoEnt(dataSet):
    numEntries = len(dataSet)  # 数据集大小
    labelCounts = {}
    for featVec in dataSet:  #
        currentLabel = featVec[-1]  # 获取分类标签
        if currentLabel not in labelCounts.keys(): labelCounts[currentLabel] = 0  # 字典值不等于0???
        labelCounts[currentLabel] += 1  # 每个类中数据个数统计
    infoEnt = 0.0
    for key in labelCounts:  # 信息熵计算
        prob = float(labelCounts[key]) / numEntries
        infoEnt -= prob * log(prob, 2)
 
    return infoEnt
    # 返回值 infoEnt 为数据集的信息熵,表示为 float 类型
 
 
if __name__ == '__main__':
    # 输出为当前数据集的信息熵
    print(calcInfoEnt(dataSet))
原文地址:https://blog.csdn.net/m0_56051805/article/details/128429532

相关文章:

  • 2021-10-01
  • 2022-12-23
  • 2023-03-09
  • 2021-09-11
  • 2021-06-06
猜你喜欢
  • 2021-10-07
  • 2021-07-27
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2023-02-15
  • 2023-03-19
相关资源
相似解决方案