edge
Classification edge for naive Bayes classifier
Syntax
Description
returns theClassification Edge(e
= edge(Mdl
,tbl
,ResponseVarName
)e
) for the naive Bayes classifierMdl
using the predictor data in tabletbl
and the class labels intbl.ResponseVarName
.
The classification edge (e
) is a scalar value that represents the weighted mean of theClassification 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 thefisheriris
data set. CreateX
as a numeric matrix that contains four petal measurements for 150 irises. CreateY
as 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 predictorsXTrain
and class labelsYTrain
. 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 trainedClassificationNaiveBayes
classifier.
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 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 thefisheriris
data set. CreateX
as a numeric matrix that contains four petal measurements for 150 irises. CreateY
as 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 predictorsXTrain
and class labelsYTrain
. 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 trainedClassificationNaiveBayes
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 predictorsXTrain
, class labelsYTrain
, and weightsweightsTrain
.
Mdl_W = fitcnb(XTrain,YTrain,“重量”,weightsTrain,...'ClassNames',{'setosa','versicolor','virginica'});
Mdl_W
is a trainedClassificationNaiveBayes
classifier.
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.
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 theionosphere
data 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:
fullXTrain
contains 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);
fullMdl
andpartMdl
are trainedClassificationNaiveBayes
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 aClassificationNaiveBayes
model object orCompactClassificationNaiveBayes
model object returned byfitcnb
orcompact
, respectively.
tbl
—Sample data
table
Sample data used to train the model, specified as a table. Each row oftbl
corresponds to one observation, and each column corresponds to one predictor variable.tbl
must contain all the predictors used to trainMdl
. 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 trainMdl
using sample data contained in a table, then the input data foredge
must also be in a table.
ResponseVarName
—Response variable name
name of a variable intbl
Response variable name, specified as the name of a variable intbl
.
You must specifyResponseVarName
as a character vector or string scalar. For example, if the response variabley
is stored astbl.y
, then specify it as'y'
. Otherwise, the software treats all columns oftbl
, includingy
, as predictors.
Iftbl
contains 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
X
—Predictor data
numeric matrix
Predictor data, specified as a numeric matrix.
Each row ofX
corresponds to one observation (also known as aninstanceorexample), and each column corresponds to one variable (also known as afeature). The variables in the columns ofX
must be the same as the variables that trained theMdl
classifier.
The length ofY
and the number of rows ofX
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 asMdl.ClassNames
.(The software treats string arrays as cell arrays of character vectors.)
The length ofY
must be equal to the number of rows oftbl
orX
.
Data Types:categorical
|char
|string
|logical
|single
|double
|cell
Weights
—Observation weights
ones(size(X,1),1)
(default) |numeric vector|name of a variable intbl
Observation weights, specified as a numeric vector or the name of a variable intbl
. The software weighs the observations in each row ofX
ortbl
with the corresponding weights inWeights
.
If you specifyWeights
as a numeric vector, then the size ofWeights
must be equal to the number of rows ofX
ortbl
.
If you specifyWeights
as 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 specifyWeights
as'w'
. Otherwise, the software treats all columns oftbl
, includingtbl.w
, as predictors.
Data Types:double
|char
|string
More About
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
where:
is the conditional joint density of the predictors given they are in classk.
Mdl.DistributionNames
stores the distribution names of the predictors.π(Y=k) is the class prior probability distribution.
Mdl.Prior
stores the prior distribution.is the joint density of the predictors. The classes are discrete, so
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
Tall Arrays
Calculate with arrays that have more rows than fit in memory.
This function fully supports tall arrays. For more information, seeTall Arrays.
Version History
Introduced in R2014b
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:
运行该命令通过输入MATLAB逗号nd 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)