Main Content

incrementalClassificationNaiveBayes

Naive Bayes classification model for incremental learning

Description

TheincrementalClassificationNaiveBayesfunction creates anincrementalClassificationNaiveBayesmodel object, which represents a naive Bayes multiclass classification model for incremental learning.

Unlike other Statistics and Machine Learning Toolbox™ model objects,incrementalClassificationNaiveBayescan be called directly. Also, you can specify learning options, such as performance metrics configurations and prior class probabilities, before fitting the model to data. After you create anincrementalClassificationNaiveBayesobject, it is prepared forincremental learning

incrementalClassificationNaiveBayesis best suited for incremental learning. For a traditional approach to training a naive Bayes model for multiclass classification (such as creating a model by fitting it to data, performing cross-validation, tuning hyperparameters, and so on), seefitcnb

创建

You can create anincrementalClassificationNaiveBayesmodel object in several ways:

  • Call the function directly— Configure incremental learning options, or specify learner-specific options, by callingincrementalClassificationNaiveBayesdirectly. This approach is best when you do not have data yet or you want to start incremental learning immediately. You must specify the maximum number of classes or all class names expected in the response data during incremental learning.

  • Convert a traditionally trained model— To initialize a naive Bayes classification model for incremental learning using the model parameters of a trained model object (ClassificationNaiveBayes), you can convert the traditionally trained model to anincrementalClassificationNaiveBayesmodel object by passing it to theincrementalLearnerfunction.

  • Call an incremental learning functionfit,updateMetrics, andupdateMetricsAndFitaccept a configuredincrementalClassificationNaiveBayesmodel object and data as input, and return anincrementalClassificationNaiveBayesmodel object updated with information learned from the input model and data.

Description

example

Mdl= incrementalClassificationNaiveBayes('MaxNumClasses',MaxNumClasses)returns a default incremental learning model object for naive Bayes classification,Mdl, whereMaxNumClassesis the maximum number of classes expected in the response data during incremental learning. Properties of a default model contain placeholders for unknown model parameters. You must train a default model before you can track its performance or generate predictions from it.

example

Mdl= incrementalClassificationNaiveBayes('ClassNames',ClassNames)specifies all class namesClassNamesexpected in the response data during incremental learning, and sets theClassNamesproperty.

example

Mdl= incrementalClassificationNaiveBayes(___,Name,Value)uses either of the previous syntaxes to setpropertiesand additional options using name-value arguments. Enclose each name in quotes. For example,incrementalClassificationNaiveBayes('DistributionNames','mn','MaxNumClasses',5,'MetricsWarmupPeriod',100)specifies that the joint conditional distribution of the predictor variables is multinomial, sets the maximum number of classes expected in the response data to5, and sets the metrics warm-up period to100

Input Arguments

expand all

Maximum number of classes expected in the response data during incremental learning, specified as a positive integer.

MaxNumClassessets the number of class names in theClassNamesproperty.

If you do not specifyMaxNumClasses, you must specify theClassNamesargument.

Example:'MaxNumClasses',5

Data Types:single|double

All unique class labels expected in the response data during incremental learning, specified as a categorical, character, or string array; logical or numeric vector; or cell array of character vectors.ClassNamesand the response data must have the same data type. This argument sets theClassNamesproperty.

ClassNamesspecifies the order of any input or output argument dimension that corresponds to the class order. For example, set'ClassNames'to specify the order of the dimensions ofCostor the column order of classification scores returned bypredict

If you do not specifyClassNames, you must specify theMaxNumClassesargument. In that case, the software infers theClassNamesproperty from the data during incremental learning.

Example:'ClassNames',["virginica" "setosa" "versicolor"]

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

Name-Value Arguments

Specify optional pairs of arguments asName1=Value1,...,NameN=ValueN, whereNameis the argument name andValueis the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and encloseNamein quotes.

Example:'NumPredictors',4,'Prior',[0.3 0.3 0.4]specifies4variables in the predictor data and the prior class probability distribution of[0.3 0.3 0.4]

Cost of misclassifying an observation, specified as a value in this table, wherecis the number of classes in theClassNamesproperty:

Value Description
c-by-cnumeric matrix

Cost(i,j)is the cost of classifying an observation into classjwhen its true class isi, for classesClassNames(i)andClassNames(j)。In other words, the rows correspond to the true class and the columns correspond to the predicted class. For example,Cost = [0 2;1 0]applies double the penalty for misclassifyingClassNames(1)than for misclassifyingClassNames(2)

Structure array

A structure array having two fields:

  • ClassNamescontaining the class names, the same value asClassNames

  • ClassificationCostscontaining the cost matrix, as previously described.

