# incrementalLearner

Convert naive Bayes classification model to incremental learner

## Description

returns a naive Bayes classification model for incremental learning, `IncrementalMdl`

= incrementalLearner(`Mdl`

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

uses additional options specified by one or more name-value pair arguments. Some options require you to train `IncrementalMdl`

= incrementalLearner(`Mdl`

,`Name,Value`

)`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 performance metrics.

## Examples

### Convert Traditionally Trained Model to Incremental Learner

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.

`load humanactivity`

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

`IncrementalMdl`

is an `incrementalClassificationNaiveBayes`

model object prepared for incremental learning using naive Bayes classification.

The

`incrementalLearner`

function Initializes the incremental learner by passing learned conditional predictor distribution parameters to it, along with other information`TTMdl`

extracted from the training data.`IncrementalMdl`

is warm (`IsWarm`

is`1`

), which means that incremental learning functions can track performance metrics and make predictions.

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

compareScores = 0

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

### Configure Performance Metric Options

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.

`load humanactivity`

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.

TTMdl = fitcnb(Xtt,Ytt);

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

A performance metrics warm-up period of 2000 observations

A metrics window size of 500 observations

Use of classification error and minimal cost to measure the performance of the model

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

Fit the incremental model to the second half of the data by using the `updateMetricsAndfit`

function. At each iteration:

Simulate a data stream by processing 20 observations at a time.

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

Store the mean of the second predictor within the first class ${\mu}_{12}$, the cumulative metrics, and the window metrics to see how they evolve during incremental learning.

% 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 = 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 observation, and then fits the model to that observation.

To see how the performance metrics and ${\mu}_{12}$ evolved during training, plot them on separate subplots.

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

The plot suggests that `updateMetricsAndFit`

does the following:

Fit ${\mu}_{12}$ during all incremental learning iterations.

Compute performance metrics after the metrics warm-up period only.

Compute the cumulative metrics during each iteration.

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

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

## Input Arguments

`Mdl`

— Traditionally trained naive Bayes model for multiclass classification

`ClassificationNaiveBayes`

model object

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

Specify optional
comma-separated pairs of `Name,Value`

arguments. `Name`

is
the argument name and `Value`

is the corresponding value.
`Name`

must appear inside quotes. You can specify several name and value
pair arguments in any order as
`Name1,Value1,...,NameN,ValueN`

.

**Example:**

`'Metrics',["classiferror" "mincost"],'MetricsWindowSize',100`

specifies tracking the misclassification rate and minimal cost, and specifies processing 100 observations before updating the performance metrics.`Metrics`

— Model performance metrics to track during incremental learning

`"mincost"`

(default) | `"classiferror"`

| string vector | function handle | cell vector | structure array | `"binodeviance"`

| `"exponential"`

| `"hinge"`

| `"logit"`

| `"quadratic"`

| ...

Model performance metrics to track during incremental learning with the `updateMetrics`

or `updateMetricsAndFit`

function, specified as a built-in loss function name, string vector of names, function handle (`@metricName`

), structure array of function handles, or cell vector of names, function handles, or structure arrays.

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"` | Classification error |

`"exponential"` | Exponential |

`"hinge"` | Hinge |

`"logit"` | Logistic |

'`"mincost"` | Minimal expected misclassification cost (for classification scores that are posterior probabilities) |

`"quadratic"` | Quadratic |

For more details on the built-in loss functions, see `loss`

.

**Example: **`'Metrics',["classiferror" "mincost"]`

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 argument

`metric`

is an*n*-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 select the function name (

`customMetric`

).`C`

is an*n*-by-*K*logical matrix with rows indicating the class to which the corresponding observation belongs, where*K*is the number of classes. The column order corresponds to the class order in the`ClassNames`

property. Create`C`

by setting`C(`

=,`p`

)`q`

`1`

, if observation

is in class`p`

, for each observation in the specified data. Set the other element in row`q`

to`p`

`0`

.`S`

is an*n*-by-*K*numeric matrix of predicted classification scores.`S`

is similar to the`Score`

output of`predict`

, where rows correspond to observations in the data and the column order corresponds to the class order in the`ClassNames`

property.`S(`

is the classification score of observation,`p`

)`q`

being classified in class`p`

.`q`

`Cost`

