naive Bayes example

%% using naive Bayes to solving my problem
%%h is health  ;  w is weather  ;  f is fruit  ;  e is exercise.
clear
a=[3,2,3,1;1,3,2,1;2,2,5,1;2,3,2,4;3,2,2,3;3,1,2,2;2,1,4,1;1,1,3,1;1,1,3,3;1,1,1,2;2,1,2,4;2,1,3,2;3,2,5,2;2,1,3,2;3,1,3,4;3,2,4,4;2,2,4,2;2,2,2,1;2,1,2,2;3,2,1,2;2,1,1,2;3,2,2,1;3,2,2,2;3,1,1,3;3,2,5,1;2,2,5,1;3,3,5,2;3,2,5,3;3,1,2,4;1,1,5,3;1,1,5,2;1,2,4,3;1,1,3,2;1,3,4,2;2,1,5,3;1,2,4,4;3,2,3,4;2,1,5,2;2,1,5,1;2,2,5,2;1,2,5,3;1,1,5,2;1,1,3,3;1,1,3,5;1,1,2,4;1,1,1,3;1,1,2,3;1,1,5,2;1,1,5,2;1,2,4,3;2,1,4,5;2,1,3,3;2,1,3,5;2,1,1,5;3,1,1,3;2,1,1,2;1,1,1,2;1,1,1,3;1,2,4,4;1,1,1,3;1,1,1,3;1,1,2,5;1,2,3,4;1,1,2,3;1,1,2,3;1,1,2,4;1,1,1,4;1,1,1,5;1,1,1,4;1,1,1,4;2,2,1,4;1,2,2,3;2,2,1,5;2,2,2,3];
n=length(a);
rank_h=5;
rank_w=3;
rank_f=3;
rank_e=5;
%% P(h_j)
for j=1:rank_h
    p=0;
    for i=1:n
        if a(i,4)==j
           p=p+1;
        end
    end
    h(j)=p;%%the sum of health 1~5 respectively
    ph(j)=p/n;%%the probability of health 1~5 
end


%% P(w_i|h_j)
 for i=1:rank_w   %the rank of weather 1~3
    for j=1:rank_h      
        t=find(a(:,4)==j);%find the rows of h_j 
        sum_h=length(t);%%sum_h is equal to h(k)
         p=0;
         for k=1:sum_h
         if a(t(k),1)==i%calculate the sum of w_i in h_jthe first column
             p=p+1;
         end
         end
        pw_h(i,j)=(p+1)/(sum_h+3);%laplace smooth +rank3
%         pw_h(i,j)=(p+0.01)/(sum_h+0.03);
    end
 end


%% P(f_i|h_j)
 for i=1:rank_f %the rank of fruit 1~3
    for j=1:rank_h      
        t=find(a(:,4)==j);%find the rows of h_j 
        sum_h=length(t);%%sum_h is equal to h(k)
         p=0;
         for k=1:sum_h
         if a(t(k),2)==i%calculate the sum of w_i in h_jthe second column
             p=p+1;
         end
         end
        pf_h(i,j)=(p+1)/(sum_h+3);
%         pf_h(i,j)=(p+0.01)/(sum_h+0.03);
    end
end
        
%% P(e_i|h_j)
 for i=1:rank_e %the rank of excerice 1~5
    for j=1:rank_h      
        t=find(a(:,4)==j);%find the rows of h_j 
        sum_h=length(t);%%sum_h is equal to h(k)
         p=0;
         for k=1:sum_h
         if a(t(k),3)==i%calculate the sum of w_i in h_jthe second column
             p=p+1;
         end
         end
        pe_h(i,j)=(p+1)/(sum_h+5);%laplace smooth +rank5
%         pe_h(i,j)=(p+0.01)/(sum_h+0.05);
    end
end
        
         ph
         pw_h
         pf_h
         pe_h
%% Predict
b=a(:,1:3);
n=length(b);
for i=1:n
    for j=1:5
       predict_h(j)= ph(j)*pw_h(b(i,1),j)*pf_h(b(i,2),j)*pe_h(b(i,3),j);
    end
   b(i,4)=find(predict_h==max(predict_h));
end
    length(find(a(:,4)==b(:,4)))/n*100
         
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值