MathWorks Machine Translation
The automated translation of this page is provided by a general purpose third party translator tool.
MathWorks does not warrant, and disclaims all liability for, the accuracy, suitability, or fitness for purpose of the translation.
Train multiclass naive Bayes model
Mdl = fitcnb(Tbl,ResponseVarName)
Mdl = fitcnb(Tbl,formula)
Mdl = fitcnb(Tbl,Y)
Mdl = fitcnb(X,Y)
Mdl = fitcnb(___,Name,Value)
returns
a multiclass naive Bayes model (Mdl
= fitcnb(Tbl
,ResponseVarName
)Mdl
), trained
by the predictors in table Tbl
and class labels
in the variable Tbl.ResponseVarName
.
returns
a naive Bayes classifier with additional options specified by one
or more Mdl
= fitcnb(___,Name,Value
)Name,Value
pair arguments, using any
of the previous syntaxes. For example, you can specify a distribution
to model the data, prior probabilities for the classes, or the kernel
smoothing window bandwidth.
Load Fisher's iris data set.
load fisheriris
X = meas(:,3:4);
Y = species;
tabulate(Y)
Value Count Percent setosa 50 33.33% versicolor 50 33.33% virginica 50 33.33%
The software can classify data with more than two classes using naive Bayes methods.
Train a naive Bayes classifier. It is good practice to specify the class order.
Mdl = fitcnb(X,Y,... 'ClassNames',{'setosa','versicolor','virginica'})
Mdl = ClassificationNaiveBayes ResponseName: 'Y' CategoricalPredictors: [] ClassNames: {'setosa' 'versicolor' 'virginica'} ScoreTransform: 'none' NumObservations: 150 DistributionNames: {'normal' 'normal'} DistributionParameters: {3x2 cell} Properties, Methods
Mdl
is a trained ClassificationNaiveBayes
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(Mdl.ClassNames,'setosa');
estimates = Mdl.DistributionParameters{setosaIndex,1}
estimates = 2×1
1.4620
0.1737
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; cxlim = h.XLim; cylim = h.YLim; hold on Params = cell2mat(Mdl.DistributionParameters); Mu = Params(2*(1:3)1,1:2); % Extract the means Sigma = zeros(2,2,3); for j = 1:3 Sigma(:,:,j) = diag(Params(2*j,:)).^2; % Create diagonal covariance matrix xlim = Mu(j,1) + 4*[1 1]*sqrt(Sigma(1,1,j)); ylim = Mu(j,2) + 4*[1 1]*sqrt(Sigma(2,2,j)); f = @(x1,x2)reshape(mvnpdf([x1(:),x2(:)],Mu(j,:),Sigma(:,:,j)),size(x1)); fcontour(f,[xlim ylim]) % Draw contours for the multivariate normal distributions end h.XLim = cxlim; h.YLim = cylim; title('Naive Bayes Classifier  Fisher''s Iris Data') xlabel('Petal Length (cm)') ylabel('Petal Width (cm)') legend('setosa','versicolor','virginica') hold off
You can change the default distribution using the namevalue pair argument 'DistributionNames'
. For example, if some predictors are categorical, then you can specify that they are multivariate, multinomial random variables using 'DistributionNames','mvmn'
.
Construct a naive Bayes classifier for Fisher's iris data set. Also, specify prior probabilities during training.
Load Fisher's iris data set.
load fisheriris X = meas; Y = species; classNames = {'setosa','versicolor','virginica'}; % Class order
X
is a numeric matrix that contains four petal measurements for 150 irises. Y
is a cell array of character vectors that contains the corresponding iris species.
By default, the prior class probability distribution is the relative frequency distribution of the classes in the data set, which in this case is 33% for each species. However, suppose you know that in the population 50% of the irises are setosa, 20% are versicolor, and 30% are virginica. You can incorporate this information by specifying this distribution as a prior probability during training.
Train a naive Bayes classifier. Specify the class order and prior class probability distribution.
prior = [0.5 0.2 0.3]; Mdl = fitcnb(X,Y,'ClassNames',classNames,'Prior',prior)
Mdl = ClassificationNaiveBayes ResponseName: 'Y' CategoricalPredictors: [] ClassNames: {'setosa' 'versicolor' 'virginica'} ScoreTransform: 'none' NumObservations: 150 DistributionNames: {'normal' 'normal' 'normal' 'normal'} DistributionParameters: {3x4 cell} Properties, Methods
Mdl
is a trained ClassificationNaiveBayes
classifier, and some of its properties appear in the Command Window. The software treats the predictors as independent given a class, and, by default, fits them using normal distributions.
The naive Bayes algorithm does not use the prior class probabilities during training. Therefore, you can specify prior class probabilities after training using dot notation. For example, suppose that you want to see the difference in performance between a model that uses the default prior class probabilities and a model that uses prior
.
Create a new naive Bayes model based on Mdl
, and specify that the prior class probability distribution is an empirical class distribution.
defaultPriorMdl = Mdl; FreqDist = cell2table(tabulate(Y)); defaultPriorMdl.Prior = FreqDist{:,3};
The software normalizes the prior class probabilities to sum to 1
.
Estimate the crossvalidation error for both models using 10fold crossvalidation.
rng(1); % For reproducibility
defaultCVMdl = crossval(defaultPriorMdl);
defaultLoss = kfoldLoss(defaultCVMdl)
defaultLoss = 0.0533
CVMdl = crossval(Mdl); Loss = kfoldLoss(CVMdl)
Loss = 0.0340
Mdl
performs better than defaultPriorMdl
.
Load Fisher's iris data set.
load fisheriris
X = meas;
Y = species;
Train a naive Bayes classifier using every predictor. It is good practice to specify the class order.
Mdl1 = fitcnb(X,Y,... 'ClassNames',{'setosa','versicolor','virginica'})
Mdl1 = ClassificationNaiveBayes ResponseName: 'Y' CategoricalPredictors: [] ClassNames: {'setosa' 'versicolor' 'virginica'} ScoreTransform: 'none' NumObservations: 150 DistributionNames: {'normal' 'normal' 'normal' 'normal'} DistributionParameters: {3x4 cell} Properties, Methods
Mdl1.DistributionParameters
ans = 3x4 cell array
{2x1 double} {2x1 double} {2x1 double} {2x1 double}
{2x1 double} {2x1 double} {2x1 double} {2x1 double}
{2x1 double} {2x1 double} {2x1 double} {2x1 double}
Mdl1.DistributionParameters{1,2}
ans = 2×1
3.4280
0.3791
By default, the software models the predictor distribution within each class as a Gaussian with some mean and standard deviation. There are four predictors and three class levels. Each cell in Mdl1.DistributionParameters
corresponds to a numeric vector containing the mean and standard deviation of each distribution, e.g., the mean and standard deviation for setosa iris sepal widths are 3.4280
and 0.3791
, respectively.
Estimate the confusion matrix for Mdl1
.
isLabels1 = resubPredict(Mdl1); ConfusionMat1 = confusionchart(Y,isLabels1);
Element (j, k) of the confusion matrix chart represents the number of observations that the software classifies as k, but are truly in class j according to the data.
Retrain the classifier using the Gaussian distribution for predictors 1 and 2 (the sepal lengths and widths), and the default normal kernel density for predictors 3 and 4 (the petal lengths and widths).
Mdl2 = fitcnb(X,Y,... 'DistributionNames',{'normal','normal','kernel','kernel'},... 'ClassNames',{'setosa','versicolor','virginica'}); Mdl2.DistributionParameters{1,2}
ans = 2×1
3.4280
0.3791
The software does not train parameters to the kernel density. Rather, the software chooses an optimal width. However, you can specify a width using the 'Width'
namevalue pair argument.
Estimate the confusion matrix for Mdl2
.
isLabels2 = resubPredict(Mdl2); ConfusionMat2 = confusionchart(Y,isLabels2);
Based on the confusion matrices, the two classifiers perform similarly in the training sample.
Load Fisher's iris data set.
load fisheriris X = meas; Y = species; rng(1); % For reproducibility
Train and crossvalidate a naive Bayes classifier using the default options and kfold crossvalidation. It is good practice to specify the class order.
CVMdl1 = fitcnb(X,Y,... 'ClassNames',{'setosa','versicolor','virginica'},... 'CrossVal','on');
By default, the software models the predictor distribution within each class as a Gaussian with some mean and standard deviation. CVMdl1
is a ClassificationPartitionedModel
model.
Create a default naive Bayes binary classifier template, and train an errorcorrecting, output codes multiclass model.
t = templateNaiveBayes(); CVMdl2 = fitcecoc(X,Y,'CrossVal','on','Learners',t);
CVMdl2
is a ClassificationPartitionedECOC
model. You can specify options for the naive Bayes binary learners using the same namevalue pair arguments as for fitcnb
.
Compare the outofsample kfold classification error (proportion of misclassified observations).
classErr1 = kfoldLoss(CVMdl1,'LossFun','ClassifErr')
classErr1 = 0.0533
classErr2 = kfoldLoss(CVMdl2,'LossFun','ClassifErr')
classErr2 = 0.0467
Mdl2
has a lower generalization error.
Some spam filters classify an incoming email as spam based on how many times a word or punctuation (called tokens) occurs in an email. The predictors are the frequencies of particular words or punctuations in an email. Therefore, the predictors compose multinomial random variables.
This example illustrates classification using naive Bayes and multinomial predictors.
Create Training Data
Suppose you observed 1000 emails and classified them as spam or not spam. Do this by randomly assigning 1 or 1 to y
for each email.
n = 1000; % Sample size rng(1); % For reproducibility Y = randsample([1 1],n,true); % Random labels
To build the predictor data, suppose that there are five tokens in the vocabulary, and 20 observed tokens per email. Generate predictor data from the five tokens by drawing random, multinomial deviates. The relative frequencies for tokens corresponding to spam emails should differ from emails that are not spam.
tokenProbs = [0.2 0.3 0.1 0.15 0.25;... 0.4 0.1 0.3 0.05 0.15]; % Token relative frequencies tokensPerEmail = 20; % Fixed for convenience X = zeros(n,5); X(Y == 1,:) = mnrnd(tokensPerEmail,tokenProbs(1,:),sum(Y == 1)); X(Y == 1,:) = mnrnd(tokensPerEmail,tokenProbs(2,:),sum(Y == 1));
Train the Classifier
Train a naive Bayes classifier. Specify that the predictors are multinomial.
Mdl = fitcnb(X,Y,'DistributionNames','mn');
Mdl
is a trained ClassificationNaiveBayes
classifier.
Assess the insample performance of Mdl
by estimating the misclassification error.
isGenRate = resubLoss(Mdl,'LossFun','ClassifErr')
isGenRate = 0.0200
The insample misclassification rate is 2%.
Create New Data
Randomly generate deviates that represent a new batch of emails.
newN = 500; newY = randsample([1 1],newN,true); newX = zeros(newN,5); newX(newY == 1,:) = mnrnd(tokensPerEmail,tokenProbs(1,:),... sum(newY == 1)); newX(newY == 1,:) = mnrnd(tokensPerEmail,tokenProbs(2,:),... sum(newY == 1));
Assess Classifier Performance
Classify the new emails using the trained naive Bayes classifier Mdl
, and determine whether the algorithm generalizes.
oosGenRate = loss(Mdl,newX,newY)
oosGenRate = 0.0261
The outofsample misclassification rate is 2.6% indicating that the classifier generalizes fairly well.
This example shows how to use the OptimizeHyperparameters
namevalue pair to minimize crossvalidation loss in a naive Bayes classifier using fitcnb
. The example uses Fisher's iris data.
Load Fisher's iris data.
load fisheriris X = meas; Y = species; classNames = {'setosa','versicolor','virginica'};
Optimize the classification using the 'auto' parameters.
For reproducibility, set the random seed and use the 'expectedimprovementplus'
acquisition function.
rng default Mdl = fitcnb(X,Y,'ClassNames',classNames,'OptimizeHyperparameters','auto',... 'HyperparameterOptimizationOptions',struct('AcquisitionFunctionName',... 'expectedimprovementplus'))
Warning: It is recommended that you first standardize all numeric predictors when optimizing the Naive Bayes 'Width' parameter. Ignore this warning if you have done that.
=====================================================================================================  Iter  Eval  Objective  Objective  BestSoFar  BestSoFar  Distribution Width    result   runtime  (observed)  (estim.)  Names   =====================================================================================================  1  Best  0.053333  0.97778  0.053333  0.053333  normal     2  Best  0.046667  0.93806  0.046667  0.049998  kernel  0.11903   3  Accept  0.053333  0.25921  0.046667  0.046667  normal     4  Accept  0.086667  0.7748  0.046667  0.046668  kernel  2.4506   5  Accept  0.046667  0.67447  0.046667  0.046663  kernel  0.10449   6  Accept  0.073333  1.0916  0.046667  0.046665  kernel  0.025044   7  Accept  0.046667  0.76329  0.046667  0.046655  kernel  0.27647   8  Accept  0.046667  0.84405  0.046667  0.046647  kernel  0.2031   9  Accept  0.06  0.82149  0.046667  0.046658  kernel  0.44271   10  Accept  0.046667  1.2658  0.046667  0.046618  kernel  0.2412   11  Accept  0.046667  1.2609  0.046667  0.046619  kernel  0.071925   12  Accept  0.046667  0.72656  0.046667  0.046612  kernel  0.083459   13  Accept  0.046667  1.5018  0.046667  0.046603  kernel  0.15661   14  Accept  0.046667  1.1362  0.046667  0.046607  kernel  0.25613   15  Accept  0.046667  0.7071  0.046667  0.046606  kernel  0.17776   16  Accept  0.046667  1.1039  0.046667  0.046606  kernel  0.13632   17  Accept  0.046667  0.81257  0.046667  0.046606  kernel  0.077598   18  Accept  0.046667  0.61019  0.046667  0.046626  kernel  0.25646   19  Accept  0.046667  1.1751  0.046667  0.046626  kernel  0.093584   20  Accept  0.046667  1.6979  0.046667  0.046627  kernel  0.061602  =====================================================================================================  Iter  Eval  Objective  Objective  BestSoFar  BestSoFar  Distribution Width    result   runtime  (observed)  (estim.)  Names   =====================================================================================================  21  Accept  0.046667  0.59446  0.046667  0.046627  kernel  0.066532   22  Accept  0.093333  0.45766  0.046667  0.046618  kernel  5.8968   23  Accept  0.046667  0.64292  0.046667  0.046619  kernel  0.067045   24  Accept  0.046667  0.55548  0.046667  0.04663  kernel  0.25281   25  Accept  0.046667  0.51658  0.046667  0.04663  kernel  0.1473   26  Accept  0.046667  0.56157  0.046667  0.046631  kernel  0.17211   27  Accept  0.046667  0.70347  0.046667  0.046631  kernel  0.12457   28  Accept  0.046667  0.67667  0.046667  0.046631  kernel  0.066659   29  Accept  0.046667  0.75186  0.046667  0.046631  kernel  0.1081   30  Accept  0.08  0.73588  0.046667  0.046628  kernel  1.1048  __________________________________________________________ Optimization completed. MaxObjectiveEvaluations of 30 reached. Total function evaluations: 30 Total elapsed time: 112.7679 seconds. Total objective function evaluation time: 25.3393 Best observed feasible point: DistributionNames Width _________________ _______ kernel 0.11903 Observed objective function value = 0.046667 Estimated objective function value = 0.046628 Function evaluation time = 0.93806 Best estimated feasible point (according to models): DistributionNames Width _________________ _______ kernel 0.25613 Estimated objective function value = 0.046628 Estimated function evaluation time = 0.7889
Mdl = ClassificationNaiveBayes ResponseName: 'Y' CategoricalPredictors: [] ClassNames: {'setosa' 'versicolor' 'virginica'} ScoreTransform: 'none' NumObservations: 150 HyperparameterOptimizationResults: [1x1 BayesianOptimization] DistributionNames: {1x4 cell} DistributionParameters: {3x4 cell} Kernel: {1x4 cell} Support: {1x4 cell} Width: [3x4 double] Properties, Methods
Tbl
— Sample dataSample data used to train the model, specified as a table. Each row of Tbl
corresponds to one observation, and each column corresponds to one predictor variable.
Optionally, Tbl
can contain one additional column for the response
variable. Multicolumn variables and cell arrays other than cell arrays of character
vectors are not allowed.
If Tbl
contains the response variable, and you want to use all remaining
variables in Tbl
as predictors, then specify the response variable by
using ResponseVarName
.
If Tbl
contains the response variable, and you want to use only a subset of
the remaining variables in Tbl
as predictors, then specify a formula
by using formula
.
If Tbl
does not contain the response variable, then specify a response
variable by using Y
. The length of the response variable and the
number of rows in Tbl
must be equal.
Data Types: table
ResponseVarName
— Response variable nameTbl
Response variable name, specified as the name of a variable in
Tbl
.
You must specify ResponseVarName
as a character vector or string scalar.
For example, if the response variable Y
is
stored as Tbl.Y
, then specify it as
'Y'
. Otherwise, the software
treats all columns of Tbl
, including
Y
, as predictors when training
the model.
The response variable must be a categorical, character, or string array, logical or numeric
vector, or cell array of character vectors. If
Y
is a character array, then each
element of the response variable must correspond to one row of
the array.
It is a good practice to specify the order of the classes by using the
ClassNames
namevalue pair argument.
Data Types: char
 string
