Python3 机器学习之计算香农熵
2023-09-11 14:18:32 时间
Python3 机器学习之计算香农熵
from math import log
# 函数说明:计算给定数据集的经验熵(香农熵)
def calcShannonEnt(dataSet):
numEntires = len(dataSet) #返回数据集的行数
labelCounts = {} #保存每个标签(Label)出现次数的字典
for featVec in dataSet: #对每组特征向量进行统计
currentLabel = featVec[-1] #提取标签(Label)信息
if currentLabel not in labelCounts.keys(): #如果标签(Label)没有放入统计次数的字典,添加进去
labelCounts[currentLabel] = 0
labelCounts[currentLabel] += 1 #Label计数
shannonEnt = 0.0 #经验熵(香农熵)
for key in labelCounts: #计算香农熵
prob = float(labelCounts[key]) / numEntires #选择该标签(Label)的概率
shannonEnt -= prob * log(prob, 2) #利用公式计算
return shannonEnt #返回经验熵(香农熵)
相关文章
- 【Python3网络爬虫开发实战】1.4.2-MongoDB安装
- 【Python3网络爬虫开发实战】1.2.1-Requests的安装
- python3以post方式提交数据
- Centos7安装Python3并更改默认版本为python3(编译安装)
- Python3字符串填充和对齐代码示例
- Python3 安装PyMySQL
- Python3 函数(方法)
- Python3运算符优先级
- Python语言学习:解决python版本升级问题集合(python2系列→Python3系列)导致错误的总结集合
- 【LeetCode 中等 链表 python3】2. 两数相加
- windows上安装python2和python3虚拟环境
- macOS python3 opencv PIL.Image 二值化图像
- python3 selenium chrome headless 无界面浏览器