# edge

Classification edge for naive Bayes classifier

## Syntax

## Description

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`

.

The classification edge (`e`

) is a scalar value that
represents the weighted mean of the Classification Margins.

## Examples

### Estimate Test Sample Edge of Naive Bayes Classifier

Estimate the test sample edge (the classification margin average) of a naive Bayes classifier. The test sample edge is the average 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.

Load the `fisheriris`

data set. Create `X`

as a numeric matrix that contains four petal measurements for 150 irises. Create `Y`

as a cell array of character vectors that contains the corresponding iris species.

load fisheriris X = meas; Y = species; rng('default') % for reproducibility

Randomly partition observations into a training set and a test set with stratification, using the class information in `Y`

. Specify a 30% holdout sample for testing.

`cv = cvpartition(Y,'HoldOut',0.30);`

Extract the training and test indices.

trainInds = training(cv); testInds = test(cv);

Specify the training and test data sets.

XTrain = X(trainInds,:); YTrain = Y(trainInds); XTest = X(testInds,:); YTest = Y(testInds);

Train a naive Bayes classifier using the predictors `XTrain`

and class labels `YTrain`

. A recommended practice is to specify the class names. `fitcnb`

assumes that each predictor is conditionally and normally distributed.

Mdl = fitcnb(XTrain,YTrain,'ClassNames',{'setosa','versicolor','virginica'})

Mdl = ClassificationNaiveBayes ResponseName: 'Y' CategoricalPredictors: [] ClassNames: {'setosa' 'versicolor' 'virginica'} ScoreTransform: 'none' NumObservations: 105 DistributionNames: {'normal' 'normal' 'normal' 'normal'} DistributionParameters: {3x4 cell} Properties, Methods

`Mdl`

is a trained `ClassificationNaiveBayes`

classifier.

Estimate the test sample edge.

e = edge(Mdl,XTest,YTest)

e = 0.8658

The margin average is approximately `0.87`

. This result suggests that the classifier labels predictors with high confidence.

### Estimate Test Sample Weighted Edge of Naive Bayes Classifier

Estimate the test sample weighted edge (the weighted margin average) of a naive Bayes classifier. The test sample edge is the average 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. The weighted sample edge estimates the margin average when the software assigns a weight to each observation.

Load the `fisheriris`

data set. Create `X`

as a numeric matrix that contains four petal measurements for 150 irises. Create `Y`

as a cell array of character vectors that contains the corresponding iris species.

load fisheriris X = meas; Y = species; rng('default') % for reproducibility

Suppose that some of the measurements are lower quality because they were measured with older technology. To simulate this effect, add noise to a random subset of 20 measurements.

idx = randperm(size(X,1),20); X(idx,:) = X(idx,:) + 2*randn(20,size(X,2));

Randomly partition observations into a training set and a test set with stratification, using the class information in `Y`

. Specify a 30% holdout sample for testing.

`cv = cvpartition(Y,'HoldOut',0.30);`

Extract the training and test indices.

trainInds = training(cv); testInds = test(cv);

Specify the training and test data sets.

XTrain = X(trainInds,:); YTrain = Y(trainInds); XTest = X(testInds,:); YTest = Y(testInds);

Train a naive Bayes classifier using the predictors `XTrain`

and class labels `YTrain`

. A recommended practice is to specify the class names. `fitcnb`

assumes that each predictor is conditionally and normally distributed.

Mdl = fitcnb(XTrain,YTrain,'ClassNames',{'setosa','versicolor','virginica'});

`Mdl`

is a trained `ClassificationNaiveBayes`

classifier.

Estimate the test sample edge.

e = edge(Mdl,XTest,YTest)

e = 0.5920

The average margin is approximately 0.59.

One way to reduce the effect of the noisy measurements is to assign them less weight than the other observations. Define a weight vector that gives the better quality observations twice the weight of the other observations.

n = size(X,1); weights = ones(size(X,1),1); weights(idx) = 0.5; weightsTrain = weights(trainInds); weightsTest = weights(testInds);

Train a naive Bayes classifier using the predictors `XTrain`

, class labels `YTrain`

, and weights `weightsTrain`

.

Mdl_W = fitcnb(XTrain,YTrain,'Weights',weightsTrain,... 'ClassNames',{'setosa','versicolor','virginica'});

`Mdl_W`

is a trained `ClassificationNaiveBayes`

classifier.

Estimate the test sample weighted edge using the weighting scheme.

`e_W = edge(Mdl_W,XTest,YTest,'Weights',weightsTest)`

e_W = 0.6816

The weighted average margin is approximately 0.69. This result indicates that, on average, the weighted classifier labels predictors with higher confidence than the noise corrupted predictors.

### Select Naive Bayes Classifier Features by Comparing Test Sample Edges

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

data set. Remove the first two predictors for stability.

load ionosphere X = X(:,3:end); rng('default') % for reproducibility

Randomly partition observations into a training set and a test set with stratification, using the class information in `Y`

. Specify a 30% holdout sample for testing.

`cv = cvpartition(Y,'Holdout',0.30);`

Extract the training and test indices.

trainInds = training(cv); testInds = test(cv);

Specify the training and test data sets.

XTrain = X(trainInds,:); YTrain = Y(trainInds); XTest = X(testInds,:); YTest = Y(testInds);

Define these two training data sets:

`fullXTrain`

contains all predictors.`partXTrain`

contains the 10 most important predictors.

fullXTrain = XTrain; idx = fscmrmr(XTrain,YTrain); partXTrain = XTrain(:,idx(1:10));

Train a naive Bayes classifier for each predictor set.

fullMdl = fitcnb(fullXTrain,YTrain); partMdl = fitcnb(partXTrain,YTrain);

`fullMdl`

and `partMdl`

are trained `ClassificationNaiveBayes`

classifiers.

Estimate the test sample edge for each classifier.

fullEdge = edge(fullMdl,XTest,YTest)

fullEdge = 0.5831

partEdge = edge(partMdl,XTest(:,idx(1:10)),YTest)

partEdge = 0.7593

The test sample edge of the classifier using the 10 most important predictors is larger.

## Input Arguments

`Mdl`

— Naive Bayes classification model

`ClassificationNaiveBayes`

model object | `CompactClassificationNaiveBayes`

model object

Naive Bayes classification model, specified as a `ClassificationNaiveBayes`

model object or `CompactClassificationNaiveBayes`

model object returned by `fitcnb`

or `compact`

,
respectively.

`tbl`

— Sample data

table

Sample 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. `tbl`

must contain all the predictors used
to train `Mdl`

. Multicolumn variables and cell arrays other than cell
arrays of character vectors are not allowed. Optionally, `tbl`

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

If you train `Mdl`

using sample data contained in a table, then the input
data for `edge`

must also be in a table.

`ResponseVarName`

— Response variable name

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

If `tbl`

contains the response variable used to train
`Mdl`

, then you do not need to specify
`ResponseVarName`

.

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 data

numeric 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 in the
columns of `X`

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

classifier.

The length of `Y`

and the number of rows of `X`

must
be equal.

**Data Types: **`double`

| `single`

`Y`

— Class labels

categorical array | character array | string array | logical vector | numeric vector | 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 have the same data
type as `Mdl.ClassNames`

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

The length of `Y`

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

or `X`

.

**Data Types: **`categorical`

| `char`

| `string`

| `logical`

| `single`

| `double`

| `cell`

`Weights`

— Observation weights

`ones(size(X,1),1)`

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

Observation weights, specified as 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 weights in `Weights`

.

If you specify `Weights`

as a numeric 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`

, then the name must be 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.

**Data Types: **`double`

| `char`

| `string`

## More About

### Classification Edge

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.

When choosing among multiple classifiers to perform a task such as feature section, choose the classifier that yields the highest edge.

### Classification Margins

The *classification margin* for each observation is the
difference between the score for the true class and the maximal score for the false classes.
Margins provide a classification confidence measure; among multiple classifiers, those that
yield larger margins (on the same scale) are better.

### Posterior Probability

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).$$

### Prior Probability

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

### Classification Score

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

## Extended Capabilities

### Tall Arrays

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

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

## Version History

**Introduced in R2014b**

## See Also

`ClassificationNaiveBayes`

| `CompactClassificationNaiveBayes`

| `predict`

| `fitcnb`

| `loss`

| `resubLoss`

| `margin`

| `resubEdge`

## Open Example

You have a modified version of this example. Do you want to open this example with your edits?

## MATLAB Command

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.

# Select a Web Site

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

You can also select a web site from the following list:

## How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

### Americas

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

### Europe

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