formula
— Explanatory model of response and subset of predictor variablesExplanatory model of the response and a subset of the predictor variables, specified as a
character vector or string scalar in the form 'Y~X1+X2+X3'
. In this
form, Y
represents the response variable, and X1
,
X2
, and X3
represent the predictor variables.
The variables must be variable names in Tbl
(Tbl.Properties.VariableNames
).
To specify a subset of variables in Tbl
as
predictors for training the model, use a formula. If you specify a
formula, then the software does not use any variables in Tbl
that
do not appear in formula
.
Data Types: char
 string
Y
— Class labelsClass labels to which the naive Bayes classifier is trained, specified as a categorical,
character, or string array, a logical or numeric vector, or a cell array of character
vectors. Each element of Y
defines the class membership of the
corresponding row of X
. Y
supports
K class levels.
If Y
is a character array, then each row
must correspond to one class label.
The length of Y
and the number of rows of X
must
be equivalent.
Data Types: categorical
 char
 string
 logical
 single
 double
 cell
X
— Predictor dataPredictor data, specified as a numeric matrix.
Each row of X
corresponds to one observation
(also known as an instance or example), and each column corresponds
to one variable (also known as a feature).
The length of Y
and the number of rows of X
must
be equivalent.
Data Types: double
The software treats NaN
, empty character vector (''
),
empty string (""
), <missing>
, and
<undefined>
elements as missing data values.
If Y
contains missing values, then the software removes
them and the corresponding rows of X
.
If X
contains any rows composed entirely of missing values,
then the software removes those rows and the corresponding elements of
Y
.
If X
contains missing values and you set
'DistributionNames','mn'
, then the software removes those
rows of X
and the corresponding elements of
Y
.
If a predictor is not represented in a class, that is, if all of its values
are NaN
within a class, then the software returns an
error.
Removing rows of X
and corresponding elements of
Y
decreases the effective training or crossvalidation sample
size.
Specify optional
commaseparated pairs of Name,Value
arguments. Name
is
the argument name and Value
is the corresponding value.
Name
must appear inside quotes. You can specify several name and value
pair arguments in any order as
Name1,Value1,...,NameN,ValueN
.
'DistributionNames','mn','Prior','uniform','KSWidth',0.5
specifies that the data distribution is multinomial, the prior probabilities for all
classes are equal, and the kernel smoothing window bandwidth for all classes is
0.5
units.You cannot use any crossvalidation namevalue pair argument along with the
'OptimizeHyperparameters'
namevalue pair argument. You can modify
the crossvalidation for 'OptimizeHyperparameters'
only by using the
'HyperparameterOptimizationOptions'
namevalue pair
argument.
'DistributionNames'
— Data distributions'kernel'
 'mn'
 'mvmn'
 'normal'
 string array  cell array of character vectorsData distributions fitcnb
