Naive Bayes classification model for incremental learning
incrementalClassificationNaiveBayes
creates an incrementalClassificationNaiveBayes
model object, which represents a naive Bayes multiclass classification model for incremental learning. incrementalClassificationNaiveBayes
supports normally distributed predictor variables.
Unlike other Statistics and Machine Learning Toolbox™ model objects, incrementalClassificationNaiveBayes
can 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 an incrementalClassificationNaiveBayes
object, it is prepared for incremental learning.
incrementalClassificationNaiveBayes
is 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 crossvalidation, tuning hyperparameters, and so on), see fitcnb
.
You can create an incrementalClassificationNaiveBayes
model object in several ways:
Call the function directly — Configure incremental learning options, or specify learnerspecific options, by calling incrementalClassificationNaiveBayes
directly. 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 naive Bayes model object, you can convert the traditionally trained model to an incrementalClassificationNaiveBayes
model object by passing it to the incrementalLearner
function.
Call an incremental learning function — fit
, updateMetrics
, and updateMetricsAndFit
accept a configured incrementalClassificationNaiveBayes
model object and data as input, and return an incrementalClassificationNaiveBayes
model object updated with information learned from the input model and data.
returns a default naive Bayes classification model object for incremental learning, Mdl
= incrementalClassificationNaiveBayes('MaxNumClasses',MaxNumClasses
)Mdl
, where MaxNumClasses
is 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.
specifies all class names Mdl
= incrementalClassificationNaiveBayes('ClassNames',ClassNames
)ClassNames
expected in the response data during incremental learning, and sets the ClassNames
property.
uses any of the inputargument combinations in the previous syntaxes to set properties and additional options using namevalue pair arguments . Enclose each name in quotes. For example, Mdl
= incrementalClassificationNaiveBayes(___,Name,Value
)incrementalClassificationNaiveBayes('MaxNumClasses',5,'MetricsWarmupPeriod',100)
sets the maximum number of classes expected in the response data to 5
, and sets the metrics warmup period to 100
.
MaxNumClasses
— Maximum number of classesMaximum number of classes expected in the response data during incremental learning, specified as a positive integer.
If you do not specify MaxNumClasses
, you must specify the ClassNames
argument. In that case, MaxNumClasses
is the number of class names in ClassNames
.
Example: 'MaxNumClasses',5
Data Types: single
 double
ClassNames
— All unique class labelsAll unique class labels expected in the response data during incremental learning, specified as a categorical or character array; logical, numeric, or string vector, or cell array of character vectors. ClassNames
and the response data must have the same data type. ClassNames
sets the ClassNames
property.
ClassNames
specifies 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 of Cost
or the column order of classification scores returned by predict
If you do not specify ClassNames
, you must specify the MaxNumClasses
argument. In that case, the software infers the MaxNumClasses
ClassNames
from the data during incremental learning.
Example: 'ClassNames',["virginica" "setosa" "versicolor"}
Data Types: single
 double
 logical
 string
 char
 cell
 categorical
Specify optional
commaseparated 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
.
'NumPredictors',4,'Prior',[0.3 0.3 0.4]
specifies 4
variables in the predictor data and a prior class probability distribution of [0.3 0.3 0.4]
.'Cost'
— Cost of misclassifying an observationCost of misclassifying an observation, specified as a value in this table, where are MaxNumClasses
is the number of classes in the ClassNames
property:
Value  Description 

MaxNumClasses byMaxNumClasses numeric matrix 

Structure array  A structure array having two fields:

If you specify Cost
, you must also specify the ClassNames
argument. Cost
sets the Cost
property.
The default is a MaxNumClasses
byMaxNumClasses
matrix, where Cost(
for all i
,j
) = 1
≠ i
, and j
Cost(
for all i
,j
) = 0
= i
.j
Example: 'Cost',struct('ClassNames',{'b','g'},'ClassificationCosts',[0 2; 1 0])
Data Types: single
 double
 struct