is a*K*-by-*K*numeric 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 @customeMetric2 'logit' struct('Metric3',@customMetric3)}`

`updateMetrics`

and `updateMetricsAndFit`

store specified metrics in a table in the property `IncrementalMdl.Metrics`

. The data type of `Metrics`

determines the row names of the table.

`'Metrics'` Value Data Type | Description of `Metrics` Property 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 for `struct('Metric1',@customMetric1)` is `"Metric1"` |

Function handle to function stored in a program file | Name of function | Row name for `@customMetric` is `"customMetric"` |

Anonymous function | `CustomMetric_` , where is metric in `Metrics` | Row name for `@(C,S,Cost)customMetric(C,S,Cost)...` is `CustomMetric_1` |

For more details on performance metrics options, see Performance Metrics.

**Data Types: **`char`

| `string`

| `struct`

| `cell`

| `function_handle`

`MetricsWarmupPeriod`

— Number of observations fit before tracking performance metrics

`1000`

(default) | nonnegative integer

This property is read-only.

Number of observations the incremental model must be fit to before it tracks performance metrics in its `Metrics`

property, specified as a nonnegative integer.

For more details, see Performance Metrics.

**Data Types: **`single`

| `double`

`MetricsWindowSize`

— Number of observations to use to compute window performance metrics

`200`

(default) | positive integer

This property is read-only.

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

For more details on performance metrics options, see Performance Metrics.

**Data Types: **`single`

| `double`

## Output Arguments

`IncrementalMdl`

— Naive Bayes classification for incremental learning

`incrementalClassificationNaiveBayes`

model object

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`

).

To initialize `IncrementalMdl`

for incremental learning, `incrementalLearner`

passes the values of the properties of `Mdl`

in this table to congruent properties of `IncrementalMdl`

.

Property | Description |
---|---|

`CategoricalLevels` | Multivariate multinomial predictor levels, a cell array with length
equal to |

`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, see `DistributionParameters` ) |

`NumPredictors` | Number of predictors, a positive integer. |

`Prior` | Prior class label distribution, a numeric vector |

`ScoreTransform` | Score transformation function, a name or function handle. |

`Y` | Class labels supplied to `fitcnb` to compute per class weights for incremental learning, stored as an array of labels (see `Y` ) |

## More About

### Incremental Learning

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

Predict labels.

Measure the predictive performance.

Check for structural breaks or drift in the model.

Fit the model to the incoming observations.

## Algorithms

### Performance Metrics

The

`updateMetrics`

and`updateMetricsAndFit`

functions track model performance metrics (`'Metrics'`

) from new data when the incremental model is*warm*(`IsWarm`

property). An incremental model is warm when`fit`

or`updateMetricsAndFit`

perform both of the following actions:Fit the incremental model to MetricsWarmupPeriod observations, which is the

*metrics warm-up period*.Process

`MaxNumClasses`

classes or all class names specified by the`ClassNames`

name-value argument.

The

`Metrics`

property of the incremental model stores two forms of each performance metric as variables (columns) of a table,`Cumulative`

and`Window`

, with individual metrics in rows. When the incremental model is warm,`updateMetrics`

and`updateMetricsAndFit`

update the metrics at the following frequencies:`Cumulative`

— The functions compute cumulative metrics since the start of model performance tracking. The functions update metrics every time you call the functions and base the calculation on the entire supplied data set.`Window`

— The functions compute metrics based on all observations within a window determined by the MetricsWindowSize name-value pair argument.`MetricsWindowSize`

also determines the frequency at which the software updates`Window`

metrics. For example, if`MetricsWindowSize`

is 20, the functions compute metrics based on the last 20 observations in the supplied data (`X((end – 20 + 1):end,:)`

and`Y((end – 20 + 1):end)`

).Incremental functions that track performance metrics within a window use the following process:

For each specified metric, store a buffer of length

`MetricsWindowSize`

and a buffer of observation weights.Populate elements of the metrics buffer with the model performance based on batches of incoming observations, and store corresponding observation weights in the weights buffer.

When the buffer is filled, overwrite

`Mdl.Metrics.Window`

with the weighted average performance in the metrics window. If the buffer is overfilled when the function processes a batch of observations, the latest incoming`MetricsWindowSize`

observations enter the buffer, and the earliest observations are removed from the buffer. For example, suppose`MetricsWindowSize`

is 20, the metrics buffer has 10 values from a previously processed batch, and 15 values are incoming. To compose the length 20 window, the functions use the measurements from the 15 incoming observations and the latest 5 measurements from the previous batch.

## See Also

### Objects

### Functions

**Introduced in R2021a**

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