uses to model the data, specified as the
commaseparated pair consisting of 'DistributionNames'
and a
character vector or string scalar, a string array, or a cell array of character vectors
with values from this table.
Value  Description 

'kernel'  Kernel smoothing density estimate. 
'mn'  Multinomial distribution. If you specify mn ,
then all features are components of a multinomial distribution.
Therefore, you cannot include 'mn' as an element
of a string array or a cell array of character vectors. For details,
see Algorithms. 
'mvmn'  Multivariate multinomial distribution. For details, see Algorithms. 
'normal'  Normal (Gaussian) distribution. 
If you specify a character vector or string scalar, then the software models all the features using that distribution. If you specify a 1byP string array or cell array of character vectors, then the software models feature j using the distribution in element j of the array.
By default, the software sets all predictors specified as categorical
predictors (using the CategoricalPredictors
namevalue
pair argument) to 'mvmn'
. Otherwise, the default
distribution is 'normal'
.
You must specify that at least one predictor has distribution 'kernel'
to
additionally specify Kernel
, Support
,
or Width
.
Example: 'DistributionNames','mn'
Example: 'DistributionNames',{'kernel','normal','kernel'}
'Kernel'
— Kernel smoother type'normal'
(default)  'box'
 'epanechnikov'
 'triangle'
 string array  cell array of character vectorsKernel smoother type, specified as the commaseparated pair consisting of
