【统计机器学习】决策树

题目

代码

CountEntropy.m

function [num1,num2,sum]=CountEntropy(index,n,mat,num)%index是索引,n是属性数,mat是原矩阵,num是可用数目
    sum=[0,0,0,0];%分别表示1的正、反例数,0的正、反例数
    len=length(num(:));
    num1=linspace(0,0,14);
    num2=linspace(0,0,14);
    for i=1:len
        if num(i)==0
            continue;
        end
        if mat(i,index)==1
            num1(i)=1;
            if mat(i,6)==1
                sum(1)=sum(1)+1;
            else
                sum(2)=sum(2)+1;
            end
        else
            num2(i)=1;
            if mat(i,6)==1
                sum(3)=sum(3)+1;
            else
                sum(4)=sum(4)+1;
            end
        end
    end

DepthSearch.m

function [node,array,ent,cnt,sum]=DepthSearch(mat,depth)
    nodenum=2.^depth-1;
    node=linspace(0,0,nodenum);
    array=zeros(nodenum,depth);%各节点祖先节点
    sum=zeros(nodenum,4);
    [m,n]=size(mat);
    ent=zeros(nodenum,4);%各节点信息熵
    cnt=ones(nodenum,m);%可用例
    for i=1:depth
        l=2.^(i-1);
        r=2.^i-1;
        for j=l:r
            for k=1:n-1
                c=find(array(j,:)==k);%查找是否存在
                if length(c)>0%若存在则跳过
                    continue;
                end
                [temp1,temp2,temp3]=CountEntropy(k,n-1,mat,cnt(j,:))
    
                curent=Entropy(temp3)
                if curent(end)>ent(j,4)
                    ent(j,:)=curent;
                    sum(j,:)=temp3;
                    array(j,i)=k;
                    if j*2<nodenum
                        
                        array(j*2,:)=array(j,:);
                        %array(j*2,i)=k;
                        array(j*2+1,:)=array(j,:);
                        %array(j*2+1,i)=k;
                        cnt(2*j,:)=temp2;
                        cnt(2*j+1,:)=temp1;
                    end
                end
            end
        end
    end
end

run.m

mat=[[1,1,0,0,1,1],
    [1,1,1,0,1,1],
    [0,0,1,0,0,0],
    [0,1,1,0,1,0],
    [0, 1, 1, 0, 0, 1],
    [0, 0, 1, 1, 1, 1],
    [1, 0, 0, 0, 1, 0],
    [0, 1, 0, 1, 1, 1],
    [0, 0, 1, 0, 1, 1],
    [1, 0, 0, 0, 0, 0],
    [1, 1, 1, 0, 0, 1],
    [0, 1, 1, 1, 1, 0],
    [0, 0, 0, 0, 1, 0],
    [1, 0, 0, 1, 0, 1],  
];
[a,b,c,d,e]=DepthSearch(mat,3)

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
青葱年少的头像青葱年少普通用户
上一篇 2022年5月26日
下一篇 2022年5月26日

相关推荐