incrementalClassificationLinear
Binary classification linear model for incremental learning
Description
incrementalClassificationLinear
creates an incrementalClassificationLinear
model object, which represents a binary classification linear model for incremental learning. Supported learners include support vector machine (SVM) and logistic regression.
Unlike other Statistics and Machine Learning Toolbox™ model objects, incrementalClassificationLinear
can be called directly. Also, you can specify learning options such as performance metrics configurations, parameter values, and the objective solver, before fitting the model to data. After you create an incrementalClassificationLinear
object, it is prepared for incremental learning.
incrementalClassificationLinear
is best suited for incremental learning. For a traditional approach to training an SVM or linear model for binary classification (such as creating a model by fitting it to data, performing crossvalidation, tuning hyperparameters, and so on), see fitcsvm
or fitclinear
. For multiclass incremental learning using the naive Bayes algorithm, see incrementalClassificationNaiveBayes
.
Creation
You can create an incrementalClassificationLinear
model object in several ways:
Call the function directly — Configure incremental learning options, or specify initial values for linear model parameters and hyperparameters, by calling
incrementalClassificationLinear
directly. This approach is best when you do not have data yet or you want to start incremental learning immediately.Convert a traditionally trained model — To initialize a binary classification linear model for incremental learning using the model coefficients and hyperparameters of a trained SVM or binary classification linear model object, you can convert the traditionally trained model to an
incrementalClassificationLinear
model object by passing it to theincrementalLearner
function. This table contains links to the appropriate reference pages.Convertible Model Object Conversion Function ClassificationSVM
orCompactClassificationSVM
incrementalLearner
ClassificationLinear
incrementalLearner
Call an incremental learning function —
fit
,updateMetrics
, andupdateMetricsAndFit
accept a configuredincrementalClassificationLinear
model object and data as input, and return anincrementalClassificationLinear
model object updated with information learned from the input model and data.
Description
returns a default binary classification linear model object for incremental learning, Mdl
= incrementalClassificationLinear()Mdl
. 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.
sets properties and additional options using namevalue pair arguments. Enclose each name in quotes. For example, Mdl
= incrementalClassificationLinear(Name
,Value
)incrementalClassificationLinear('Beta',[0.1 0.3],'Bias',1,'MetricsWarmupPeriod',100)
sets the vector of linear model coefficients β to [0.1 0.3]
, the bias β_{0} to 1
, and the metrics warmup period to 100
.
Input Arguments
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
.
'Standardize',true
standardizes the predictor data using the predictor means and standard deviations estimated during the estimation period.Metrics
— Model performance metrics to track during incremental learning
"classiferror"
(default)  string vector  function handle  cell vector  structure array  "binodeviance"
 "exponential"
 "hinge"
 "logit"
 "quadratic"
 ...
Model performance metrics to track during incremental learning, 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"  Classification error 
"exponential"  Exponential 
"hinge"  Hinge 
"logit"  Logistic 
"quadratic"  Quadratic 
For more details on the builtin loss functions, see loss
.
Example: 'Metrics',["classiferror" "hinge"]
To specify a custom function that returns a performance metric, use function handle notation. The function must have this form:
metric = customMetric(C,S)
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 nby2 logical matrix with rows indicating the class to which the corresponding observation belongs. The column order corresponds to the class order in theClassNames
property. CreateC
by settingC(
=p
,q
)1
, if observation
is in classp
, for each observation in the specified data. Set the other element in rowq
top
0
.S
is an nby2 numeric matrix of predicted classification scores.S
is similar to theScore
output ofpredict
, where rows correspond to observations in the data and the column order corresponds to the class order in theClassNames
property.S(
is the classification score of observationp
,q
)
being classified in classp
.q
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)customMetric(C,S)... is CustomMetric_1 
For more details on performance metrics options, see Performance Metrics.
Data Types: char
 string
 struct
 cell
 function_handle