'Kernel'
and a character vector or string scalar, a string array,
or a cell array of character vectors.
This table summarizes the available options for setting the kernel smoothing density region. Let I{u} denote the indicator function.
Value  Kernel  Formula 

'box'  Box (uniform) 
$$f(x)=0.5I\left\{\leftx\right\le 1\right\}$$ 
'epanechnikov'  Epanechnikov 
$$f(x)=0.75\left(1{x}^{2}\right)I\left\{\leftx\right\le 1\right\}$$ 
'normal'  Gaussian 
$$f(x)=\frac{1}{\sqrt{2\pi}}\mathrm{exp}\left(0.5{x}^{2}\right)$$ 
'triangle'  Triangular 
$$f(x)=\left(1\leftx\right\right)I\left\{\leftx\right\le 1\right\}$$ 
If you specify a 1byP string array or cell array, with each element of
the array containing any value in the table, then the software trains the classifier
using the kernel smoother type in element j for feature
j in X
. The software ignores elements of
Kernel
not corresponding to a predictor whose distribution is
'kernel'
.
You must specify that at least one predictor has distribution 'kernel'
to
additionally specify Kernel
, Support
,
or Width
.
Example: 'Kernel',{'epanechnikov','normal'}
'Support'
— Kernel smoothing density support'unbounded'
(default)  'positive'
 string array  cell array  numeric row vectorKernel smoothing density support, specified as the commaseparated pair consisting of
'Support'
and 'positive'
,
'unbounded'
, a string array, a cell array, or a numeric row
vector. The software applies the kernel smoothing density to the specified
region.
This table summarizes the available options for setting the kernel smoothing density region.
Value  Description 

