incrementalLearner - Convert naive Bayes classification model to incremental learner - MATLAB (original) (raw)

Convert naive Bayes classification model to incremental learner

Since R2021a

Syntax

Description

[IncrementalMdl](#mw%5Fc3ae089d-221b-445d-a4f4-2994a9231a75) = incrementalLearner([Mdl](#mw%5Fcc61bc07-2701-4215-b2bd-6c540d606104)) returns a naive Bayes classification model for incremental learning,IncrementalMdl, using the hyperparameters of the traditionally trained naive Bayes classification model Mdl. Because its property values reflect the knowledge gained from Mdl,IncrementalMdl can predict labels given new observations, and it is_warm_, meaning that its predictive performance is tracked.

example

[IncrementalMdl](#mw%5Fc3ae089d-221b-445d-a4f4-2994a9231a75) = incrementalLearner([Mdl](#mw%5Fcc61bc07-2701-4215-b2bd-6c540d606104),[Name,Value](#namevaluepairarguments)) uses additional options specified by one or more name-value arguments. Some options require you to train IncrementalMdl before its predictive performance is tracked. For example,'MetricsWarmupPeriod',50,'MetricsWindowSize',100 specifies a preliminary incremental training period of 50 observations before performance metrics are tracked, and specifies processing 100 observations before updating the window performance metrics.

example

Examples

collapse all

Train a naive Bayes model by using fitcnb, and then convert it to an incremental learner.

Load and Preprocess Data

Load the human activity data set.

For details on the data set, enter Description at the command line.

Train Naive Bayes Model

Fit a naive Bayes classification model to the entire data set.

TTMdl = fitcnb(feat,actid);

TTMdl is a ClassificationNaiveBayes model object representing a traditionally trained naive Bayes classification model.

Convert Trained Model

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

IncrementalMdl = incrementalLearner(TTMdl)

IncrementalMdl = incrementalClassificationNaiveBayes

                IsWarm: 1
               Metrics: [1×2 table]
            ClassNames: [1 2 3 4 5]
        ScoreTransform: 'none'
     DistributionNames: {1×60 cell}
DistributionParameters: {5×60 cell}

Properties, Methods

IncrementalMdl is an incrementalClassificationNaiveBayes model object prepared for incremental learning using naive Bayes classification.

Predict Responses

An incremental learner created from converting a traditionally trained model can generate predictions without further processing.

Predict classification scores (class posterior probabilities) for all observations using both models.

[,ttscores] = predict(TTMdl,feat); [,ilcores] = predict(IncrementalMdl,feat); compareScores = norm(ttscores - ilcores)

The difference between the scores generated by the models is 0.

Use a trained naive Bayes model to initialize an incremental learner. Prepare the incremental learner by specifying a metrics warm-up period, during which the updateMetricsAndFit function only fits the model. Specify a metrics window size of 500 observations.

Load the human activity data set.

For details on the data set, enter Description at the command line.

Randomly split the data in half: the first half for training a model traditionally, and the second half for incremental learning.

n = numel(actid);

rng(1) % For reproducibility cvp = cvpartition(n,'Holdout',0.5); idxtt = training(cvp); idxil = test(cvp);

% First half of data Xtt = feat(idxtt,:); Ytt = actid(idxtt);

% Second half of data Xil = feat(idxil,:); Yil = actid(idxil);

Fit a naive Bayes model to the first half of the data. Suppose you want to double the penalty to the classifier when it mistakenly classifies class 2.

C = ones(5) - eye(5); C(2,[1 3 4 5]) = 2; TTMdl = fitcnb(Xtt,Ytt,'Cost',C);

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

IncrementalMdl = incrementalLearner(TTMdl,'MetricsWarmupPeriod',2000,'MetricsWindowSize',500,... 'Metrics','classiferror');

Fit the incremental model to the second half of the data by using the updateMetricsAndFit function. At each iteration:

% Preallocation nil = numel(Yil); numObsPerChunk = 20; nchunk = ceil(nil/numObsPerChunk); ce = array2table(zeros(nchunk,2),'VariableNames',["Cumulative" "Window"]); mc = array2table(zeros(nchunk,2),'VariableNames',["Cumulative" "Window"]); mu12 = [IncrementalMdl.DistributionParameters{1,2}(1); zeros(nchunk,1)];

% Incremental fitting for j = 1:nchunk ibegin = min(nil,numObsPerChunk*(j-1) + 1); iend = min(nil,numObsPerChunk*j); idx = ibegin:iend;
IncrementalMdl = updateMetricsAndFit(IncrementalMdl,Xil(idx,:),Yil(idx)); ce{j,:} = IncrementalMdl.Metrics{"ClassificationError",:}; mc{j,:} = IncrementalMdl.Metrics{"MinimalCost",:}; mu12(j + 1) = IncrementalMdl.DistributionParameters{1,2}(1); end

IncrementalMdl is an incrementalClassificationNaiveBayes model object trained on all the data in the stream. During incremental learning and after the model is warmed up, updateMetricsAndFit checks the performance of the model on the incoming observations, and then fits the model to those observations.

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

t = tiledlayout(3,1); nexttile plot(mu12) ylabel('\mu_{12}') xlim([0 nchunk]); xline(IncrementalMdl.MetricsWarmupPeriod/numObsPerChunk,'r-.'); nexttile h = plot(ce.Variables); xlim([0 nchunk]); ylabel('Classification Error') xline(IncrementalMdl.MetricsWarmupPeriod/numObsPerChunk,'r-.'); legend(h,ce.Properties.VariableNames,'Location','northwest') nexttile h = plot(mc.Variables); xlim([0 nchunk]); ylabel('Minimal Cost') xline(IncrementalMdl.MetricsWarmupPeriod/numObsPerChunk,'r-.'); legend(h,mc.Properties.VariableNames,'Location','northwest') xlabel(t,'Iteration')

Figure contains 3 axes objects. Axes object 1 with ylabel \mu_{12} contains 2 objects of type line, constantline. Axes object 2 with ylabel Classification Error contains 3 objects of type line, constantline. These objects represent Cumulative, Window. Axes object 3 with ylabel Minimal Cost contains 3 objects of type line, constantline. These objects represent Cumulative, Window.

The plots indicate that updateMetricsAndFit performs the following actions:

Because the data is ordered by activity, the mean and performance metrics periodically change abruptly.

Input Arguments

collapse all

Traditionally trained naive Bayes model for multiclass classification, specified as a ClassificationNaiveBayes model object returned by fitcnb. The conditional distribution of each predictor variable, as stored in Mdl.DistributionNames, cannot be a kernel distribution.

Name-Value Arguments

collapse all

Specify optional pairs of arguments asName1=Value1,...,NameN=ValueN, where Name is the argument name and Value is 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 enclose Name in quotes.

Example: 'Metrics',["classiferror" "mincost"],'MetricsWindowSize',100 specifies tracking the misclassification rate and minimal cost, and specifies processing 100 observations before updating the window performance metrics.

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

Data Types: single | double

Data Types: single | double

Output Arguments

collapse all

Naive Bayes classification model for incremental learning, returned as an incrementalClassificationNaiveBayes model object. IncrementalMdl is also configured to generate predictions given new data (see predict).

incrementalLearner initializes IncrementalMdl for incremental learning using the model information in Mdl. The following table shows the Mdl properties thatincrementalLearner passes to corresponding properties ofIncrementalMdl. The function also uses other model properties required to initialize IncrementalMdl, such as Y (class labels) and W (observation weights).

Property Description
CategoricalLevels Multivariate multinomial predictor levels, a cell array with length equal to NumPredictors
CategoricalPredictors Categorical predictor indices, a vector of positive integers
ClassNames Class labels for binary classification, a list of names
Cost Misclassification costs, a numeric matrix
DistributionNames Names of the conditional distributions of the predictor variables, either a cell array in which each cell contains 'normal' or'mvmn', or the value 'mn'
DistributionParameters Parameter values of the conditional distributions of the predictor variables, a cell array of length 2 numeric vectors (for details, seeDistributionParameters)
NumPredictors Number of predictors, a positive integer
Prior Prior class label distribution, a numeric vector
ScoreTransform Score transformation function, a function name or function handle

More About

collapse all

Incremental learning, or online learning, is a branch of machine learning concerned with processing incoming data from a data stream, possibly given little to no knowledge of the distribution of the predictor variables, aspects of the prediction or objective function (including tuning parameter values), or whether the observations are labeled. Incremental learning differs from traditional machine learning, where enough labeled data is available to fit to a model, perform cross-validation to tune hyperparameters, and infer the predictor distribution.

Given incoming observations, an incremental learning model processes data in any of the following ways, but usually in this order:

For more details, see Incremental Learning Overview.

Algorithms

collapse all

Version History

Introduced in R2021a