If you specifyCost, you must also specify theClassNamesargument.Costsets theCostproperty.

The default is one of the following alternatives:

  • An empty array[]when you specifyMaxNumClasses

  • Ac-by-cmatrix when you specifyClassNames, whereCost(i,j) = 1for allij, andCost(i,j) = 0for alli=j

Example:'Cost',struct('ClassNames',{'b','g'},'ClassificationCosts',[0 2; 1 0])

Data Types:single|double|struct

Model performance metrics to track during incremental learning, in addition to minimal expected misclassification cost, specified as a built-in loss function name, string vector of names, function handle (for example,@metricName), structure array of function handles, or cell vector of names, function handles, or structure arrays.

WhenMdlis温暖的(seeIsWarm),updateMetricsandupdateMetricsAndFittrack performance metrics in theMetricsproperty ofMdl

The following table lists the built-in loss function names. You can specify more than one by using a string vector.

Name Description
"binodeviance" Binomial deviance
"classiferror" Misclassification error rate
"exponential" Exponential
"hinge" Hinge
"logit" Logistic
"mincost"

Minimal expected misclassification cost (for classification scores that are posterior probabilities).incrementalClassificationNaiveBayesalways tracks this metric.

"quadratic" Quadratic

For more details on the built-in loss functions, seeloss

Example:'Metrics',["classiferror" "logit"]

To specify a custom function that returns a performance metric, use function handle notation. The function must have this form.

metric = customMetric(C,S,Cost)

  • The output argumentmetricis ann-by-1 numeric vector, where each element is the loss of the corresponding observation in the data processed by the incremental learning functions during a learning cycle.

  • You specify the function name (here,customMetric).

  • Cis ann-by-Klogical matrix with rows indicating the class to which the corresponding observation belongs, whereKis the number of classes. The column order corresponds to the class order in theClassNamesproperty. CreateCby settingC(p,q)=1, if observationpis in classq, for each observation in the specified data. Set the other element in rowpto0

  • Sis ann-by-Knumeric matrix of predicted classification scores.Sis similar to thePosterioroutput ofpredict, where rows correspond to observations in the data and the column order corresponds to the class order in theClassNamesproperty.S(p,q)is the classification score of observationpbeing classified in classq

  • Costis aK-by-Knumeric matrix of misclassification costs. See the'Cost'name-value argument.

To specify multiple custom metrics and assign a custom name to each, use a structure array. To specify a combination of built-in and custom metrics, use a cell vector.

Example:'Metrics',struct('Metric1',@customMetric1,'Metric2',@customMetric2)

Example:'Metrics',{@customMetric1 @customMetric2 'logit' struct('Metric3',@customMetric3)}

updateMetricsandupdateMetricsAndFitstore specified metrics in a table in theMetricsproperty. The data type ofMetricsdetermines the row names of the table.

'Metrics'Value Data Type Description ofMetricsProperty Row Name Example
String or character vector Name of corresponding built-in metric Row name for"classiferror"is"ClassificationError"
Structure array Field name Row name forstruct('Metric1',@customMetric1)is"Metric1"
Function handle to function stored in a program file Name of function Row name for@customMetricis"customMetric"
Anonymous function CustomMetric_j, wherejis metricjinMetrics Row name for@ (C、S、成本)customMetric (C、S、成本)…isCustomMetric_1

For more details on performance metrics options, seePerformance Metrics

Data Types:char|string|struct|cell|function_handle

Properties

expand all

You can set most properties by using name-value pair argument syntax only when you callincrementalClassificationNaiveBayesdirectly. You can set some properties when you callincrementalLearnerto convert a traditionally trained model. You cannot set the propertiesDistributionParameters,IsWarm, andNumTrainingObservations

Classification Model Parameters

This property is read-only.

Categorical predictors list, specified as one of the values in this table.

Value Description
Vector of positive integers

Each entry in the vector is an index value corresponding to the column of the predictor data that contains a categorical variable. The index values are between 1 andNumPredictors

Logical vector Atrueentry means that the corresponding column of predictor data is a categorical variable. The length of the vector isNumPredictors
"all" All predictors are categorical.

For the identified categorical predictors,incrementalClassificationNaiveBayesuses multivariate multinomial distributions. For more details, seeDistributionNames

By default, if you specify theDistributionNamesoption, all predictor variables corresponding to'mvmn'are categorical. Otherwise, none of the predictor variables are categorical.

Example:'CategoricalPredictors',[1 2 4]and'CategoricalPredictors',[true true false true]specify that the first, second, and fourth of four predictor variables are categorical.

Data Types:single|double|logical