1by2 numeric row vector  For example, [L,U] , where L and U are
the finite lower and upper bounds, respectively, for the density support. 
'positive'  The density support is all positive real values. 
'unbounded'  The density support is all real values. 
If you specify a 1byP string array or cell array, with
each element in the string array containing any text value in the table and each element
in the cell array containing any value in the table, then the software trains the
classifier using the kernel support in element j for feature
j in X
. The software ignores elements of
Kernel
not corresponding to a predictor whose distribution is
'kernel'
.
You must specify that at least one predictor has distribution 'kernel'
to
additionally specify Kernel
, Support
,
or Width
.
Example: 'KSSupport',{[10,20],'unbounded'}
Data Types: char
 string
 cell
 double
'Width'
— Kernel smoothing window widthKernel smoothing window width, specified as the commaseparated
pair consisting of 'Width'
and a matrix of numeric
values, numeric column vector, numeric row vector, or scalar.
Suppose there are K class levels and P predictors. This table summarizes the available options for setting the kernel smoothing window width.
Value  Description 

KbyP matrix of numeric values  Element (k,j) specifies the width for predictor j in class k. 
Kby1 numeric column vector  Element k specifies the width for all predictors in class k. 
1byP numeric row vector  Element j specifies the width in all class levels for predictor j. 
scalar  Specifies the bandwidth for all features in all classes. 
By default, the software selects
a default width automatically for each combination of predictor and
class by using a value that is optimal for a Gaussian distribution.
If you specify Width
and it contains NaN
s,
then the software selects widths for the elements containing NaN
s.
You must specify that at least one predictor has distribution 'kernel'
to
additionally specify Kernel
, Support
,
or Width
.
Example: 'Width',[NaN NaN]
Data Types: double
 struct
'CrossVal'
— Crossvalidation flag'off'
(default)  'on'
Crossvalidation flag, specified as the commaseparated pair
consisting of 'Crossval'
and 'on'
or 'off'
.
If you specify 'on'
, then the software implements
10fold crossvalidation.
To override this crossvalidation setting, use one of these namevalue
pair arguments: CVPartition
,
Holdout
, KFold
, or
Leaveout
. To create a crossvalidated model,
you can use one crossvalidation namevalue pair argument at a time
only.
Alternatively, crossvalidate later by passing
Mdl
to crossval
.
Example: 'CrossVal','on'
'CVPartition'
— Crossvalidation partition[]
(default)  cvpartition
partition objectCrossvalidation partition, specified as the commaseparated pair consisting of
'CVPartition'
and a cvpartition
partition
object created by cvpartition
. The partition object
specifies the type of crossvalidation and the indexing for the training and validation
sets.
To create a crossvalidated model, you can use one of these four namevalue pair arguments
only: CVPartition
, Holdout
,
KFold
, or Leaveout
.
Example: Suppose you create a random partition for 5fold crossvalidation on 500
observations by using cvp = cvpartition(500,'KFold',5)
. Then, you can
specify the crossvalidated model by using
'CVPartition',cvp
.
'Holdout'
— Fraction of data for holdout validationFraction of the data used for holdout validation, specified as the commaseparated pair
consisting of 'Holdout'
and a scalar value in the range (0,1). If you
specify 'Holdout',p
, then the software completes these steps:
Randomly select and reserve p*100
% of the data as
validation data, and train the model using the rest of the data.
Store the compact, trained model in the Trained
property of the crossvalidated model.
To create a crossvalidated model, you can use one of these
four namevalue pair arguments only: CVPartition
, Holdout
, KFold
,
or Leaveout
.
Example: 'Holdout',0.1
Data Types: double
 single
'KFold'
— Number of folds10
(default)  positive integer value greater than 1Number of folds to use in a crossvalidated model, specified as the commaseparated pair
consisting of 'KFold'
and a positive integer value greater than 1. If
you specify 'KFold',k
, then the software completes these steps:
Randomly partition the data into k
sets.
For each set, reserve the set as validation data, and train the model
using the other k
– 1 sets.
Store the k
compact, trained models in the cells of a
k
by1 cell vector in the Trained
property of the crossvalidated model.
To create a crossvalidated model, you can use one of these
four namevalue pair arguments only: CVPartition
, Holdout
, KFold
,
or Leaveout
.
Example: 'KFold',5
Data Types: single
 double
'Leaveout'
— Leaveoneout crossvalidation flag'off'
(default)  'on'
Leaveoneout crossvalidation flag, specified as the commaseparated pair consisting of
'Leaveout'
and 'on'
or
'off'
. If you specify 'Leaveout','on'
, then,
for each of the n observations (where n is the
number of observations excluding missing observations, specified in the
NumObservations
property of the model), the software completes
these steps:
Reserve the observation as validation data, and train the model using the other n – 1 observations.
Store the n compact, trained models in the cells of an
nby1 cell vector in the Trained
property of the crossvalidated model.
To create a crossvalidated model, you can use one of these
four namevalue pair arguments only: CVPartition
, Holdout
, KFold
,
or Leaveout
.
Example: 'Leaveout','on'
'CategoricalPredictors'
— Categorical predictors list'all'
Categorical predictors
list, specified as the commaseparated pair consisting of
'CategoricalPredictors'
and one of the values in this table.
Value  Description 

Vector of positive integers  An entry in the vector is the index value corresponding to the column of the
predictor data (X or Tbl ) that contains a
categorical variable. 
Logical vector  A true entry means that the corresponding column of predictor
data (X or Tbl ) is a categorical
variable. 
Character matrix  Each row of the matrix is the name of a predictor variable. The names must match
the entries in PredictorNames . Pad the names with extra blanks so
each row of the character matrix has the same length. 
String array or cell array of character vectors  Each element in the array is the name of a predictor variable. The names must match
the entries in PredictorNames . 
'all'  All predictors are categorical. 
By default, if the
predictor data is in a table (Tbl
), fitcnb
assumes that a variable is categorical if it contains logical values, categorical values, a
string array, or a cell array of character vectors. If the predictor data is a matrix
(X
), fitcnb
assumes all predictors are
continuous. To identify any categorical predictors when the data is a matrix, use the 'CategoricalPredictors'
namevalue pair
argument.
Example: 'CategoricalPredictors','all'
Data Types: single
 double
 logical
 char
 string
 cell
