Classification edge for naive Bayes classifiers

`e = edge(Mdl,tbl,ResponseVarName)`

`e = edge(Mdl,tbl,Y)`

`e = edge(Mdl,X,Y)`

`e = edge(___,Name,Value)`

returns the classification edge
(`e`

= edge(`Mdl`

,`tbl`

,`ResponseVarName`

)`e`

) for the naive Bayes classifier `Mdl`

using the predictor data in table `tbl`

and the class labels
in `tbl.ResponseVarName`

.

computes the classification edge with additional options specified by one or
more `e`

= edge(___,`Name,Value`

)`Name,Value`

pair arguments, using any of the previous
syntaxes.

`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`

Specify optional
comma-separated 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`

.

`'Weights'`

— Observation weights`ones(size(X,1),1)`

(default) | numeric vector | name of a variable in `tbl`

Observation weights, specified as the comma-separated pair consisting
of `'Weights'`

and a numeric vector or the name of
a variable in `tbl`

. The software weighs the observations
in each row of `X`

or `tbl`

with
the corresponding weight in `Weights`

.

If you specify `Weights`

as a vector, then
the size of `Weights`

must be equal to the number
of rows of `X`

or `tbl`

.

If you specify `Weights`

as the name of a variable in
`tbl`

, you must do so as a character vector or string scalar. For
example, if the weights are stored as `tbl.w`

, then specify
`Weights`

as `'w'`

. Otherwise, the software
treats all columns of `tbl`

, including `tbl.w`

, as
predictors.

If you do not specify your own loss function, then the software normalizes
`Weights`

to add up to `1`

.

**Data Types: **`double`

| `char`

| `string`

`e`

— Classification edgescalar

Classification edge, returned as
a scalar. If you supply `Weights`

, then
`e`

is the weighted classification edge.

Load Fisher's iris data set.

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

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 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 edge.

e = edge(CMdl,XTest,YTest)

e = 0.8244

The estimated test sample margin average is approximately `0.82`

. This indicates that, on average, the test sample difference between the estimated posterior probability for the predicted class and the posterior probability for the class with the next lowest posterior probability is approximately 0.82. This indicates that the classifier labels with high confidence.

Load Fisher's iris data set.

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

Suppose that the setosa iris measurements are lower quality because they were measured with an older technology. One way to incorporate this is to weigh the setosa iris measurements less than the other observations.

Define a weight vector that weighs the better quality observations twice the other observations.

```
n = size(X,1);
idx = strcmp(Y,'setosa');
weights = ones(size(X,1),1);
weights(idx) = 0.5;
```

Train a naive Bayes classifier. Specify the weighting scheme and 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,'Weights',weights,'Holdout',0.30,... 'ClassNames',{'setosa','versicolor','virginica'}); CMdl = CVMdl.Trained{1}; % Extract trained, compact classifier testInds = test(CVMdl.Partition); % Extract the test indices XTest = X(testInds,:); YTest = Y(testInds); wTest = weights(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 weighted edge using the weighting scheme.

`e = edge(CMdl,XTest,YTest,'Weights',wTest)`

e = 0.7893

The test sample weighted average margin is approximately 0.79. This indicates that, on average, the test sample difference between the estimated posterior probability for the predicted class and the posterior probability for the class with the next lowest posterior probability is approximately 0.79. This indicates that the classifier labels with high confidence.

The classifier edge measures the average of the classifier margins. One way to perform feature selection is to compare test sample edges from multiple models. Based solely on this criterion, the classifier with the highest edge is the best classifier.

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 two 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};

`FCVMdl`

and `PCVMdl`

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 edge for each classifier.

fullEdge = edge(FCMdl,XTest,YTest)

fullEdge = 0.8244

partEdge = edge(PCMdl,XTest(:,3:4),YTest)

partEdge = 0.8420

The test-sample edges of the classifiers are nearly the same. However, the model trained using two predictors (`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`

| `fitcnb`

| `loss`

| `margin`

| `predict`

| `resubEdge`

| `resubLoss`

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)