Standardize
— Flag to standardize predictor data
'auto'
(default)  false
 true
Flag to standardize the predictor data, specified as the commaseparated pair consisting of 'Standardize'
and a value in this table.
Value  Description 

'auto'  incrementalClassificationLinear determines whether the predictor variables need to be standardized. See Standardize Data. 
true  The software standardizes the predictor data. For more details, see Standardize Data. 
false  The software does not standardize the predictor data. 
Example: 'Standardize',true
Data Types: logical
 char
 string
Properties
You can set most properties by using namevalue pair argument syntax only when you call incrementalClassificationLinear
directly. You can set some properties when you call incrementalLearner
to convert a traditionally trained model. You cannot set the properties FittedLoss
, NumTrainingObservations
, Mu
, Sigma
, SolverOptions
, and IsWarm
.
Classification Model Parameters
Beta
— Linear model coefficients β
numeric vector
This property is readonly.
Linear model coefficients β, specified as a NumPredictors
by1 numeric vector.
If you convert a traditionally trained model to create Mdl
, Beta
is specified by the value of the Beta
property of the traditionally trained model. Otherwise, by default, Beta
is zeros(NumPredictors,1)
.
Data Types: single
 double
Bias
— Model intercept β_{0}
numeric scalar
This property is readonly.
Model intercept β_{0}, or bias term, specified as a numeric scalar.
If you convert a traditionally trained model to create Mdl
, Bias
is specified by the value of the Bias
property of the traditionally trained model. Otherwise, by default, Bias
is 0
.
Data Types: single
 double
ClassNames
— Unique class labels
categorical array  character array  logical vector  numeric vector  cell array of character vectors
This property is readonly.
Unique class labels used in training the model, specified as a categorical or character array, logical or numeric vector, or cell array of character vectors. incrementalClassificationLinear
stores a specified string vector as a cell array of character vectors. ClassNames
and the response data must have the same data type.
If you convert a traditionally trained model to create
Mdl
,ClassNames
is theClassNames
property of the traditionally trained model.Otherwise, incremental fitting functions infer
ClassNames
during training.
Data Types: single
 double
 logical
 char
 cell
 categorical
FittedLoss
— Loss function used to fit linear model
'hinge'
 'logit'
This property is readonly.
Loss function used to fit the linear model, specified as 'hinge'
or 'logit'
.
Value  Algorithm  Loss Function  Learner Value 

'hinge'  Support vector machine  Hinge: $$\ell \left[y,f\left(x\right)\right]=\mathrm{max}\left[0,1yf\left(x\right)\right]$$  'svm' 
'logit'  Logistic regression  Deviance (logistic): $$\ell \left[y,f\left(x\right)\right]=\mathrm{log}\left\{1+\mathrm{exp}\left[yf\left(x\right)\right]\right\}$$  'logistic' 
Learner
— Linear classification model type
'logistic'
 'svm'
This property is readonly.
Linear classification model type, specified as 'logistic'
or 'svm'
.
In the following table, $$f\left(x\right)=x\beta +b.$$
β is a vector of p coefficients.
x is an observation from p predictor variables.
b is the scalar bias.
Value  Algorithm  Loss Function  FittedLoss Value 

'logistic'  Logistic regression  Deviance (logistic): $$\ell \left[y,f\left(x\right)\right]=\mathrm{log}\left\{1+\mathrm{exp}\left[yf\left(x\right)\right]\right\}$$  'logit' 
'svm'  Support vector machine  Hinge: $$\ell \left[y,f\left(x\right)\right]=\mathrm{max}\left[0,1yf\left(x\right)\right]$$  'hinge' 
If you convert a traditionally trained model to create Mdl
, Learner
is the learner of the traditionally trained model.
If the traditionally trained model is
ClassificationSVM
orCompactClassificationSVM
,Learner
is'svm'
.If the traditionally trained model is
ClassificationLinear
,Learner
is the value of theLearner
property of the traditionally trained model.
NumPredictors
— Number of predictor variables
0
(default)  nonnegative numeric scalar
This 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 model
0
(default)  nonnegative numeric scalar
This 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
, incrementalClassificationLinear
does not add the number of observations fit to the traditionally trained model to NumTrainingObservations
.
Data Types: double
Prior
— Prior class probabilities
numeric vector  '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 incrementalClassificationLinear
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 (after the estimation period EstimationPeriod ). 
'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
,incrementalClassificationLinear
uses thePrior
property of the traditionally trained model.Otherwise,
Prior
is'empirical'
.
Data Types: single
 double