'ClassNames'
— Names of classes to use for trainingNames of classes to use for training, specified as the commaseparated pair consisting of
'ClassNames'
and a categorical, character, or string array, a
logical or numeric vector, or a cell array of character vectors.
ClassNames
must have the same data type as
Y
.
If ClassNames
is a character array, then each element must correspond to
one row of the array.
Use ClassNames
to:
Order the classes during training.
Specify the order of any input or output argument
dimension that corresponds to the class order. For example, use ClassNames
to
specify the order of the dimensions of Cost
or
the column order of classification scores returned by predict
.
Select a subset of classes for training. For example,
suppose that the set of all distinct class names in Y
is {'a','b','c'}
.
To train the model using observations from classes 'a'
and 'c'
only,
specify 'ClassNames',{'a','c'}
.
The default value for ClassNames
is the set of all distinct class names in
Y
.
Example: 'ClassNames',{'b','g'}
Data Types: categorical
 char
 string
 logical
 single
 double
 cell
'Cost'
— Cost of misclassificationCost of misclassification of a point, specified as the commaseparated
pair consisting of 'Cost'
and one of the
following:
Square matrix, where Cost(i,j)
is the cost
of classifying a point into class j
if its
true class is i
(i.e., the rows correspond to
the true class and the columns correspond to the predicted
class). To specify the class order for the corresponding rows
and columns of Cost
, additionally specify the
ClassNames
namevalue pair
argument.
Structure S
having two fields:
S.ClassNames
containing the group names
as a variable of the same type as Y
, and
S.ClassificationCosts
containing the cost
matrix.
The default is Cost(i,j)=1
if
i~=j
, and Cost(i,j)=0
if
i=j
.
Example: 'Cost',struct('ClassNames',{{'b','g'}},'ClassificationCosts',[0
0.5; 1 0])
Data Types: single
 double
 struct
'PredictorNames'
— Predictor variable namesPredictor variable names, specified as the commaseparated pair consisting of
'PredictorNames'
and a string array of unique names or cell array
of unique character vectors. The functionality of 'PredictorNames'
depends on the way you supply the training data.
If you supply X
and Y
, then you
can use 'PredictorNames'
to give the predictor variables
in X
names.
The order of the names in PredictorNames
must correspond to the column order of X
.
That is, PredictorNames{1}
is the name of
X(:,1)
,
PredictorNames{2}
is the name of
X(:,2)
, and so on. Also,
size(X,2)
and
numel(PredictorNames)
must be
equal.
By default, PredictorNames
is
{'x1','x2',...}
.
If you supply Tbl
, then you can use
'PredictorNames'
to choose which predictor variables
to use in training. That is, fitcnb
uses only the
predictor variables in PredictorNames
and the response
variable in training.
PredictorNames
must be a subset of
Tbl.Properties.VariableNames
and cannot
include the name of the response variable.
By default, PredictorNames
contains the
names of all predictor variables.
It is a good practice to specify the predictors for training
using either 'PredictorNames'
or
formula
only.
Example: 'PredictorNames',{'SepalLength','SepalWidth','PetalLength','PetalWidth'}
Data Types: string
 cell
'Prior'
— Prior probabilities'empirical'
(default)  'uniform'
 vector of scalar values  structurePrior probabilities for each class, specified as the commaseparated
pair consisting of 'Prior'
and a value in this
table.
Value  Description 

'empirical'  The class prior probabilities are the class relative frequencies
in Y . 
'uniform'  All class prior probabilities are equal to 1/K, where K is the number of classes. 
numeric vector  Each element is a class prior probability. Order the elements
according to Mdl .ClassNames or
specify the order using the ClassNames namevalue
pair argument. The software normalizes the elements such that they
sum to 1 . 
structure  A structure

If you set values for both Weights
and Prior
,
the weights are renormalized to add up to the value of the prior probability
in the respective class.
Example: 'Prior','uniform'
Data Types: char
 string
 single
 double
 struct
'ResponseName'
— Response variable name'Y'
(default)  character vector  string scalarResponse variable name, specified as the commaseparated pair consisting of
'ResponseName'
and a character vector or string scalar.
If you supply Y
, then you can
use 'ResponseName'
to specify a name for the response
variable.
If you supply ResponseVarName
or formula
,
then you cannot use 'ResponseName'
.
Example: 'ResponseName','response'
Data Types: char
 string
'ScoreTransform'
— Score transformation'none'
(default)  'doublelogit'
 'invlogit'
 'ismax'
 'logit'
 function handle  ...Score transformation, specified as the commaseparated pair consisting of
'ScoreTransform'
and a character vector, string scalar, or
function handle.
This table summarizes the available character vectors and string scalars.
Value  Description 

'doublelogit'  1/(1 + e^{–2x}) 
'invlogit'  log(x / (1 – x)) 
'ismax'  Sets the score for the class with the largest score to 1 , and sets the
scores for all other classes to 0 
'logit'  1/(1 + e^{–x}) 
'none' or 'identity'  x (no transformation) 
'sign'  –1 for x < 0 0 for x = 0 1 for x > 0 
'symmetric'  2x – 1 
'symmetricismax'  Sets the score for the class with the largest score to 1 ,
and sets the scores for all other classes to –1 
'symmetriclogit'  2/(1 + e^{–x}) – 1 
For a MATLAB^{®} function or a function you define, use its function handle for score transform. The function handle must accept a matrix (the original scores) and return a matrix of the same size (the transformed scores).
Example: 'ScoreTransform','logit'
Data Types: char
 string
 function_handle