Levels of multivariate multinomial predictor variables, specified as a cell vector. The length ofCategoricalLevelsis equal toNumPredictors

Incremental fitting functionsfitandupdateMetricsAndFitpopulate cells with the learned numeric categorical levels of each categorical predictor variable, while cells corresponding to other predictor variables contain an empty array[]。Specifically, if predictorjis multivariate multinomial,CategoricalLevels{j}is a list of all distinct values of predictorjexperienced during incremental fitting. For more details, see theDistributionNamesproperty.

Note

Unlikefitcnb, incremental fitting functions order the levels of a predictor as the functions experience them during training. For example, suppose predictorjis categorical with multivariate multinomial distribution. The order of the levels inCategoricalLevels{j}and, consequently, the order of the level probabilities in each cell ofDistributionParameters{:,j}returned by incremental fitting functions can differ from the order returned byfitcnbfor the same training data set.

This property is read-only.

Cost of misclassifying an observation, specified as an array.

If you specify the'Cost'name-value argument, its value setsCost。If you specify a structure array,Costis the value of theClassificationCostsfield.

If you convert a traditionally trained model to createMdl,Costis theCostproperty of the traditionally trained model.

Data Types:single|double

This property is read-only.

All unique class labels expected in the response data during incremental learning, specified as a categorical or character array, a logical or numeric vector, or a cell array of character vectors.

You can setClassNamesin one of three ways:

  • If you specify theMaxNumClassesargument, the software infers theClassNamesproperty during incremental learning.

  • If you specify theClassNamesargument,incrementalClassificationNaiveBayesstores your specification in theClassNamesproperty.(The software treats string arrays as cell arrays of character vectors.)

  • If you convert a traditionally trained model to createMdl, theClassNamesproperty is specified by the corresponding property of the traditionally trained model.

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

This property is read-only.

Number of predictor variables, specified as a nonnegative numeric scalar.

The defaultNumPredictorsvalue depends on how you create the model:

  • If you convert a traditionally trained model to createMdl,NumPredictorsis specified by the corresponding property of the traditionally trained model.

  • If you createMdlby callingincrementalClassificationNaiveBayesdirectly, you can specifyNumPredictorsby using name-value argument syntax. If you do not specify the value, then the default value is0, and incremental fitting functions inferNumPredictorsfrom the predictor data during training.

Data Types:double

This property is read-only.

Number of observations fit to the incremental modelMdl, specified as a nonnegative numeric scalar.NumTrainingObservationsincreases when you passMdland training data tofitorupdateMetricsAndFit

Note

If you convert a traditionally trained model to createMdl,incrementalClassificationNaiveBayesdoes not add the number of observations fit to the traditionally trained model toNumTrainingObservations

Data Types:double

This property is read-only.

Prior class probabilities, specified as'empirical','uniform', or a numeric vector.incrementalClassificationNaiveBayesstores thePriorvalue as a numeric vector.

Value Description
'empirical' Incremental learning functions infer prior class probabilities from the observed class relative frequencies in the response data during incremental training.
'uniform' For each class, the prior probability is 1/K, whereKis the number of classes.
numeric vector Custom, normalized prior probabilities. The order of the elements ofPriorcorresponds to the elements of theClassNamesproperty.

The defaultPriorvalue depends on how you create the model:

  • If you convert a traditionally trained model to createMdl,Prioris specified by the corresponding property of the traditionally trained model.

  • Otherwise, the default value ofPrioris'empirical'

Data Types:single|double|char|string

This property is read-only.

Score transformation function describing how incremental learning functions transform raw response values, specified as a character vector, string scalar, or function handle.incrementalClassificationNaiveBayesstores the specified value as a character vector or function handle.

This table describes the available built-in functions for score transformation.

Value Description
"doublelogit" 1/(1 +e–2x)
"invlogit" log(x/ (1 –x))
"ismax" Sets the score for the class with the largest score to 1, and sets the scores for all other classes to 0
"logit" 1/(1 +ex)
"none"or"identity" x(no transformation)
"sign" –1 forx< 0
0 forx= 0
1 forx> 0
"symmetric" 2x– 1
"symmetricismax" Sets the score for the class with the largest score to 1, and sets the scores for all other classes to –1
"symmetriclogit" 2/(1 +ex) – 1

For a MATLAB®function or a function that you define, enter its function handle; for example,@function, where:

  • functionaccepts ann-by-Kmatrix (the original scores) and returns a matrix of the same size (the transformed scores).

  • nis the number of observations, and rowjof the matrix contains the class scores of observationj

  • Kis the number of classes, and columnkis classClassNames(k)