ScoreTransform
— Score transformation function
character vector  string scalar  function handle
This 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. incrementalClassificationLinear
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
numel(ClassNames)
, and column k is classClassNames(
.k
)
By default:
If you convert a traditionally trained model to create
Mdl
,ScoreTransform
is specified by the congruent property of the traditionally trained model. For example, if theScoreTransform
property of the traditionally trained model is a scoretoposteriorprobability transformation function, as computed byfitPosterior
orfitSVMPosterior
,Mdl.ScoreTransform
contains an anonymous function.ScoreTransform
is'none'
whenLearner
is'svm'
.ScoreTransform
is'logit'
whenLearner
is'logistic'
.
Data Types: char
 function_handle
Training Parameters
EstimationPeriod
— Number of observations processed to estimate hyperparameters
nonnegative integer
This property is readonly.
Number of observations processed by the incremental model to estimate hyperparameters before training or tracking performance metrics, specified as a nonnegative integer.
Note
If
Mdl
is prepared for incremental learning (all hyperparameters required for training are specified),incrementalClassificationLinear
forces'EstimationPeriod'
to0
.If
Mdl
is not prepared for incremental learning,incrementalClassificationLinear
sets'EstimationPeriod'
to1000
.
For more details, see Estimation Period.
Data Types: single
 double
FitBias
— Linear model intercept inclusion flag
true
 false
This property is readonly.
Linear model intercept inclusion flag, specified as true
or false
.
Value  Description 

true  incrementalClassificationLinear includes the bias term β_{0} in the linear model, which incremental fitting functions fit to data. 
false  incrementalClassificationLinear sets β_{0} = 0. 
If Bias
≠ 0, FitBias
must be true
. In other words, incrementalClassificationLinear
does not support an equality constraint on β_{0}.
If you convert a traditionally trained linear classification model (ClassificationLinear
) to create Mdl
, FitBias
is specified by the value of the ModelParameters.FitBias
property of the traditionally trained model.
Data Types: logical
Mu
— Predictor means
vector of numeric values  []
This property is readonly.
Predictor means, specified as a numeric vector.
If Mu
is an empty array []
and you specify 'Standardize',true
, incremental fitting functions set Mu
to the predictor variable means estimated during the estimation period specified by EstimationPeriod
.
You cannot specify Mu
directly.
Data Types: single
 double
Sigma
— Predictor standard deviations
vector of numeric values  []
This property is readonly.
Predictor standard deviations, specified as a numeric vector.
If Sigma
is an empty array []
and you specify 'Standardize',true
, incremental fitting functions set Sigma
to the predictor variable standard deviations estimated during the estimation period specified by EstimationPeriod
.
You cannot specify Sigma
directly.
Data Types: single
 double
Solver
— Objective function minimization technique
'scaleinvariant'
(default)  'sgd'
 'asgd'
This property is readonly.
Objective function minimization technique, specified as a value in this table.
Value  Description  Notes 

'scaleinvariant'  Adaptive scaleinvariant solver for incremental learning [1] 

'sgd'  Stochastic gradient descent (SGD) [3][2] 

'asgd'  Average stochastic gradient descent (ASGD) [4] 

If you convert a traditionally trained linear model for binary classification (ClassificationLinear
) to create Mdl
, whose ModelParameters.Solver
property is 'sgd'
or 'asgd'
, Solver
is specified by the ModelParameters.Solver
property of the traditionally trained model.
Data Types: char
 string