'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, in addition to minimal expected misclassification cost, specified as a builtin 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.
When Mdl
is warm (see IsWarm), updateMetrics
and updateMetricsAndFit
track performance metrics in the Metrics property of Mdl
.
The following table lists the builtin 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). 
"quadratic"  Quadratic 
For more details on the builtin loss functions, see loss
.
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 argument metric
is an nby1 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 nbyK 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 nbyK numeric matrix of predicted classification scores. S
is similar to the Posterior
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 KbyK numeric matrix of misclassification costs. See the 'Cost'
namevalue argument.
To specify multiple custom metrics and assign a custom name to each, use a structure array. To specify a combination of builtin 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 Metrics
property. 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 builtin 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
You can set most properties by using namevalue pair argument syntax only when you call incrementalClassificationNaiveBayes
directly. You can set some properties when you call incrementalLearner
to convert a traditionally trained model. You cannot set the properties DistributionParameters
, IsWarm
, and NumTrainingObservations
.
Cost
— Cost of misclassifying an observationThis property is readonly.
Cost of misclassifying an observation, specified as a MaxNumClasses
byMaxNumClasses
numeric matrix.
If you specify the 'Cost'
namevalue argument, its value sets Cost
. If you specify a structure array, Cost
is the value of the ClassificationCosts
field.
If you convert a traditionally trained model to create Mdl
, Cost
is the Cost
property of the traditionally trained model.
Data Types: single
 double
ClassNames
— All unique class labelsThis property is readonly.
All unique class labels expected in the response data during incremental learning, specified as a categorical or character array, logical or numeric vector, or cell array of character vectors.
If you specify the MaxNumClasses
argument, the software infers ClassNames
during incremental learning.
If you specify the ClassNames
argument, incrementalClassificationNaiveBayes
stores your specification in ClassNames
. If you specify a string vector, incrementalClassificationNaiveBayes
stores it as a cell array of character vectors instead.
If you convert a traditionally trained model to create Mdl
, ClassNames
is the ClassNames
property of the traditionally trained model.
Data Types: single
 double
 logical
 char
 cell
 categorical
NumPredictors
— Number of predictor variables0
(default)  nonnegative numeric scalarThis property is readonly.
Number of predictor variables, specified as a nonnegative numeric scalar.
If you convert a traditionally trained model to create Mdl
, NumPredictors
is specified by the congruent property of the traditionally trained model. Otherwise, incremental fitting functions infer NumPredictors
from the predictor data during training.
Data Types: double
NumTrainingObservations
— Number of observations fit to incremental model0
(default)  nonnegative numeric scalarThis property is readonly.
Number of observations fit to the incremental model Mdl
, specified as a nonnegative numeric scalar. NumTrainingObservations
increases when you pass Mdl
and training data to fit
or updateMetricsAndFit
.
Note
If you convert a traditionally trained model to create Mdl
, incrementalClassificationNaiveBayes
does not add the number of observations fit to the traditionally trained model to NumTrainingObservations
.
Data Types: double
Prior
— Prior class probabilities'empirical'
 'uniform'
This property is readonly.
Prior class probabilities, specified as a value in this table. You can set this property using namevalue pair argument syntax, but incrementalClassificationNaiveBayes
always stores 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, where K is the number of classes. 
numeric vector  Custom, normalized prior probabilities. The order of the elements of Prior corresponds to the elements of the ClassNames property. 
If you convert a traditionally trained model to create Mdl
, incrementalClassificationNaiveBayes
uses the Prior
property of the traditionally trained model.
Otherwise, Prior
is 'empirical'
.
Data Types: single
 double
ScoreTransform
— Score transformation function'none'
(default)  string scalar  character vector  function handleThis property is readonly.
Score transformation function describing how incremental learning functions transform raw response values, specified as a character vector, string scalar, or function handle. incrementalClassificationNaiveBayes
stores the specified value as a character vector or function handle.
This table describes the available builtin 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 + e^{–x}) 
'none' or 'identity'  x (no transformation) 
'sign'  –1 for x < 0 0 for x = 0 1 for x > 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 + e^{–x}) – 1 
For a MATLAB^{®} function or a function that you define, enter its function handle; for example, 'ScoreTransform',@function
, where:
function
accepts an nbyK matrix (the original scores) and returns a matrix of the same size (the transformed scores).
n is the number of observations, and row j of the matrix contains the class scores of observation j.
K is the number of classes, and column k is class ClassNames(
.k
)
If you convert a traditionally trained model to create Mdl
, ScoreTransform
is specified by the congruent property of the traditionally trained model.
The default 'none'
specifies returning posterior class probabilities.
Data Types: char
 function_handle