The defaultScoreTransformvalue depends on how you create the model:

  • If you convert a traditionally trained model to createMdl,ScoreTransformis specified by the corresponding property of the traditionally trained model.

  • The default'none'specifies returning posterior class probabilities.

Data Types:char|function_handle|string

Training Parameters

Predictor distributions P(x|ck), whereckis classClassNames(k), specified as a character vector or string scalar, or a 1-by-NumPredictorsstring vector or cell vector of character vectors with values from the table.

Value Description
"mn" Multinomial distribution. If you specify"mn", then all features are components of a multinomial distribution (for example, abag-of-tokensmodel). Therefore, you cannot include"mn"as an element of a string array or a cell array of character vectors. For details, seeEstimated Probability for Multinomial Distribution
"mvmn" Multivariate multinomial distribution. For details, seeEstimated Probability for Multivariate Multinomial Distribution
"normal" Normal distribution. For details, seeNormal Distribution Estimators

If you specify a character vector or string scalar, then the software models all the features using that distribution. If you specify a 1-by-NumPredictorsstring vector or cell vector of character vectors, the software models featurejusing the distribution in elementjof the vector.

By default, the software sets all predictors specified as categorical predictors (see theCategoricalPredictorsproperty) to'mvmn'。Otherwise, the default distribution is'normal'

incrementalClassificationNaiveBayesstores the value as a character vector or cell vector of character vectors.

Example:“DistributionNames”、“锰”specifies that the joint conditional distribution of all predictor variables is multinomial.

Example:'DistributionNames',["normal" "mvmn" "normal"]specifies that the first and third predictor variables are normally distributed and the second variable is categorical with a multivariate multinomial distribution.

Data Types:char|string|cell

This property is read-only.

Distribution parameter estimates, specified as a cell array.DistributionParametersis aK-by-NumPredictorscell array, whereKis the number of classes and cell (k,j) contains the distribution parameter estimates for instances of predictorjin classk。The order of the rows corresponds to the order of the classes in the propertyClassNames, and the order of the columns corresponds to the order of the predictors in the predictor data.

If classkhas no observations for predictorj, thenDistributionParameters{k,j}is empty ([]).

The elements ofDistributionParametersdepend on the distributions of the predictors. This table describes the values inDistributionParameters{k,j}

Distribution of Predictorj Value of Cell Array for Predictorjand Classk
'mn' A scalar representing the probability that tokenjappears in classk。为依据ails, seeEstimated Probability for Multinomial Distribution
'mvmn' A numeric vector containing the probabilities for each possible level of predictorjin classk。The software orders the probabilities by the sorted order of all unique levels of predictorj(stored in the propertyCategoricalLevels). For more details, seeEstimated Probability for Multivariate Multinomial Distribution
'normal' A 2-by-1 numeric vector. The first element is the weighted sample mean and the second element is the weighted sample standard deviation. For more details, seeNormal Distribution Estimators

Note

Unlikefitcnb, incremental fitting functions order the levels of a predictor as the functions experience them during training. For example, suppose predictorjis categorical with multivariate multinomial distribution. The order of the levels inCategoricalLevels{j}and, consequently, the order of the level probabilities in each cell ofDistributionParameters{:,j}returned by incremental fitting functions can differ from the order returned byfitcnbfor the same training data set.

Data Types:cell

性能指标参数

Flag indicating whether the incremental model tracks performance metrics, specified as logical0(false) or1(true).

The incremental modelMdlis温暖的(IsWarmbecomestrue) when incremental fitting functions perform both of these actions:

  • Fit the incremental model toMetricsWarmupPeriodobservations.

  • ProcessMaxNumClassesclasses or all class names specified by theClassNamesname-value argument.

Value Description
trueor1 The incremental modelMdlis warm. Consequently,updateMetricsandupdateMetricsAndFittrack performance metrics in theMetricsproperty ofMdl
falseor0 updateMetricsandupdateMetricsAndFitdo not track performance metrics.

Data Types:logical

This property is read-only.

Model performance metrics updated during incremental learning byupdateMetricsandupdateMetricsAndFit, specified as a table with two columns andmrows, wheremis the number of metrics specified by theMetricsname-value argument.

The columns ofMetricsare labeledCumulativeandWindow

  • Cumulative: Elementjis the model performance, as measured by metricj, from the time the model became warm (IsWarmis1).

  • Window: Elementjis the model performance, as measured by metricj, evaluated over all observations within the window specified by theMetricsWindowSizeproperty. The software updatesWindowafter it processesMetricsWindowSizeobservations.

行标记指定的指标。为依据ails, see theMetricsname-value argument ofincrementalLearnerorincrementalClassificationNaiveBayes

Data Types:table

This property is read-only.

