樸素貝葉斯學習筆記-matlab

clc
clear
close all

total_data=load('C:\Users\ZAN\Desktop\matalb_drive\machine-learnning\Bayes\iris_data.mat');
len = size(total_data.features,1);
rand_num=randperm(len);%disorder sequence
ratio=0.8;
train_num=ratio*len;
test_num=len-train_num;
data_mat = total_data.features(rand_num,:);%attribute
labels = total_data.classes(rand_num);%class labels

% normalization 
maxV = max(data_mat);
minV = min(data_mat);
range = maxV-minV;
newdataMat = (data_mat-repmat(minV,[len,1]))./(repmat(range,[len,1]));

newtrain_dataMat=newdataMat(1:train_num,:);
newtest_dataMat=newdataMat(train_num+1:end,:);
train_labels=labels(1:train_num);
test_labels=labels(train_num+1:end);
dataMat_1=newtrain_dataMat(find(train_labels==1),:);
dataMat_2=newtrain_dataMat(find(train_labels==2),:);
dataMat_3=newtrain_dataMat(find(train_labels==3),:);
%compute the mean and stdandard diviation of each class
mean_1=mean(dataMat_1);
std_1=std(dataMat_1);
mean_2=mean(dataMat_2);
std_2=std(dataMat_2);
mean_3=mean(dataMat_3);
std_3=std(dataMat_3);
right_pre=0;
for i=1:test_num
        prob_1=prod( normpdf(newtest_dataMat(i,:),mean_1,std_1) ,2);
        prob_2=prod( normpdf(newtest_dataMat(i,:),mean_2,std_2) ,2);
        prob_3=prod( normpdf(newtest_dataMat(i,:),mean_3,std_3) ,2);
        max_prob=max([prob_1,prob_2,prob_3]);
        if max_prob==prob_1
            pre_class=1;
        elseif max_prob==prob_2
            pre_class=2;
        else 
            pre_class=3;
        end
    fprintf('predict class is:%d  true result is:%d \n',[pre_class , test_labels(i)] );
    if pre_class == test_labels(i)
        right_pre=right_pre+1;
    end
   
end
 fprintf('the accuracy of the classifiter is:%d',right_pre/test_num);

最基本的樸素貝葉斯分類器,數據集用的鳶尾花數據集。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章