SolverOptions
— Objective solver configurations
structure array
This property is readonly.
Objective solver configurations, specified as a structure array. The fields of SolverOptions
are properties specific to the specified solver Solver
.
Data Types: struct
SGD and ASGD Solver Parameters
BatchSize
— Minibatch size
positive integer
This property is readonly.
Minibatch size, specified as a positive integer. At each iteration during training, incrementalClassificationLinear
uses min(BatchSize,numObs)
observations to compute the subgradient, where numObs
is the number of observations in the training data passed to fit
or updateMetricsAndFit
.
If you convert a traditionally trained linear model for binary classification (ClassificationLinear
) to create Mdl
, whose ModelParameters.Solver
property is 'sgd'
or 'asgd'
, BatchSize
is specified by the ModelParameters.BatchSize
property of the traditionally trained model. Otherwise, the default is 10
.
Data Types: single
 double
Lambda
— Ridge (L2) regularization term strength
nonnegative scalar
This property is readonly.
Ridge (L2) regularization term strength, specified as a nonnegative scalar.
If you convert a traditionally trained linear model for binary classification with a ridge penalty (ClassificationLinear
object with property Regularization
equal to 'ridge (L2)'
) to create Mdl
, Lambda
is specified by the value of the Lambda
property of the traditionally trained model. Otherwise, the default is 1e5
.
Data Types: double
 single
LearnRate
— Learning rate
'auto'
 positive scalar
This property is readonly.
Learning rate, specified as 'auto'
or a positive scalar. LearnRate
controls the optimization step size by scaling the objective subgradient.
When you specify 'auto'
:
If
EstimationPeriod
is0
, the initial learning rate is0.7
.If
EstimationPeriod
>0
, the initial learning rate is1/sqrt(1+max(sum(X.^2,obsDim)))
, whereobsDim
is1
if the observations compose the columns of the predictor data, and2
otherwise.fit
andupdateMetricsAndFit
set the value when you pass the model and training data to either.
If you convert a traditionally trained linear model for binary classification (ClassificationLinear
) to create Mdl
, whose ModelParameters.Solver
property is 'sgd'
or 'asgd'
, LearnRate
is specified by the ModelParameters.LearnRate
property of the traditionally trained model.
The LearnRateSchedule
property determines the learning rate for subsequent learning cycles.
Data Types: single
 double
 char
 string
LearnRateSchedule
— Learning rate schedule
'decaying'
(default)  'constant'
This property is readonly.
Learning rate schedule, specified as a value in this table, where LearnRate
specifies the initial learning rate ɣ_{0}.
Value  Description 

'constant'  The learning rate is ɣ_{0} for all learning cycles. 
'decaying'  The learning rate at learning cycle t is $${\gamma}_{t}=\frac{{\gamma}_{0}}{{\left(1+\lambda {\gamma}_{0}t\right)}^{c}}.$$

If you convert a traditionally trained linear model for binary classification (ClassificationLinear
) to create Mdl
, whose ModelParameters.Solver
property is 'sgd'
or 'asgd'
, LearnRate
is 'decaying'
.
Data Types: char
 string
Adaptive ScaleInvariant Solver Options
Shuffle
— Flag for shuffling observations in batch
true
(default)  false
This property is readonly.
Flag for shuffling the observations in the batch at each learning cycle, specified as a value in this table.
Value  Description 

true  The software shuffles observations in each incoming batch of data before processing the set. This action reduces bias induced by the sampling scheme. 
false  The software processes the data in the order received. 
Data Types: logical
Performance Metrics Parameters
IsWarm
— Flag indicating whether model tracks performance metrics
false
 true
