Main Content

edge

Classification edge for naive Bayes classifier

Description

e= edge(Mdl,tbl,ResponseVarName)returns theClassification Edge(e) for the naive Bayes classifierMdlusing the predictor data in tabletbland the class labels intbl.ResponseVarName.

The classification edge (e) is a scalar value that represents the weighted mean of theClassification Margins.

e= edge(Mdl,tbl,Y)returns the classification edge forMdlusing the predictor data in tabletbland the class labels in vectorY.

example

e= edge(Mdl,X,Y)returns the classification edge forMdlusing the predictor data in matrixXand the class labels inY.

example

e= edge(___,“重量”,Weights)returns the classification edge with additional observation weights supplied inWeightsusing any of the input argument combinations in the previous syntaxes.

Examples

collapse all

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 thefisheririsdata set. CreateXas a numeric matrix that contains four petal measurements for 150 irises. CreateYas a cell array of character vectors that contains the corresponding iris species.

loadfisheririsX = meas; Y = species; rng('default')% for reproducibility

Randomly partition observations into a training set and a test set with stratification, using the class information inY. 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 predictorsXTrainand class labelsYTrain. A recommended practice is to specify the class names.fitcnbassumes 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

Mdlis a trainedClassificationNaiveBayesclassifier.

Estimate the test sample edge.

e = edge(Mdl,XTest,YTest)
e = 0.8658

The margin average is approximately0.87. This result suggests that the classifier labels predictors with high confidence.

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 thefisheririsdata set. CreateXas a numeric matrix that contains four petal measurements for 150 irises. CreateYas a cell array of character vectors that contains the corresponding iris species.

loadfisheririsX = 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 inY. 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 predictorsXTrainand class labelsYTrain. A recommended practice is to specify the class names.fitcnbassumes that each predictor is conditionally and normally distributed.

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

Mdlis a trainedClassificationNaiveBayesclassifier.

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 predictorsXTrain, class labelsYTrain, and weightsweightsTrain.

Mdl_W = fitcnb(XTrain,YTrain,“重量”,weightsTrain,...'ClassNames',{'setosa','versicolor','virginica'});

Mdl_Wis a trainedClassificationNaiveBayesclassifier.

Estimate the test sample weighted edge using the weighting scheme.

e_W = edge(Mdl_W,XTest,YTest,“重量”,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.

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 theionospheredata set. Remove the first two predictors for stability.

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

Randomly partition observations into a training set and a test set with stratification, using the class information inY. 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:

  • fullXTraincontains all predictors.

  • partXTrain包含10个最重要的因素s.

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

fullMdlandpartMdlare trainedClassificationNaiveBayesclassifiers.

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

collapse all

Naive Bayes classification model, specified as aClassificationNaiveBayesmodel object orCompactClassificationNaiveBayesmodel object returned byfitcnborcompact, respectively.

Sample data used to train the model, specified as a table. Each row oftblcorresponds to one observation, and each column corresponds to one predictor variable.tblmust contain all the predictors used to trainMdl. Multicolumn variables and cell arrays other than cell arrays of character vectors are not allowed. Optionally,tblcan contain additional columns for the response variable and observation weights.

If you trainMdlusing sample data contained in a table, then the input data foredgemust also be in a table.

Response variable name, specified as the name of a variable intbl.

You must specifyResponseVarNameas a character vector or string scalar. For example, if the response variableyis stored astbl.y, then specify it as'y'. Otherwise, the software treats all columns oftbl, includingy, as predictors.

Iftblcontains the response variable used to trainMdl, then you do not need to specifyResponseVarName.

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

Predictor data, specified as a numeric matrix.

Each row ofXcorresponds to one observation (also known as aninstanceorexample), and each column corresponds to one variable (also known as afeature). The variables in the columns ofXmust be the same as the variables that trained theMdlclassifier.

The length ofYand the number of rows ofXmust be equal.

Data Types:double|single

Class labels, specified as a categorical, character, or string array, logical or numeric vector, or cell array of character vectors.Ymust have the same data type asMdl.ClassNames.(The software treats string arrays as cell arrays of character vectors.)

The length ofYmust be equal to the number of rows oftblorX.

Data Types:categorical|char|string|logical|single|double|cell

Observation weights, specified as a numeric vector or the name of a variable intbl. The software weighs the observations in each row ofXortblwith the corresponding weights inWeights.

If you specifyWeightsas a numeric vector, then the size ofWeightsmust be equal to the number of rows ofXortbl.

If you specifyWeightsas the name of a variable intbl, then the name must be a character vector or string scalar. For example, if the weights are stored astbl.w, then specifyWeightsas'w'. Otherwise, the software treats all columns oftbl, includingtbl.w, as predictors.

Data Types:double|char|string

More About

collapse all

Classification Edge

Theclassification edgeis 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.

当选择多个分类器perfor之一m a task such as feature section, choose the classifier that yields the highest edge.

Classification Margins

Theclassification marginfor 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

Theposterior probabilityis the probability that an observation belongs in a particular class, given the data.

For naive Bayes, the posterior probability that a classification iskfor a given observation (x1,...,xP) is

P ^ ( Y = k | x 1 , .. , x P ) = P ( X 1 , ... , X P | y = k ) π ( Y = k ) P ( X 1 , ... , X P ) ,

where:

  • P ( X 1 , ... , X P | y = k ) is the conditional joint density of the predictors given they are in classk.Mdl.DistributionNamesstores the distribution names of the predictors.

  • π(Y=k) is the class prior probability distribution.Mdl.Priorstores the prior distribution.

  • P ( X 1 , .. , X P ) is the joint density of the predictors. The classes are discrete, so P ( X 1 , ... , X P ) = k = 1 K P ( X 1 , ... , X P | y = k ) π ( Y = k ) .

Prior Probability

Theprior probabilityof a class is the assumed relative frequency with which observations from that class occur in a population.

Classification Score

The naive Bayesscoreis the class posterior probability given the observation.

Extended Capabilities

Version History

Introduced in R2014b