DistributionNames
— Predictor distributions'normal'
(default)  cell array of character vectorsThis property is readonly.
Predictor distributions, specified as 'normal'
or a 1byNumPredictors
cell array with all cells containing 'normal'
. The conditional distribution P(x_{j}c_{k}) is normal (Gaussian), for j = 1,…,NumPredictors
and each k ∈ ClassNames
.
Data Types: char
 string
 cell
DistributionParameters
— Distribution parameter estimatesThis property is readonly.
Distribution parameter estimates, specified as a cell array. DistributionParameters
is a KbyNumPredictors
cell array, where K is the number of classes and cell (k
,j
) contains the distribution parameter estimates for instances of predictor j
in class k
. The order of the rows corresponds to the order of the classes in the property ClassNames
, and the order of the columns corresponds to the order of the predictors in the predictor data.
If class k
has no observations for predictor j
, then DistributionParameters{
is empty (k
,j
}[]
).
Because all predictor distributions, specified by the DistributionNames
property, are 'normal'
, each cell of DistributionParameters
is a 2by1 numeric vector, where the first element is the sample mean and the second element is the sample standard deviation.
Data Types: cell
IsWarm
— Flag indicating whether model tracks performance metricsfalse
 true
Flag indicating whether the incremental model tracks performance metrics, specified as false
or true
.
The incremental model Mdl
is warm (IsWarm
becomes true
) when incremental fitting functions perform both of the following actions:
Fit the incremental model to MetricsWarmupPeriod
observations.
Process MaxNumClasses
classes or all class names specified by the ClassNames
namevalue argument.
Value  Description 

