Classification margins for naive Bayes classifiers

`m = margin(Mdl,tbl,ResponseVarName)`

`m = margin(Mdl,tbl,Y)`

`m = margin(Mdl,X,Y)`

returns the classification margins
(`m`

= margin(`Mdl`

,`tbl`

,`ResponseVarName`

)`m`

) for the trained naive Bayes classifier
`Mdl`

using the predictor data in table `tbl`

and the class labels in `tbl.ResponseVarName`

.

`Mdl`

— Naive Bayes classifier`ClassificationNaiveBayes`

model | `CompactClassificationNaiveBayes`

modelNaive Bayes classifier, specified as a `ClassificationNaiveBayes`

model
or `CompactClassificationNaiveBayes`

model
returned by `fitcnb`

or `compact`

,
respectively.

`tbl`

— Sample datatable

Sample data, specified as a table. Each row of `tbl`

corresponds
to one observation, and each column corresponds to one predictor variable.
Optionally, `tbl`

can contain additional columns
for the response variable and observation weights. `tbl`

must
contain all the predictors used to train `Mdl`

.
Multi-column variables and cell arrays other than cell arrays of character
vectors are not allowed.

If you trained `Mdl`

using sample data contained
in a `table`

, then the input data for this method
must also be in a table.

**Data Types: **`table`

`ResponseVarName`

— Response variable namename of a variable in

`tbl`

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 the response variable is a character array, then each element must correspond to one row of the array.

**Data Types: **`char`

| `string`

`X`

— Predictor datanumeric matrix

Predictor 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 variables making up
the columns of `X`

should be the same as the variables
that trained `Mdl`

.

The length of `Y`

and the number of rows of `X`

must
be equal.

**Data Types: **`double`

| `single`

`Y`

— Class labelscategorical array | character array | string array | logical vector | vector of numeric values | cell array of character vectors

Class labels, specified as a categorical, character, or string array, logical or numeric
vector, or cell array of character vectors. `Y`

must be the same as the
data type of `Mdl.ClassNames`

. (The software treats string arrays as cell arrays of character
vectors.)

The length of `Y`

and the number of rows of `tbl`

or `X`

must
be equal.

**Data Types: **`categorical`

| `char`

| `string`

| `logical`

| `single`

| `double`

| `cell`

`m`

— Classification marginsnumeric vector

Classification margins, returned as a numeric vector.

`m`

has the same length equal to
`size(X,1)`

. Each entry of `m`

is the
classification margin of the corresponding observation (row) of
`X`

and element of `Y`

.

Load Fisher's iris data set.

load fisheriris X = meas; % Predictors Y = species; % Response rng(1);

Train a naive Bayes classifier. Specify a 30% holdout sample for testing. It is good practice to specify the class order. Assume that each predictor is conditionally normally distributed given its label.

CVMdl = fitcnb(X,Y,'Holdout',0.30,... 'ClassNames',{'setosa','versicolor','virginica'}); CMdl = CVMdl.Trained{1}; ... % Extract the trained, compact classifier testInds = test(CVMdl.Partition); % Extract the test indices XTest = X(testInds,:); YTest = Y(testInds);

`CVMdl`

is a `ClassificationPartitionedModel`

classifier. It contains the property `Trained`

, which is a 1-by-1 cell array holding a `CompactClassificationNaiveBayes`

classifier that the software trained using the training set.

Estimate the test sample classification margins. Display the distribution of the margins using a boxplot.

```
m = margin(CMdl,XTest,YTest);
figure;
boxplot(m);
title 'Distribution of the Test-Sample Margins';
```

An observation margin is the observed true class score minus the maximum false class score among all scores in the respective class. Classifiers that yield relatively large margins are desirable.

The classifier margins measure, for each observation, the difference between the true class observed score and the maximal false class score for a particular class. One way to perform feature selection is to compare test sample margins from multiple models. Based solely on this criterion, the model with the highest margins is the best model.