'Weights'
— Observation weightsTbl
Observation weights, specified as the commaseparated pair consisting
of 'Weights'
and a numeric vector of positive values
or name of a variable in Tbl
. The software weighs
the observations in each row of X
or Tbl
with
the corresponding value in Weights
. The size of Weights
must
equal the number of rows of X
or Tbl
.
If you specify the input data as a table Tbl
, then
Weights
can be the name of a variable in Tbl
that contains a numeric vector. In this case, you must specify
Weights
as a character vector or string scalar. For example, if
the weights vector W
is stored as Tbl.W
, then
specify it as 'W'
. Otherwise, the software treats all columns of
Tbl
, including W
, as predictors or the
response when training the model.
The software normalizes Weights
to sum up
to the value of the prior probability in the respective class.
By default, Weights
is ones(
,
where n
,1)n
is the number of observations in X
or Tbl
.
Data Types: double
 single
 char
 string
'OptimizeHyperparameters'
— Parameters to optimize'none'
(default)  'auto'
 'all'
 string array or cell array of eligible parameter names  vector of optimizableVariable
objectsParameters to optimize, specified as the commaseparated pair
consisting of 'OptimizeHyperparameters'
and one of
the following:
'none'
— Do not optimize.
'auto'
— Use
{'DistributionNames','Width'}
.
'all'
— Optimize all eligible
parameters.
String array or cell array of eligible parameter names.
Vector of optimizableVariable
objects,
typically the output of hyperparameters
.
The optimization attempts to minimize the crossvalidation loss
(error) for fitcnb
by varying the parameters. For
information about crossvalidation loss (albeit in a different context),
see Classification Loss. To control the
crossvalidation type and other aspects of the optimization, use the
HyperparameterOptimizationOptions
namevalue
pair.
'OptimizeHyperparameters'
values override any values you set using
other namevalue pair arguments. For example, setting
'OptimizeHyperparameters'
to 'auto'
causes the
'auto'
values to apply.
The eligible parameters for fitcnb
are:
DistributionNames
—
fitcnb
searches among
'normal'
and
'kernel'
.
Width
—
fitcnb
searches among real values, by
default logscaled in the range
[MinPredictorDiff/4,max(MaxPredictorRange,MinPredictorDiff)]
.
Kernel
—
fitcnb
searches among
'normal'
, 'box'
,
'epanechnikov'
, and
'triangle'
.
Set nondefault parameters by passing a vector of
optimizableVariable
objects that have nondefault
values. For example,
load fisheriris params = hyperparameters('fitcnb',meas,species); params(2).Range = [1e2,1e2];
Pass params
as the value of
OptimizeHyperparameters
.
By default, iterative display appears at the command line, and
plots appear according to the number of hyperparameters in the optimization. For the
optimization and plots, the objective function is log(1 + crossvalidation loss) for regression and the misclassification rate for classification. To control
the iterative display, set the Verbose
field of the
'HyperparameterOptimizationOptions'
namevalue pair argument. To
control the plots, set the ShowPlots
field of the
'HyperparameterOptimizationOptions'
namevalue pair argument.
For an example, see Optimize Naive Bayes Classifier.
Example: 'auto'
'HyperparameterOptimizationOptions'
— Options for optimizationOptions for optimization, specified as the commaseparated pair consisting of
'HyperparameterOptimizationOptions'
and a structure. This
argument modifies the effect of the OptimizeHyperparameters
namevalue pair argument. All fields in the structure are optional.
Field Name  Values  Default 

Optimizer 
 'bayesopt' 
AcquisitionFunctionName 
Acquisition functions whose names include
 'expectedimprovementpersecondplus' 
MaxObjectiveEvaluations  Maximum number of objective function evaluations.  30 for 'bayesopt' or 'randomsearch' , and the entire grid for 'gridsearch' 
MaxTime  Time limit, specified as a positive real. The time limit is in seconds, as measured by  Inf 
NumGridDivisions  For 'gridsearch' , the number of values in each dimension. The value can be
a vector of positive integers giving the number of
values for each dimension, or a scalar that
applies to all dimensions. This field is ignored
for categorical variables.  10 
ShowPlots  Logical value indicating whether to show plots. If true , this field plots
the best objective function value against the
iteration number. If there are one or two
optimization parameters, and if
Optimizer is
'bayesopt' , then
ShowPlots also plots a model of
the objective function against the
parameters.  true 
SaveIntermediateResults  Logical value indicating whether to save results when Optimizer is
'bayesopt' . If
true , this field overwrites a
workspace variable named
'BayesoptResults' at each
iteration. The variable is a BayesianOptimization object.  false 
Verbose  Display to the command line.
For details, see the
 1 
UseParallel  Logical value indicating whether to run Bayesian optimization in parallel, which requires Parallel Computing Toolbox™. For details, see Parallel Bayesian Optimization.  false 
Repartition  Logical value indicating whether to repartition the crossvalidation at every iteration. If
 false 