true  The incremental model Mdl is warm. Consequently, updateMetrics and updateMetricsAndFit track performance metrics in the Metrics property of Mdl . 
false  updateMetrics and updateMetricsAndFit do not track performance metrics. 
Data Types: logical
Metrics
— Model performance metricsThis property is readonly.
Model performance metrics updated during incremental learning by updateMetrics
and updateMetricsAndFit
, specified as a table with two columns and m rows, where m is the number of metrics specified by the 'Metrics'
namevalue pair argument.
The columns of Metrics
are labeled Cumulative
and Window
.
Cumulative
: Element j
is the model performance, as measured by metric j
, from the time the model became warm (IsWarm is 1
).
Window
: Element j
is the model performance, as measured by metric j
, evaluated over all observations within the window specified by the MetricsWindowSize
property. The software updates Window
after it processes MetricsWindowSize
observations.
Rows are labeled by the specified metrics. For details, see 'Metrics'
.
Data Types: table
MetricsWarmupPeriod
— Number of observations fit before tracking performance metrics1000
(default)  nonnegative integerThis property is readonly.
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 metrics200
(default)  positive integerThis property is readonly.
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
fit  Train naive Bayes classification model for incremental learning 
updateMetricsAndFit  Update performance metrics in naive Bayes classification model for incremental learning given new data and train model 
updateMetrics  Update performance metrics in naive Bayes classification model for incremental learning given new data 
logp  Log unconditional probability density of naive Bayes classification model for incremental learning 
loss  Loss of naive Bayes classification model for incremental learning on batch of data 
predict  Predict responses for new observations from naive Bayes classification model for incremental learning 
To create a naive Bayes classification model for incremental learning, the least amount of information you must specify is the maximum number of classes that you expect the model to experience ('MaxNumClasses'
namevalue argument). As you fit the model to incoming batches of data by using an incremental fitting function, the model collects newly experienced classes in its ClassNames
property. If the specified expected maximum number of classes is inaccurate, one of the following alternatives occurs:
Before an incremental fitting function experiences the expected maximum number of classes, the model is cold. Consequently, the updateMetrics
and updateMetricsAndFit
functions 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 you know only the expected maximum number of classes in the data. Also, the example illustrates the consequences when incremental fitting functions experience 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.
Experience Expected Maximum Number of Classes Early in Sample
Create an incremental naive Bayes learner for multiclass learning. Specify a maximum of 5 classes in the data.
MdlEarly = incrementalClassificationNaiveBayes('MaxNumClasses',5)
MdlEarly = incrementalClassificationNaiveBayes IsWarm: 0 Metrics: [1×2 table] ClassNames: [1×0 double] ScoreTransform: 'none' DistributionNames: 'normal' DistributionParameters: {} Properties, Methods
MdlEarly
is an incrementalClassificationNaiveBayes
model object. All its properties are readonly.
MdlEarly
must be fit to data before you can use it to perform any other operations.
Load the human activity data set. Randomly shuffle the data.
load humanactivity n = numel(actid); rng(1); % For reproducibility idx = randsample(n,n); X = feat(idx,:); Y = actid(idx);
For details on the data set, enter Description
at the command line.
Fit the incremental model to the training data by using the updateMetricsAndfit
function. 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 observation.
Store ${\mu}_{11}$ (the mean of the first predictor variable in the first class), the cumulative metrics, and the window metrics to see how they evolve during incremental learning.
% Preallocation numObsPerChunk = 50; nchunk = floor(n/numObsPerChunk); mc = array2table(zeros(nchunk,2),'VariableNames',["Cumulative" "Window"]); mu1 = zeros(nchunk,1); % Incremental learning for j = 1:nchunk ibegin = min(n,numObsPerChunk*(j1) + 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
MdlEarly
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}_{11}$ evolved during training, plot them on separate subplots.
figure; subplot(2,1,1) plot(mu1) ylabel('\mu_{11}') xlim([0 nchunk]); subplot(2,1,2) h = plot(mc.Variables); xlim([0 nchunk]); ylabel('Minimal Cost') xline(MdlEarly.MetricsWarmupPeriod/numObsPerChunk,'r.'); legend(h,mc.Properties.VariableNames) xlabel('Iteration')
The plot suggests that updateMetricsAndFit
does the following:
Fit ${\mu}_{11}$ during all incremental learning iterations
Compute performance metrics after the metrics warmup period only.
Compute the cumulative metrics during each iteration.
Compute the window metrics after processing 500 observations.
Experience 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: [1×2 table] ClassNames: [1×0 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 results, as performed previously.
mcnew = array2table(zeros(nchunk,2),'VariableNames',["Cumulative" "Window"]); mu1new = zeros(nchunk,1); for j = 1:nchunk ibegin = min(n,numObsPerChunk*(j1) + 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); end figure; subplot(2,1,1) plot(mu1new) ylabel('\mu_{11}') xlim([0 nchunk]); subplot(2,1,2) 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('Iteration')
The updateMetricsAndFit
function trains throughout incremental learning, but the function starts tracking performance metrics after the model has been fit to all expected number of classes (the green vertical line in the bottom subplot).
This example shows how to create an incremental naive Bayes learner 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, and you know the class names map 1 through 5 to an activity.
Create an incremental naive Bayes learner 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
Mdl
is an incrementalClassificationNaiveBayes
model object. All its properties are readonly.
Mdl
must be fit to data before you can use it to perform any other operations.
Load the human activity data set. Randomly shuffle the data.
load humanactivity n = numel(actid); rng(1); % For reproducibility idx = randsample(n,n); X = feat(idx,:); Y = actid(idx);
For details on the data set, enter Description
at the command line.
Fit the incremental model to the training data by using the updateMetricsAndfit
function. 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 observation.
% Preallocation numObsPerChunk = 50; nchunk = floor(n/numObsPerChunk); % Incremental learning for j = 1:nchunk ibegin = min(n,numObsPerChunk*(j1) + 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 warmup period, during which the updateMetricsAndFit
function only fits the model. Specify a metrics window size of 500 observations.
Load the human activity data set. Randomly shuffle the data.
load humanactivity
n = numel(actid);
idx = randsample(n,n);
X = feat(idx,:);
Y = actid(idx);
For details on the data set, enter Description
at the command line.
Create an incremental linear model for binary classification. Configure the model as follows:
Specify a metrics warmup period of 5000 observations.
Specify a metrics window size of 500 observations.
Track the classification error and minimal cost to measure the performance of the model.
Mdl = incrementalClassificationNaiveBayes('MaxNumClasses',5,'MetricsWarmupPeriod',5000,... 'MetricsWindowSize',500,'Metrics',["classiferror" "mincost"])
Mdl = incrementalClassificationNaiveBayes IsWarm: 0 Metrics: [2x2 table] ClassNames: [1x0 double] ScoreTransform: 'none' DistributionNames: 'normal' DistributionParameters: {} Properties, Methods
Mdl
is an incrementalClassificationNaiveBayes
model object configured for incremental learning.
Fit the incremental model to the rest of the data by using the updateMetricsAndfit
function. 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 observation.
Store ${\sigma}_{11}$ (the standard deviation of the first predictor variable in the first class), the cumulative metrics, and the window metrics to see how they evolve during incremental learning.
% Preallocation numObsPerChunk = 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 fitting for j = 1:nchunk ibegin = min(n,numObsPerChunk*(j1) + 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
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 ${\sigma}_{11}$ evolved during training, plot them on separate subplots.
figure; subplot(2,2,1) plot(sigma11) ylabel('\sigma_{11}') xlim([0 nchunk]); xline(Mdl.MetricsWarmupPeriod/numObsPerChunk,'r.'); xlabel('Iteration') subplot(2,2,2) h = plot(ce.Variables); xlim([0 nchunk]); ylabel('Classification Error') xline(Mdl.MetricsWarmupPeriod/numObsPerChunk,'r.'); legend(h,ce.Properties.VariableNames) xlabel('Iteration') subplot(2,2,3) h = plot(mc.Variables); xlim([0 nchunk]); ylabel('Minimal Cost') xline(Mdl.MetricsWarmupPeriod/numObsPerChunk,'r.'); legend(h,mc.Properties.VariableNames) xlabel('Iteration')
The plot suggests that updateMetricsAndFit
does the following:
Fit ${\sigma}_{11}$ during all incremental learning iterations
Compute performance metrics after the metrics warmup period 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 using fitcnb
, convert it to an incremental learner, track its performance, and fit it 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.
load humanactivity rng(1); % For reproducibility n = numel(actid); idx = randsample(n,n); X = feat(idx,:); Y = actid(idx);
For details on the data set, enter Description
at 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 < 3);
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
TTMdl
is a ClassificationNaiveBayes
model 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 the updateMetrics
and fit
functions. Simulate a data stream by processing 50 observations at a time. At each iteration:
Call updateMetrics
to 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 the Metrics
property. 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.
Call fit
to fit the model to the incoming chunk of observations. Overwrite the previous incremental model to update the model parameters. Specify the observation weights.
Store the minimal cost and mean of the first predictor variable of the first class ${\mu}_{11}$.
% Preallocation idxil = ~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 fitting for j = 1:nchunk ibegin = min(nil,numObsPerChunk*(j1) + 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
IncrementalMdl
is an incrementalClassificationNaiveBayes
model object trained on all the data in the stream.
Alternatively, you can use updateMetricsAndFit
to update 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 estimated coefficient ${\mu}_{11}$.
figure; subplot(2,1,1) h = plot(mc.Variables); xlim([0 nchunk]); ylabel('Minimal Cost') legend(h,mc.Properties.VariableNames) subplot(2,1,2) plot(mu11) ylabel('\mu_11') xlim([0 nchunk]); xlabel('Iteration')
The cumulative loss is stable and decreases gradually, whereas the window loss jumps.
${\mu}_{11}$ changes abruptly at first, then gradually levels off as fit
processes more chunks.
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 crossvalidation 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.
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 warmup period.
Process MaxNumClasses
classes or all class names specified by the ClassNames
namevalue 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 namevalue 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.
You have a modified version of this example. Do you want to open this example with your edits?
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.
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: .
Select web siteYou can also select a web site from the following list:
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.