Load Fisher's iris data set.

load fisheriris X = meas; % Predictors Y = species; % Response rng(1);

Partition the data set into training and test sets. Specify a 30% holdout sample for testing.

Partition = cvpartition(Y,'Holdout',0.30); testInds = test(Partition); % Indices for the test set XTest = X(testInds,:); YTest = Y(testInds);

Partition defines the data set partition.

Define these two data sets:

`fullX`

contains all predictors.`partX`

contains the last 2 predictors.

fullX = X; partX = X(:,3:4);

Train naive Bayes classifiers for each predictor set. Specify the partition definition.

FCVMdl = fitcnb(fullX,Y,'CVPartition',Partition); PCVMdl = fitcnb(partX,Y,'CVPartition',Partition); FCMdl = FCVMdl.Trained{1}; PCMdl = PCVMdl.Trained{1};

`FullCVMdl`

and `PartCVMdl`

are `ClassificationPartitionedModel`

classifiers. They contain the property `Trained`

, which is a 1-by-1 cell array holding a `CompactClassificationNaiveBayes`

classifier that the software trained using the training set.

Estimate the test sample margins for each classifier. Display the distributions of the margins for each model using boxplots.

fullM = margin(FCMdl,XTest,YTest); partM = margin(PCMdl,XTest(:,3:4),YTest); figure; boxplot([fullM partM],'Labels',{'All Predictors','Two Predictors'}) h = gca; h.YLim = [0.98 1.01]; % Modify axis to see boxes. title 'Boxplots of Test-Sample Margins';

The margins have a similar distribution, but `PCMdl`

is less complex.

The *classification edge* is
the weighted mean of the classification margins.

If you supply weights, then the software normalizes them to sum to the prior probability of their respective class. The software uses the normalized weights to compute the weighted mean.

One way to choose among multiple classifiers, e.g., to perform feature selection, is to choose the classifier that yields the highest edge.

The *classification margins* are,
for each observation, the difference between the score for the true
class and maximal score for the false classes. Provided that they
are on the same scale, margins serve as a classification confidence
measure, i.e., among multiple classifiers, those that yield larger
margins are better.

The *posterior probability* is
the probability that an observation belongs in a particular class,
given the data.

For naive Bayes, the posterior probability that a classification
is *k* for a given observation (*x*_{1},...,*x _{P}*)
is

$$\widehat{P}\left(Y=k|{x}_{1},\mathrm{..},{x}_{P}\right)=\frac{P\left({X}_{1},\mathrm{...},{X}_{P}|y=k\right)\pi \left(Y=k\right)}{P\left({X}_{1},\mathrm{...},{X}_{P}\right)},$$

where:

$$P\left({X}_{1},\mathrm{...},{X}_{P}|y=k\right)$$ is the conditional joint density of the predictors given they are in class

*k*.`Mdl.DistributionNames`

stores the distribution names of the predictors.*π*(*Y*=*k*) is the class prior probability distribution.`Mdl.Prior`

stores the prior distribution.$$P\left({X}_{1},\mathrm{..},{X}_{P}\right)$$ is the joint density of the predictors. The classes are discrete, so $$P({X}_{1},\mathrm{...},{X}_{P})={\displaystyle \sum _{k=1}^{K}P}({X}_{1},\mathrm{...},{X}_{P}|y=k)\pi (Y=k).$$

The *prior
probability* of a class is the believed relative frequency with which
observations from that class occur in a population.

The naive Bayes *score* is
the class posterior probability given the observation.

Calculate with arrays that have more rows than fit in memory.

This function fully supports tall arrays. For more information, see Tall Arrays (MATLAB).

`ClassificationNaiveBayes`

| `CompactClassificationNaiveBayes`

| `edge`

| `fitcnb`

| `loss`

| `predict`

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.

- América Latina (Español)
- Canada (English)
- United States (English)

- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)

- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)