Use no more than one of the following three field names.  
CVPartition  A cvpartition object, as created by cvpartition .  'Kfold',5 if you do not specify any crossvalidation
field 
Holdout  A scalar in the range (0,1) representing the holdout fraction.  
Kfold  An integer greater than 1. 
Example: 'HyperparameterOptimizationOptions',struct('MaxObjectiveEvaluations',60)
Data Types: struct
Mdl
— Trained naive Bayes classification modelClassificationNaiveBayes
model object  ClassificationPartitionedModel
crossvalidated
model objectTrained naive Bayes classification model, returned as a ClassificationNaiveBayes
model
object or a ClassificationPartitionedModel
crossvalidated
model object.
If you set any of the namevalue pair arguments KFold
, Holdout
, CrossVal
,
or CVPartition
, then Mdl
is
a ClassificationPartitionedModel
crossvalidated
model object. Otherwise, Mdl
is a ClassificationNaiveBayes
model
object.
To reference properties of Mdl
, use dot notation.
For example, to access the estimated distribution parameters, enter Mdl.DistributionParameters
.
In the bagoftokens model, the value of predictor j is the nonnegative number of occurrences of token j in this observation. The number of categories (bins) in this multinomial model is the number of distinct tokens, that is, the number of predictors.
Naive Bayes is a classification algorithm that applies density estimation to the data.
The algorithm leverages Bayes theorem, and (naively) assumes that the predictors are conditionally independent, given the class. Though the assumption is usually violated in practice, naive Bayes classifiers tend to yield posterior distributions that are robust to biased class density estimates, particularly where the posterior is 0.5 (the decision boundary) [1].
Naive Bayes classifiers assign observations to the most probable class (in other words, the maximum a posteriori decision rule). Explicitly, the algorithm:
Estimates the densities of the predictors within each class.
Models posterior probabilities according to Bayes rule. That is, for all k = 1,...,K,
$$\widehat{P}\left(Y=k{X}_{1},\mathrm{..},{X}_{P}\right)=\frac{\pi \left(Y=k\right){\displaystyle \prod _{j=1}^{P}P}\left({X}_{j}Y=k\right)}{{\displaystyle \sum}_{k=1}^{K}\pi \left(Y=k\right){\displaystyle \prod _{j=1}^{P}P}\left({X}_{j}Y=k\right)},$$
where:
Y is the random variable corresponding to the class index of an observation.
X_{1},...,X_{P} are the random predictors of an observation.
$$\pi \left(Y=k\right)$$ is the prior probability that a class index is k.
Classifies an observation by estimating the posterior probability for each class, and then assigns the observation to the class yielding the maximum posterior probability.
If the predictors compose a multinomial distribution, then the posterior probability$$\widehat{P}\left(Y=k{X}_{1},\mathrm{..},{X}_{P}\right)\propto \pi \left(Y=k\right){P}_{mn}\left({X}_{1},\mathrm{...},{X}_{P}Y=k\right),$$ where $${P}_{mn}\left({X}_{1},\mathrm{...},{X}_{P}Y=k\right)$$ is the probability mass function of a multinomial distribution.
For classifying countbased data, such as the bagoftokens model, use the multinomial distribution (e.g., set
'DistributionNames','mn'
).
After training a model, you can generate C/C++ code that predicts labels for new data. Generating C/C++ code requires MATLAB Coder™. For details, see Introduction to Code Generation.
If you specify 'DistributionNames','mn'
when training
Mdl
using fitcnb
, then the software fits a multinomial distribution using the
bagoftokens
model. The software stores the probability that token
j
appears in class k
in
the property
DistributionParameters{
.
Using additive smoothing [2], the estimated probability isk
,j
}
$$P(\text{token}j\text{class}k)=\frac{1+{c}_{jk}}{P+{c}_{k}},$$
where:
$${c}_{jk}={n}_{k}\frac{{\displaystyle \sum _{i:{y}_{i}\in \text{class}k}^{}{x}_{ij}}{w}_{i}^{}}{{\displaystyle \sum _{i:{y}_{i}\in \text{class}k}^{}{w}_{i}}};$$ which is the weighted number of occurrences of token j in class k.
n_{k} is the number of observations in class k.
$${w}_{i}^{}$$ is the weight for observation i. The software normalizes weights within a class such that they sum to the prior probability for that class.
$${c}_{k}={\displaystyle \sum _{j=1}^{P}{c}_{jk}};$$ which is the total weighted number of occurrences of all tokens in class k.
If you specify 'DistributionNames','mvmn'
when training
Mdl
using fitcnb
, then:
For each predictor, the software collects a list of the unique levels,
stores the sorted list in CategoricalLevels
, and considers each level a bin. Each
predictor/class combination is a separate, independent multinomial
random variable.
For predictor j
in class
k, the software counts instances of each
categorical level using the list stored in
CategoricalLevels{
.j
}
The software stores the probability that predictor
j
, in class k
,
has level L in the property
DistributionParameters{
,
for all levels in
k
,j
}CategoricalLevels{
.
Using additive smoothing [2], the estimated probability isj
}
$$P\left(\text{predictor}j=L\text{class}k\right)=\frac{1+{m}_{jk}(L)}{{m}_{j}+{m}_{k}},$$
where:
$${m}_{jk}(L)={n}_{k}\frac{{\displaystyle \sum _{i:{y}_{i}\in \text{class}k}^{}I\{{x}_{ij}=L\}{w}_{i}^{}}}{{\displaystyle \sum _{i:{y}_{i}\in \text{class}k}^{}{w}_{i}^{}}};$$ which is the weighted number of observations for which predictor j equals L in class k.
n_{k} is the number of observations in class k.
$$I\left\{{x}_{ij}=L\right\}=1$$ if x_{ij} = L, 0 otherwise.
$${w}_{i}^{}$$ is the weight for observation i. The software normalizes weights within a class such that they sum to the prior probability for that class.
m_{j} is the number of distinct levels in predictor j.
m_{k} is the weighted number of observations in class k.
[1] Hastie, T., R. Tibshirani, and J. Friedman. The Elements of Statistical Learning, Second Edition. NY: Springer, 2008.
[2] Manning, C. D., P. Raghavan, and M. Schütze. Introduction to Information Retrieval, NY: Cambridge University Press, 2008.
This function supports tall arrays with the limitations:
Supported syntaxes are:
Mdl = fitcnb(Tbl,Y)
Mdl = fitcnb(X,Y)
Mdl = fitcnb(___,Name,Value)
Options related to kernel densities, crossvalidation, and hyperparameter optimization are not supported. The supported namevalue pair arguments are:
'DistributionNames'
— 'kernel'
value is not supported.
'CategoricalPredictors'
'Cost'
'PredictorNames'
'Prior'
'ResponseName'
'ScoreTransform'
'Weights'
— Value must be a tall array.
For more information, see Tall Arrays (MATLAB).
To run in parallel, set the 'UseParallel'
option to true
.
To perform parallel hyperparameter optimization, use the 'HyperparameterOptions', struct('UseParallel',true)
namevalue pair argument in the call to this function.
For more information on parallel hyperparameter optimization, see Parallel Bayesian Optimization.
For more general information about parallel computing, see Run MATLAB Functions with Automatic Parallel Support (Parallel Computing Toolbox).
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
Select web siteYou can also select a web site from the following list:
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.