www.gusucode.com > stats 源码程序 matlab案例代码 > stats/TrainANaiveBayesClassifierExample.m
%% Train a Naive Bayes Classifier %% % Load Fisher's iris data set. % Copyright 2015 The MathWorks, Inc. load fisheriris X = meas(:,3:4); Y = species; tabulate(Y) %% % The software can classify data with more than two classes % using naive Bayes methods. %% % Train a naive Bayes classifier. NBModel = fitNaiveBayes(X,Y) %% % |NBModel| is a trained |NaiveBayes| classifier. %% % By default, the software models the predictor distribution within each class % using a Gaussian distribution having some mean and standard deviation. Use % dot notation to display the parameters of a particular Gaussian fit, % e.g., display the fit for the first feature within |setosa|. setosaIndex = strcmp(NBModel.ClassLevels,'setosa'); estimates = NBModel.Params{setosaIndex,1} %% % The mean is |1.4620| and the standard deviation is |0.1737|. %% % Plot the Gaussian contours. figure gscatter(X(:,1),X(:,2),Y); h = gca; xylim = [h.XLim h.YLim]; hold on Params = cell2mat(NBModel.Params); Mu = Params(2*(1:3)-1,1:2); % Extracts the means Sigma = zeros(2,2,3); for j = 1:3 Sigma(:,:,j) = diag(Params(2*j,:)); % Extracts the standard deviations ezcontour(@(x1,x2)mvnpdf([x1,x2],Mu(j,:),Sigma(:,:,j)),... xylim+0.5*[-1,1,-1,1]) ... % Draws contours for the multivariate normal distributions end title('Naive Bayes Classifier -- Fisher''s Iris Data') xlabel('Petal Length (cm)') ylabel('Petal Width (cm)') hold off %% % You can change the default distribution using the name-value pair % argument |'Distribution'|. For example, If some predictors are count % based, then you can specify that they are multinomial random variables % using |'Distribution','mn'| .