This property is readonly.
Flag indicating whether the incremental model tracks performance metrics, specified as false
or true
. The incremental model Mdl
is warm (IsWarm
becomes true
) after incremental fitting functions fit MetricsWarmupPeriod
observations to the incremental model (that is, EstimationPeriod
+ MetricsWarmupPeriod
observations).
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 metrics
table
This 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
: Elementj
is the model performance, as measured by metricj
, from the time the model became warm (IsWarm is1
).Window
: Elementj
is the model performance, as measured by metricj
, evaluated over all observations within the window specified by theMetricsWindowSize
property. The software updatesWindow
after it processesMetricsWindowSize
observations.
Rows are labeled by the specified metrics. For details, see 'Metrics'
.
Data Types: table
MetricsWarmupPeriod
— Number of observations fit before tracking performance metrics
1000
(default)  nonnegative integer
This 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 metrics
200
(default)  positive integer
This 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
Object Functions
fit  Train linear model for incremental learning 
updateMetricsAndFit  Update performance metrics in linear model for incremental learning given new data and train model 
updateMetrics  Update performance metrics in linear model for incremental learning given new data 
loss  Loss of linear model for incremental learning on batch of data 
predict  Predict responses for new observations from linear model for incremental learning 
Examples
Create Incremental Learner Without Any Prior Information
Create a default incremental linear SVM model for binary classification.
Mdl = incrementalClassificationLinear()
Mdl = incrementalClassificationLinear IsWarm: 0 Metrics: [1x2 table] ClassNames: [1x0 double] ScoreTransform: 'none' Beta: [0x1 double] Bias: 0 Learner: 'svm' Properties, Methods
Mdl
is an incrementalClassificationLinear
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.
Responses can be one of five classes: Sitting, Standing, Walking, Running, or Dancing. Dichotomize the response by identifying whether the subject is moving (actid
> 2).
Y = Y > 2;
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 ${\beta}_{1}$, 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"]); beta1 = zeros(nchunk,1); % 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)); ce{j,:} = Mdl.Metrics{"ClassificationError",:}; beta1(j + 1) = Mdl.Beta(1); end
IncrementalMdl
is an incrementalClassificationLinear
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 ${\beta}_{1}$ evolved during training, plot them on separate subplots.
figure; subplot(2,1,1) plot(beta1) ylabel('\beta_1') xlim([0 nchunk]); xline(Mdl.EstimationPeriod/numObsPerChunk,'r.'); subplot(2,1,2) h = plot(ce.Variables); xlim([0 nchunk]); ylabel('Classification Error') xline(Mdl.EstimationPeriod/numObsPerChunk,'r.'); xline((Mdl.EstimationPeriod + Mdl.MetricsWarmupPeriod)/numObsPerChunk,'g.'); legend(h,ce.Properties.VariableNames) xlabel('Iteration')
The plot suggests that updateMetricsAndFit
does the following:
Fit ${\beta}_{1}$ 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.
Configure Incremental Learning Options
Prepare an incremental binary SVM learner by specifying a metrics warmup period, during which the updateMetricsAndFit
function only fits the model. Specify a metrics window size of 500 observations. Train the model by using SGD, and adjust the SGD batch size, learning rate, and regularization parameter.
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.
Responses can be one of five classes: Sitting, Standing, Waling, Running, or Dancing. Dichotomize the response by identifying whether the subject is moving (actid
> 2).
Y = Y > 2;
Create an incremental linear model for binary classification. Configure the model as follows:
Specify that the incremental fitting functions process the raw (unstandardized) predictor data.
Specify the SGD solver.
Assume that a ridge regularization parameter value of 0.001, SGD batch size of 20, and learning rate of 0.002 work well for the problem.
Specify a metrics warmup period of 5000 observations.
Specify a metrics window size of 500 observations.
Track the classification and hinge error metrics to measure the performance of the model.
Mdl = incrementalClassificationLinear('Standardize',false,... 'Solver','sgd','Lambda',0.001,'BatchSize',20,'LearnRate',0.002,... 'MetricsWarmupPeriod',5000,'MetricsWindowSize',500,... 'Metrics',{'classiferror' 'hinge'})
Mdl = incrementalClassificationLinear IsWarm: 0 Metrics: [2x2 table] ClassNames: [1x0 double] ScoreTransform: 'none' Beta: [0x1 double] Bias: 0 Learner: 'svm' Properties, Methods
Mdl
is an incrementalClassificationLinear
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. Note that chunk size is different from SGD batch size.
Overwrite the previous incremental model with a new one fitted to the incoming observation.
Store the estimated coefficient ${\beta}_{10}$, 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"]); hinge = array2table(zeros(nchunk,2),'VariableNames',["Cumulative" "Window"]); beta10 = 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",:}; hinge{j,:} = Mdl.Metrics{"HingeLoss",:}; beta10(j + 1) = Mdl.Beta(10); end
IncrementalMdl
is an incrementalClassificationLinear
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 ${\beta}_{10}$ evolved during training, plot them on separate subplots.
figure; subplot(2,2,1) plot(beta10) ylabel('\beta_{10}') 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(hinge.Variables); xlim([0 nchunk]); ylabel('Hinge Loss') xline(Mdl.MetricsWarmupPeriod/numObsPerChunk,'r.'); legend(h,hinge.Properties.VariableNames) xlabel('Iteration')
The plot suggests that updateMetricsAndFit
does the following:
Fit ${\beta}_{10}$ 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).
Convert Traditionally Trained Model to Incremental Learner
Train a linear model for binary classification by using fitclinear
, 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. Orient the observations of the predictor data in columns.
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.
Responses can be one of five classes: Sitting, Standing, Walking, Running, or Dancing. Dichotomize the response by identifying whether the subject is moving (actid
> 2).
Y = Y > 2;
Suppose that the data collected when the subject was idle (Y
= false
) 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;
Train Linear Model for Binary Classification
Fit a linear model for binary classification to a random sample of half the data.
idxtt = randsample([true false],n,true); TTMdl = fitclinear(X(:,idxtt),Y(idxtt),'ObservationsIn','columns',... 'Weights',W(idxtt))
TTMdl = ClassificationLinear ResponseName: 'Y' ClassNames: [0 1] ScoreTransform: 'none' Beta: [60x1 double] Bias: 0.1107 Lambda: 8.2967e05 Learner: 'svm' Properties, Methods
TTMdl
is a ClassificationLinear
model object representing a traditionally trained linear model for binary classification.
Convert Trained Model
Convert the traditionally trained classification model to a binary classification linear model for incremental learning.
IncrementalMdl = incrementalLearner(TTMdl)
IncrementalMdl = incrementalClassificationLinear IsWarm: 1 Metrics: [1x2 table] ClassNames: [0 1] ScoreTransform: 'none' Beta: [60x1 double] Bias: 0.1107 Learner: 'svm' 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 theMetrics
property. Note that the function does not fit the model to the chunk of data—the chunk is "new" data for the model. Specify that the observations are oriented in columns, and 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 that the observations are oriented in columns, and specify the observation weights.Store the classification error and first estimated coefficient ${\beta}_{1}$.
% Preallocation idxil = ~idxtt; nil = sum(idxil); numObsPerChunk = 50; nchunk = floor(nil/numObsPerChunk); ce = array2table(zeros(nchunk,2),'VariableNames',["Cumulative" "Window"]); beta1 = [IncrementalMdl.Beta(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),... 'ObservationsIn','columns','Weights',Wil(idx)); ce{j,:} = IncrementalMdl.Metrics{"ClassificationError",:}; IncrementalMdl = fit(IncrementalMdl,Xil(:,idx),Yil(idx),'ObservationsIn','columns',... 'Weights',Wil(idx)); beta1(j + 1) = IncrementalMdl.Beta(end); end
IncrementalMdl
is an incrementalClassificationLinear
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 ${\beta}_{1}$.
figure; subplot(2,1,1) h = plot(ce.Variables); xlim([0 nchunk]); ylabel('Classification Error') legend(h,ce.Properties.VariableNames) subplot(2,1,2) plot(beta1) ylabel('\beta_1') xlim([0 nchunk]); xlabel('Iteration')
The cumulative loss is stable and decreases gradually, whereas the window loss jumps.
${\beta}_{1}$ changes abruptly at first, then gradually levels off as fit
processes more chunks.
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 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.
Adaptive ScaleInvariant Solver for Incremental Learning
The adaptive scaleinvariant solver for incremental learning, introduced in [1], is a gradientdescentbased objective solver for training linear predictive models. The solver is hyperparameter free, insensitive to differences in predictor variable scales, and does not require prior knowledge of the distribution of the predictor variables. These characteristics make it well suited to incremental learning.
The standard SGD and ASGD solvers are sensitive to differing scales among the predictor variables, resulting in models that can perform poorly. To achieve better accuracy using SGD and ASGD, you can standardize the predictor data, and tune the regularization and learning rate parameters can require tuning. For traditional machine learning, enough data is available to enable hyperparameter tuning by crossvalidation and predictor standardization. However, for incremental learning, enough data might not be available (for example, observations might be available only one at a time) and the distribution of the predictors might be unknown. These characteristics make parameter tuning and predictor standardization difficult or impossible to do during incremental learning.
The incremental fitting functions for classification fit
and updateMetricsAndFit
use the more aggressive ScInOL2 version of the algorithm.
Tips
After creating a model, you can generate C/C++ code that performs incremental learning on a data stream. Generating C/C++ code requires MATLAB Coder™. For details, see Introduction to Code Generation.
Algorithms
Estimation Period
During the estimation period, incremental fitting functions fit
and updateMetricsAndFit
use the first incoming EstimationPeriod
observations to estimate (tune) hyperparameters required for incremental training. This table describes the hyperparameters and when they are estimated or tuned. Estimation occurs only when EstimationPeriod
is positive.
Hyperparameter  Model Property  Use  Hyperparameters Estimated 

