决策树算法中:根据信息增益选取下一个分类特征(python代码-算法面试)

Python实现基于信息增益选取样本分类特


def ent(dataSet):
    N=len(dataSet)
    n=defaultdict(int)
    ent = 0
    for i in range(N):
        n[dataSet[i][-1]] += 1
    for index, num in n.items():
        p = num/N


        ent -= p*math.log(p)
    return ent

def entCondition(dataSet,feature):
    n = defaultdict(list)
    N = len(dataSet)
    entConditon = 0
    for i in range(N):
        n[dataSet[i][feature]].append(dataSet[i])
    for _, data in n.items():
        q = len(data)/N
        entConditon+=q*ent(data)
    return entConditon

dataSet = [[1,1,1,1],[0,0,1,1],[1,1,0,0],[1,1,0,0]]
feature_num=len(dataSet[0])-1
N = len(dataSet)
best_feature=0
best_ent_increase=0
last_ent=ent(dataSet)
for i in range(feature_num):
    i_entCondtion = entCondition(dataSet, i)
    ent_increase=last_ent-i_entCondtion
    print(ent_increase)
    if ent_increase>best_ent_increase:
        best_ent_increase=ent_increase
        best_feature=i
print(best_feature)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值