Number of observations the incremental model must be fit to before it tracks performance metrics in itsMetricsproperty, specified as a nonnegative integer.

The defaultMetricsWarmupPeriodvalue depends on how you create the model:

  • If you convert a traditionally trained model to createMdl, theMetricsWarmupPeriodname-value argument of theincrementalLearnerfunction sets this property. The default value of the argument is0

  • Otherwise, the default value is1000

For more details, seePerformance Metrics

Data Types:single|double

This property is read-only.

Number of observations to use to compute window performance metrics, specified as a positive integer.

The defaultMetricsWindowSizevalue depends on how you create the model:

  • If you convert a traditionally trained model to createMdl, theMetricsWindowSizename-value argument of theincrementalLearnerfunction sets this property. The default value of the argument is200

  • Otherwise, the default value is200

For more details on performance metrics options, seePerformance Metrics

Data Types:single|double

Object Functions

fit Train naive Bayes classification model for incremental learning
updateMetricsAndFit Update performance metrics in naive Bayes incremental learning classification model given new data and train model
updateMetrics Update performance metrics in naive Bayes incremental learning classification model given new data
logp Log unconditional probability density of naive Bayes classification model for incremental learning
loss Loss of naive Bayes incremental learning classification model on batch of data
predict Predict responses for new observations from naive Bayes incremental learning classification model
perObservationLoss Per observation classification error of model for incremental learning
reset Reset incremental classification model

Examples

collapse all

To create a naive Bayes classification model for incremental learning, you must specify the maximum number of classes that you expect the model to process ('MaxNumClasses'name-value argument). As you fit the model to incoming batches of data by using an incremental fitting function, the model collects new classes in itsClassNamesproperty. If the specified maximum number of classes is inaccurate, one of the following occurs:

  • Before an incremental fitting function processes the expected maximum number of classes, the model is cold. Consequently, theupdateMetricsandupdateMetricsAndFitfunctions do not measure performance metrics.

  • If the number of classes exceeds the maximum expected, the incremental fitting function issues an error.

This example shows how to create a naive Bayes classification model for incremental learning when the only information you specify is the expected maximum number of classes in the data. Also, the example illustrates the consequences when incremental fitting functions process all expected classes early and late in the sample.

For this example, consider training a device to predict whether a subject is sitting, standing, walking, running, or dancing based on biometric data measured on the subject. Therefore, the device has a maximum of 5 classes from which to choose.

Process Expected Maximum Number of Classes Early in Sample

Create an incremental naive Bayes model for multiclass learning. Specify a maximum of 5 classes in the data.

MdlEarly = incrementalClassificationNaiveBayes('MaxNumClasses',5)
MdlEarly = incrementalClassificationNaiveBayes IsWarm: 0 Metrics: [1x2 table] ClassNames: [1x0 double] ScoreTransform: 'none' DistributionNames: 'normal' DistributionParameters: {} Properties, Methods

MdlEarlyis anincrementalClassificationNaiveBayesmodel object. All its properties are read-only.

MdlEarlymust be fit to data before you can use it to perform any other operations.

Load the human activity data set. Randomly shuffle the data.

loadhumanactivityn = numel(actid); rng(1);% For reproducibilityidx = randsample(n,n); X = feat(idx,:); Y = actid(idx);

为依据ails on the data set, enterDescriptionat the command line.

Fit the incremental model to the training data by using theupdateMetricsAndFitfunction. Simulate a data stream by processing chunks of 50 observations at a time. At each iteration:

  • Process 50 observations.

  • Overwrite the previous incremental model with a new one fitted to the incoming observations.

  • Store the mean of the first predictor in the first class μ 11 , the cumulative metrics, and the window metrics to see how they evolve during incremental learning.

% PreallocationnumObsPerChunk = 50; nchunk = floor(n/numObsPerChunk); mc = array2table(zeros(nchunk,2),'VariableNames',["Cumulative""Window"]); mu1 = zeros(nchunk,1);% Incremental learningforj = 1:nchunk ibegin = min(n,numObsPerChunk*(j-1) + 1); iend = min(n,numObsPerChunk*j); idx = ibegin:iend; MdlEarly = updateMetricsAndFit(MdlEarly,X(idx,:),Y(idx)); mc{j,:} = MdlEarly.Metrics{"MinimalCost",:}; mu1(j + 1) = MdlEarly.DistributionParameters{1,1}(1);end

MdlEarlyis anincrementalClassificationNaiveBayesmodel object trained on all the data in the stream. During incremental learning and after the model is warmed up,updateMetricsAndFitchecks the performance of the model on the incoming observations, and then fits the model to those observations.

To see how the performance metrics and μ 11 evolve during training, plot them on separate tiles.

