文章目录
一、信息熵、条件熵、信息增益
1.信息熵
2.条件熵
3.信息增益
二、ID3算法及决策树
ID3算法只有树的生成,所以该算法生成的树容易产生过拟合。
ID3算法代码实现
# 数据使用统计特征方法上的贷款申请样本数据
import numpy as np
import operator
np.random.seed(0)
def loaddata():
dataSet = [[0, 0, 0, 0, 'no'],
[0, 0, 0, 1, 'no'],
[0, 1, 0, 1, 'yes'],
[0, 1, 1, 0, 'yes'],
[0, 0, 0, 0, 'no'],
[1, 0, 0, 0, 'no'],
[1, 0, 0, 1, 'no'],
[1, 1, 1, 1, 'yes'],
[1, 0, 1, 2, 'yes'],
[1, 0, 1, 2, 'yes'],
[2, 0, 1, 2, 'yes'],
[2, 0, 1, 1, 'yes'],
[2, 1, 0, 1, 'yes'],
[2, 1, 0, 2, 'yes'],
[2, 0, 0, 0, 'no']]
feature_name = ['age', 'job', 'house', 'credit']
return dataSet, feature_name
# 定义计算数据集的熵的函数
def entropy(dataSet):
# 数据量
m = len(dataSet)
# 标签不同类别的计数字典
labelCounts = {
}
# 循环数据集
for featVec in dataSet:
currentLabel = featVec[-1]
# 标签类别计数-如果字典中不存在则值为0,否则值加1
if currentLabel not in labelCounts.keys():
labelCounts[currentLabel] = 0
labelCounts[currentLabel] += 1
# 定义一个自变量来保存熵
e = 0.0
# 根据公式计算熵
for key in labelCounts:
prob = float(labelCounts[key]) / m
e -= prob * np.log2(prob)
return e