www.gusucode.com > stats 源码程序 matlab案例代码 > stats/TrainAndCrossValidateNaiveBayesClassifiersExample.m

    %% Train and Cross Validate Naive Bayes Classifiers
%%
% Load the |ionosphere| data set.

% Copyright 2015 The MathWorks, Inc.

load ionosphere
X = X(:,3:end); % Remove two predictors for stability
%%
% Train and cross validate a naive Bayes classifier. Assume that each
% predictor is conditionally, normally distributed given its label. It is
% good practice to specify the order of the classes.
rng(1);  % For reproducibility
CVMdl = fitcnb(X,Y,'ClassNames',{'b','g'},'CrossVal','on')
%%
% |CVMdl| is not a |ClassificationNaiveBayes| model, but a
% |ClassificationPartitionedModel| cross-validated, naive Bayes model.  By
% default, the software implements 10-fold cross validation.
%%
% Alternatively, you can cross validate a trained |ClassificationNaiveBayes|
% model by passing it to <docid:stats_ug.budv6fi-1 crossval>.
%%
% Inspect one of the trained folds using dot notation.
CVMdl.Trained{1}
%%
% Each fold is a |CompactClassificationNaiveBayes| model trained on 90% of
% the data.
%%
% Estimate the generalization error.
genError = kfoldLoss(CVMdl)
%%
% On average, the generalization error is approximately 17%.
%%
% One way to attempt reducing an unsatisfactory generalization error is to
% specify different conditional distributions for the predictors, or tune
% the parameters of the conditional distributions.