t = tiledlayout(2,1); nexttile plot(mu1) ylabel('\mu_{11}') xlim([0 nchunk]) nexttile h = plot(mc.Variables); xlim([0 nchunk]) ylabel('Minimal Cost') xline(MdlEarly.MetricsWarmupPeriod/numObsPerChunk,'r-.') legend(h,mc.Properties.VariableNames) xlabel(t,'Iteration')

图包含2轴对象。坐标轴对象1续ains an object of type line. Axes object 2 contains 3 objects of type line, constantline. These objects represent Cumulative, Window.

The plots indicate thatupdateMetricsAndFitperforms the following actions:

  • Fit μ 11 during all incremental learning iterations.

  • Compute the performance metrics after the metrics warm-up period (red vertical line) only.

  • Compute the cumulative metrics during each iteration.

  • Compute the window metrics after processing 200 observations (4 iterations).

Process Expected Maximum Number of Classes Late in Sample

Create a different naive Bayes model for incremental learning for the objective.

MdlLate = incrementalClassificationNaiveBayes('MaxNumClasses',5)
MdlLate = incrementalClassificationNaiveBayes IsWarm: 0 Metrics: [1x2 table] ClassNames: [1x0 double] ScoreTransform: 'none' DistributionNames: 'normal' DistributionParameters: {} Properties, Methods

Move all observations labeled with class 5 to the end of the sample.

idx5 = Y == 5; Xnew = [X(~idx5,:); X(idx5,:)]; Ynew = [Y(~idx5) ;Y(idx5)];

Fit the incremental model and plot the results.

mcnew = array2table(zeros(nchunk,2),'VariableNames',["Cumulative""Window"]); mu1new = zeros(nchunk,1);forj = 1:nchunk ibegin = min(n,numObsPerChunk*(j-1) + 1); iend = min(n,numObsPerChunk*j); idx = ibegin:iend; MdlLate = updateMetricsAndFit(MdlLate,Xnew(idx,:),Ynew(idx)); mcnew{j,:} = MdlLate.Metrics{"MinimalCost",:}; mu1new(j + 1) = MdlLate.DistributionParameters{1,1}(1);endt = tiledlayout(2,1); nexttile plot(mu1new) ylabel('\mu_{11}') xlim([0 nchunk]) nexttile h = plot(mcnew.Variables); xlim([0 nchunk]); ylabel('Minimal Cost') xline(MdlLate.MetricsWarmupPeriod/numObsPerChunk,'r-.') xline(sum(~idx5)/numObsPerChunk,'g-.') legend(h,mcnew.Properties.VariableNames,'Location','best') xlabel(t,'Iteration')

图包含2轴对象。坐标轴对象1续ains an object of type line. Axes object 2 contains 4 objects of type line, constantline. These objects represent Cumulative, Window.

TheupdateMetricsAndFitfunction trains the model throughout incremental learning, but the function starts tracking performance metrics only after the model is fit to all expected number of classes (the green vertical line in the bottom tile).

Create an incremental naive Bayes model when you know all the class names in the data.

Consider training a device to predict whether a subject is sitting, standing, walking, running, or dancing based on biometric data measured on the subject. The class names map 1 through 5 to an activity.

Create an incremental naive Bayes model for multiclass learning. Specify the class names.

classnames = 1:5; Mdl = incrementalClassificationNaiveBayes('ClassNames',classnames)
Mdl = incrementalClassificationNaiveBayes IsWarm: 0 Metrics: [1x2 table] ClassNames: [1 2 3 4 5] ScoreTransform: 'none' DistributionNames: 'normal' DistributionParameters: {5x0 cell} Properties, Methods

Mdlis anincrementalClassificationNaiveBayesmodel object. All its properties are read-only.

Mdlmust be fit to data before you can use it to perform any other operations.

Load the human activity data set. Randomly shuffle the data.

loadhumanactivityn = numel(actid); rng(1);% For reproducibilityidx = randsample(n,n); X = feat(idx,:); Y = actid(idx);

为依据ails on the data set, enterDescriptionat the command line.

Fit the incremental model to the training data by using theupdateMetricsAndFitfunction. Simulate a data stream by processing chunks of 50 observations at a time. At each iteration:

  • Process 50 observations.

  • Overwrite the previous incremental model with a new one fitted to the incoming observations.

% PreallocationnumObsPerChunk = 50; nchunk = floor(n/numObsPerChunk);% Incremental learningforj = 1:nchunk ibegin = min(n,numObsPerChunk*(j-1) + 1); iend = min(n,numObsPerChunk*j); idx = ibegin:iend; Mdl = updateMetricsAndFit(Mdl,X(idx,:),Y(idx));end