Predictor means and standard deviations 
 Standardize predictor data  When both these conditions apply:

Learning rate  LearnRate  Adjust solver step size  When both these conditions apply:

The functions fit only the last estimation period observation to the incremental model, and they do not use any of the observations to track the performance of the model. At the end of the estimation period, the functions update the properties that store the hyperparameters.
Standardize Data
If incremental learning functions are configured to standardize predictor variables, they do so using the means and standard deviations stored in the Mu
and Sigma
properties of the incremental learning model Mdl
.
When you set
'Standardize',true
and a positive estimation period (see EstimationPeriod), andMdl.Mu
andMdl.Sigma
are empty, incremental fitting functions estimate means and standard deviations using the estimation period observations.When you set
'Standardize','auto'
(the default), the following conditions apply:If you create
incrementalClassificationLinear
by converting a traditionally trained binary linear SVM model (ClassificationSVM
orCompactClassificationSVM
), and theMu
andSigma
properties of the traditionally trained model are empty arrays[]
, incremental learning functions do not standardize predictor variables. If theMu
andSigma
properties of the traditionally trained model are nonempty, incremental learning functions standardize the predictor variables using the specified means and standard deviations. Incremental fitting functions do not estimate new means and standard deviations, regardless of the length of the estimation period.If you create
incrementalClassificationLinear
by converting a linear classification model (ClassificationLinear
), incremental learning functions do not standardize the data, regardless of the length of the estimation period.If you do not convert a traditionally trained model, incremental learning functions standardize the predictor data only when you specify an SGD solver (see
Solver
) and a positive estimation period (see EstimationPeriod).
When incremental fitting functions estimate predictor means and standard deviations, the functions compute weighted means and weighted standard deviations using the estimation period observations. Specifically, the functions standardize predictor j (x_{j}) using
$${x}_{j}^{\ast}=\frac{{x}_{j}{\mu}_{j}^{\ast}}{{\sigma}_{j}^{\ast}}.$$
x_{j} is predictor j, and x_{jk} is observation k of predictor j in the estimation period.
$${\mu}_{j}^{\ast}=\frac{1}{{\displaystyle \sum _{k}{w}_{k}^{\ast}}}{\displaystyle \sum _{k}{w}_{k}^{\ast}{x}_{jk}}.$$
$${\left({\sigma}_{j}^{\ast}\right)}^{2}=\frac{1}{{\displaystyle \sum _{k}{w}_{k}^{\ast}}}{\displaystyle \sum _{k}{w}_{k}^{\ast}{\left({x}_{jk}{\mu}_{j}^{\ast}\right)}^{2}}.$$
$${w}_{j}^{\ast}=\frac{{w}_{j}}{{\displaystyle \sum _{\forall j\in \text{Class}k}{w}_{j}}}{p}_{k},$$
p_{k} is the prior probability of class k (
Prior
property of the incremental model).w_{j} is observation weight j.
Performance Metrics
The
updateMetrics
andupdateMetricsAndFit
functions track model performance metrics ('Metrics'
) from new data when the incremental model is warm (IsWarm property). An incremental model is warm afterfit
orupdateMetricsAndFit
fit the incremental model to MetricsWarmupPeriod observations, which is the metrics warmup period.If EstimationPeriod > 0, the functions estimate hyperparameters before fitting the model to data. Therefore, the functions must process an additional
EstimationPeriod
observations before the model starts the metrics warmup period.The
Metrics
property of the incremental model stores two forms of each performance metric as variables (columns) of a table,Cumulative
andWindow
, with individual metrics in rows. When the incremental model is warm,updateMetrics
andupdateMetricsAndFit
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 updatesWindow
metrics. For example, ifMetricsWindowSize
is 20, the functions compute metrics based on the last 20 observations in the supplied data (X((end – 20 + 1):end,:)
andY((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 observations 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 incomingMetricsWindowSize
observations enter the buffer, and the earliest observations are removed from the buffer. For example, supposeMetricsWindowSize
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.
References
[1] Kempka, Michał, Wojciech Kotłowski, and Manfred K. Warmuth. "Adaptive ScaleInvariant Online Algorithms for Learning Linear Models." CoRR (February 2019). https://arxiv.org/abs/1902.07528.
[2] Langford, J., L. Li, and T. Zhang. “Sparse Online Learning Via Truncated Gradient.” J. Mach. Learn. Res., Vol. 10, 2009, pp. 777–801.
[3] ShalevShwartz, S., Y. Singer, and N. Srebro. “Pegasos: Primal Estimated SubGradient Solver for SVM.” Proceedings of the 24th International Conference on Machine Learning, ICML ’07, 2007, pp. 807–814.
[4] Xu, Wei. “Towards Optimal One Pass Large Scale Learning with Averaged Stochastic Gradient Descent.” CoRR, abs/1107.2490, 2011.
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
All object functions of an
incrementalClassificationLinear
model object support code generation.If you configure
Mdl
to shuffle data (see Solver and Shuffle), thefit
function randomly shuffles each incoming batch of observations before it fits the model to the batch. The order of the shuffled observations might not match the order generated by MATLAB.When you generate code that loads or creates an
incrementalClassificationLinear
model object, the following restrictions apply.Mdl
cannot represent a converted SVM model configured to return posterior probabilities as scores.The
ClassNames
property must contain all expected class names.The
NumPredictors
property must reflect the number of predictor variables.
For more information, see Introduction to Code Generation.
See Also
Functions
Objects
Topics
 Incremental Learning Overview
 Configure Incremental Learning Model
 Implement Incremental Learning for Classification Using Succinct Workflow
 Implement Incremental Learning for Classification Using Flexible Workflow
 Initialize Incremental Learning Model from Logistic Regression Model Trained in Classification Learner
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)