In addition to specifying the maximum number of class names, prepare an incremental naive Bayes learner by specifying a metrics warm-up period, during which theupdateMetricsAndFitfunction fits only the model. Specify a metrics window size of 500 observations.

Load the human activity data set. Randomly shuffle the data.

loadhumanactivityn = numel(actid); rng(1);% For reproducibilityidx = randsample(n,n); X = feat(idx,:); Y = actid(idx);

The class names map 1 through 5 to an activity—sitting, standing, walking, running, or dancing, respectively—based on biometric data measured on the subject. For details on the data set, enterDescriptionat the command line.

Create an incremental naive Bayes model for multiclass learning. Configure the model as follows:

  • Specify a metrics warm-up period of 5000 observations.

  • Specify a metrics window size of 500 observations.

  • Double the penalty to the classifier when it mistakenly classifies class 2.

  • Track the classification error and minimal cost to measure the performance of the model. You do not have to specify'mincost'forMetricsbecauseincrementalClassificationNaiveBayesalways tracks this metric.

C =的眼睛(5)- (5);C (2,[1 3 4 5]) = 2; Mdl = incrementalClassificationNaiveBayes('ClassNames',1:5,。..'MetricsWarmupPeriod',5000,'MetricsWindowSize',500,。..'Cost',C,'Metrics','classiferror')
Mdl = incrementalClassificationNaiveBayes IsWarm: 0 Metrics: [2x2 table] ClassNames: [1 2 3 4 5] ScoreTransform: 'none' DistributionNames: 'normal' DistributionParameters: {5x0 cell} Properties, Methods

Mdlis anincrementalClassificationNaiveBayesmodel object configured for incremental learning.

适合增量模型的数据by using theupdateMetricsAndFitfunction. At each iteration:

  • Simulate a data stream by processing a chunk of 50 observations.

  • Overwrite the previous incremental model with a new one fitted to the incoming observations.

  • Store the standard deviation of the first predictor variable in the first class σ 11 , the cumulative metrics, and the window metrics to see how they evolve during incremental learning.

% PreallocationnumObsPerChunk = 50; nchunk = floor(n/numObsPerChunk); ce = array2table(zeros(nchunk,2),'VariableNames',["Cumulative""Window"]); mc = array2table(zeros(nchunk,2),'VariableNames',["Cumulative""Window"]); sigma11 = zeros(nchunk,1);% Incremental fittingforj = 1:nchunk ibegin = min(n,numObsPerChunk*(j-1) + 1); iend = min(n,numObsPerChunk*j); idx = ibegin:iend; Mdl = updateMetricsAndFit(Mdl,X(idx,:),Y(idx)); ce{j,:} = Mdl.Metrics{"ClassificationError",:}; mc{j,:} = Mdl.Metrics{"MinimalCost",:}; sigma11(j + 1) = Mdl.DistributionParameters{1,1}(2);end

Mdlis anincrementalClassificationNaiveBayesmodel object trained on all the data in the stream. During incremental learning and after the model is warmed up,updateMetricsAndFitchecks the performance of the model on the incoming observations, and then fits the model to those observations.

To see how the performance metrics and σ 11 evolve during training, plot them on separate tiles.

tiledlayout(2,2) nexttile plot(sigma11) ylabel('\sigma_{11}') xlim([0 nchunk]); xline(Mdl.MetricsWarmupPeriod/numObsPerChunk,'r-.') xlabel('Iteration') nexttile h = plot(ce.Variables); xlim([0 nchunk]) ylabel('Classification Error') xline(Mdl.MetricsWarmupPeriod/numObsPerChunk,'r-.') legend(h,ce.Properties.VariableNames) xlabel('Iteration') nexttile h = plot(mc.Variables); xlim([0 nchunk]); ylabel('Minimal Cost') xline(Mdl.MetricsWarmupPeriod/numObsPerChunk,'r-.') legend(h,mc.Properties.VariableNames) xlabel('Iteration')

Figure contains 3 axes objects. Axes object 1 contains 2 objects of type line, constantline. Axes object 2 contains 3 objects of type line, constantline. These objects represent Cumulative, Window. Axes object 3 contains 3 objects of type line, constantline. These objects represent Cumulative, Window.

The plots indicate thatupdateMetricsAndFitperforms the following actions:

  • Fit σ 11 during all incremental learning iterations.

  • Compute the performance metrics after the metrics warm-up period (red vertical line) only.

  • Compute the cumulative metrics during each iteration.

  • Compute the window metrics after processing 500 observations (10 iterations).

Train a naive Bayes model for multiclass classification by usingfitcnb。Then, convert the model to an incremental learner, track its performance, and fit the model to streaming data. Carry over training options from traditional to incremental learning.

Load and Preprocess Data

Load the human activity data set. Randomly shuffle the data.

loadhumanactivityrng(1)% For reproducibilityn = numel(actid); idx = randsample(n,n); X = feat(idx,:); Y = actid(idx);

为依据ails on the data set, enterDescriptionat the command line.

Suppose that the data collected when the subject was idle (Y<= 2) has double the quality than when the subject was moving. Create a weight variable that attributes 2 to observations collected from an idle subject, and 1 to a moving subject.

W = ones(n,1) + (Y <= 2);

Train Naive Bayes Model

Fit a naive Bayes model for multiclass classification to a random sample of half the data.

idxtt = randsample([true false],n,true); TTMdl = fitcnb(X(idxtt,:),Y(idxtt),'Weights',W(idxtt))
TTMdl = ClassificationNaiveBayes ResponseName: 'Y' CategoricalPredictors: [] ClassNames: [1 2 3 4 5] ScoreTransform: 'none' NumObservations: 12053 DistributionNames: {1x60 cell} DistributionParameters: {5x60 cell} Properties, Methods

TTMdlis aClassificationNaiveBayesmodel object representing a traditionally trained naive Bayes model.

Convert Trained Model

Convert the traditionally trained naive Bayes model to a naive Bayes classification model for incremental learning.

IncrementalMdl = incrementalLearner(TTMdl)
IncrementalMdl = incrementalClassificationNaiveBayes IsWarm: 1 Metrics: [1x2 table] ClassNames: [1 2 3 4 5] ScoreTransform: 'none' DistributionNames: {1x60 cell} DistributionParameters: {5x60 cell} Properties, Methods

Separately Track Performance Metrics and Fit Model

Perform incremental learning on the rest of the data by using theupdateMetricsandfitfunctions. Simulate a data stream by processing 50 observations at a time. At each iteration:

  1. CallupdateMetricsto update the cumulative and window classification error of the model given the incoming chunk of observations. Overwrite the previous incremental model to update the losses in theMetricsproperty. Note that the function does not fit the model to the chunk of data—the chunk is "new" data for the model. Specify the observation weights.

  2. Callfitto fit the model to the incoming chunk of observations. Overwrite the previous incremental model to update the model parameters. Specify the observation weights.

  3. Store the minimal cost and mean of the first predictor variable of the first class μ 11

% Preallocationidxil = ~idxtt; nil = sum(idxil); numObsPerChunk = 50; nchunk = floor(nil/numObsPerChunk); mc = array2table(zeros(nchunk,2),'VariableNames',["Cumulative""Window"]); mu11 = [IncrementalMdl.DistributionParameters{1,1}(1); zeros(nchunk,1)]; Xil = X(idxil,:); Yil = Y(idxil); Wil = W(idxil);% Incremental fittingforj = 1:nchunk ibegin = min(nil,numObsPerChunk*(j-1) + 1); iend = min(nil,numObsPerChunk*j); idx = ibegin:iend; IncrementalMdl = updateMetrics(IncrementalMdl,Xil(idx,:),Yil(idx),。..'Weights',Wil(idx)); mc{j,:} = IncrementalMdl.Metrics{"MinimalCost",:}; IncrementalMdl = fit(IncrementalMdl,Xil(idx,:),Yil(idx),'Weights',Wil(idx)); mu11(j+1) = IncrementalMdl.DistributionParameters{1,1}(1);end

IncrementalMdlis anincrementalClassificationNaiveBayesmodel object trained on all the data in the stream.

Alternatively, you can useupdateMetricsAndFitto update the performance metrics of the model given a new chunk of data, and then fit the model to the data.

Plot a trace plot of the performance metrics and μ 11

t = tiledlayout(2,1); nexttile h = plot(mc.Variables); xlim([0 nchunk]) ylabel('Minimal Cost') legend(h,mc.Properties.VariableNames) nexttile plot(mu11) ylabel('\mu_{11}') xlim([0 nchunk]) xlabel(t,'Iteration')

图包含2轴对象。坐标轴对象1续ains 2 objects of type line. These objects represent Cumulative, Window. Axes object 2 contains an object of type line.

The cumulative loss levels quickly and is stable, whereas the window loss jumps throughout the training.

μ 11 changes abruptly at first, then gradually levels off asfitprocesses more chunks.

More About

expand all

Algorithms

expand all

References

[1] Manning, Christopher D., Prabhakar Raghavan, and Hinrich Schütze.Introduction to Information Retrieval, NY: Cambridge University Press, 2008.

Version History

Introduced in R2021a

expand all