updateMetricsAndFit
Update performance metrics in ECOC incremental learning classification model given new data and train model
Since R2022a
Description
Given streaming data, updateMetricsAndFit first evaluates the
performance of a configured multiclass error-correcting output codes (ECOC) classification
model for incremental learning (incrementalClassificationECOC object) by calling updateMetrics on
incoming data. Then updateMetricsAndFit fits the model to that data by calling
fit. In other
words, updateMetricsAndFit performs prequential evaluation
because it treats each incoming chunk of data as a test set, and tracks performance metrics
measured cumulatively and over a specified window [1].
updateMetricsAndFit provides a simple way to update model performance metrics
and train the model on each chunk of data. Alternatively, you can perform the operations
separately by calling updateMetrics and then fit,
which allows for more flexibility (for example, you can decide whether you need to train the
model based on its performance on a chunk of data).
returns an incremental learning model Mdl = updateMetricsAndFit(Mdl,X,Y)Mdl, which is the input incremental learning model Mdl with the following modifications:
updateMetricsAndFitmeasures the model performance on the incoming predictor and response data,XandYrespectively. When the input model is warm (Mdl.IsWarmistrue),updateMetricsAndFitoverwrites previously computed metrics, stored in theMetricsproperty, with the new values. Otherwise,updateMetricsAndFitstoresNaNvalues inMetricsinstead.updateMetricsAndFitfits the modified model to the incoming data and stores the updated binary learners and configurations in the output modelMdl.
Examples
Prepare an incremental ECOC learner by specifying the maximum number of classes. Track the model performance on streaming data and fit the model to the data in one call by using the updateMetricsAndFit function.
Create an ECOC classification model for incremental learning by calling incrementalClassificationECOC and specifying a maximum of 5 expected classes in the data.
Mdl = incrementalClassificationECOC(MaxNumClasses=5)
Mdl =
incrementalClassificationECOC
IsWarm: 0
Metrics: [1×2 table]
ClassNames: [1×0 double]
ScoreTransform: 'none'
BinaryLearners: {10×1 cell}
CodingName: 'onevsone'
Decoding: 'lossweighted'
Properties, Methods
Mdl is an incrementalClassificationECOC model object. All its properties are read-only.
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.
Implement incremental learning by performing the following actions at each iteration:
Simulate a data stream by processing a chunk of 50 observations.
Overwrite the previous incremental model with a new one fitted to the incoming observations.
Store the first model coefficient of the first binary learner , cumulative metrics, and 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"]); beta11 = zeros(nchunk,1); % Incremental fitting for j = 1:nchunk ibegin = min(n,numObsPerChunk*(j-1) + 1); iend = min(n,numObsPerChunk*j); idx = ibegin:iend; Mdl = updateMetricsAndFit(Mdl,X(idx,:),Y(idx)); mc{j,:} = Mdl.Metrics{"ClassificationError",:}; beta11(j) = Mdl.BinaryLearners{1}.Beta(1); end
Mdl is an incrementalClassificationECOC model object trained on all the data in the stream. During incremental learning and after the model is warmed up, updateMetricsAndFit checks the performance of the model on the incoming observations, and then fits the model to those observations.
To see how the performance metrics and evolve during training, plot them on separate tiles.
t = tiledlayout(2,1); nexttile plot(beta11) ylabel("\beta_{11}") xlim([0 nchunk]) nexttile plot(mc.Variables) xlim([0 nchunk]) ylabel("Classification Error") xline(Mdl.MetricsWarmupPeriod/numObsPerChunk,"--") legend(mc.Properties.VariableNames) xlabel(t,"Iteration")

The plot indicates that updateMetricsAndFit performs the following actions:
Fit during all incremental learning iterations.
Compute the performance metrics after the metrics warm-up period only.
Compute the cumulative metrics during each iteration.
Compute the window metrics after processing 200 observations (4 iterations).
Train an ECOC classification model by using fitcecoc and convert it to an incremental learner by using incrementalLearner. Track the model performance on streaming data and fit the model to streaming data in one call by using updateMetricsAndFit. Specify the orientation of observations and the observation weights when you call updateMetricsAndFit.
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 from a stationary subject (Y <= 2) has double the quality of data from a moving subject. Create a weight variable that assigns a weight of 2 to observations from a stationary subject and 1 to a moving subject.
W = ones(n,1) + (Y <= 2);
Train ECOC Classification Model
Fit an ECOC classification model to a random sample of half the data.
idxtt = randsample([true false],n,true); TTMdl = fitcecoc(X(idxtt,:),Y(idxtt),Weights=W(idxtt))
TTMdl =
ClassificationECOC
ResponseName: 'Y'
CategoricalPredictors: []
ClassNames: [1 2 3 4 5]
ScoreTransform: 'none'
BinaryLearners: {10×1 cell}
CodingName: 'onevsone'
Properties, Methods
TTMdl is a ClassificationECOC model object representing a traditionally trained ECOC classification model.
Convert Trained Model
Convert the traditionally trained model to a model for incremental learning.
IncrementalMdl = incrementalLearner(TTMdl)
IncrementalMdl =
incrementalClassificationECOC
IsWarm: 1
Metrics: [1×2 table]
ClassNames: [1 2 3 4 5]
ScoreTransform: 'none'
BinaryLearners: {10×1 cell}
CodingName: 'onevsone'
Decoding: 'lossweighted'
Properties, Methods
IncrementalMdl is an incrementalClassificationECOC model object. Because class names are specified in IncrementalMdl.ClassNames, labels encountered during incremental learning must be in IncrementalMdl.ClassNames.
Track Performance Metrics and Fit Model
Perform incremental learning on the rest of the data by using the updateMetricsAndFit function. Transpose the predictor matrix, and specify the data orientation when you call updateMetricsAndFit. At each iteration:
Simulate a data stream by processing 50 observations at a time.
Call
updateMetricsAndFitto update the cumulative and window performance metrics of the model given the incoming chunk of observations, and then fit the model to the data. Overwrite the previous incremental model with a new one. Specify that the observations are oriented in columns, and specify the observation weights.Store the misclassification error rate.
% Preallocation idxil = ~idxtt; nil = sum(idxil); numObsPerChunk = 50; nchunk = floor(nil/numObsPerChunk); mc = array2table(zeros(nchunk,2),VariableNames=["Cumulative","Window"]); Xil = X(idxil,:)'; Yil = Y(idxil); Wil = W(idxil); % 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), ... Weights=Wil(idx),ObservationsIn="columns"); mc{j,:} = IncrementalMdl.Metrics{"ClassificationError",:}; end
IncrementalMdl is an incrementalClassificationECOC model object trained on all the data in the stream.
Create a trace plot of the misclassification error rate.
plot(mc.Variables) xlim([0 nchunk]) ylabel("Classification Error") legend(mc.Properties.VariableNames) xlabel("Iteration")

The cumulative loss initially jumps, but stabilizes around 0.03, whereas the window loss jumps throughout the training.
Input Arguments
Incremental learning model whose performance is measured and then the model is fit
to data, specified as an incrementalClassificationECOC model object. You can create
Mdl by calling incrementalClassificationECOC
directly, or by converting a supported, traditionally trained machine learning model
using the incrementalLearner function.
If Mdl.IsWarm is false,
updateMetricsAndFit does not track the performance of the model. For more
details, see Performance Metrics.
Chunk of predictor data, specified as a floating-point matrix of n
observations and Mdl.NumPredictors predictor
variables. The value of the ObservationsIn name-value
argument determines the orientation of the variables and observations. The default
ObservationsIn value is "rows", which indicates that
observations in the predictor data are oriented along the rows of
X.
The length of the observation labels Y and the number of observations in X must be equal; Y( is the label of observation j (row or column) in j)X.
Note
If
Mdl.NumPredictors= 0,updateMetricsAndFitinfers the number of predictors fromX, and sets the corresponding property of the output model. Otherwise, if the number of predictor variables in the streaming data changes fromMdl.NumPredictors,updateMetricsAndFitissues an error.updateMetricsAndFitsupports only floating-point input predictor data. If your input data includes categorical data, you must prepare an encoded version of the categorical data. Usedummyvarto convert each categorical variable to a numeric matrix of dummy variables. Then, concatenate all dummy variable matrices and any other numeric predictors. For more details, see Dummy Variables.
Data Types: single | double
Chunk of labels, specified as a categorical, character, or string array, a logical or floating-point vector, or a cell array of character vectors.
The length of the observation labels Y and the number of
observations in X must be equal;
Y( is the label of observation
j (row or column) in j)X.
updateMetricsAndFit issues an error when one or both of these conditions
are met:
Ycontains a new label and the maximum number of classes has already been reached (see theMaxNumClassesandClassNamesarguments ofincrementalClassificationECOC).The
ClassNamesproperty of the input modelMdlis nonempty, and the data types ofYandMdl.ClassNamesare different.
Data Types: char | string | cell | categorical | logical | single | double
Note
If an observation (predictor or label) or weight contains at
least one missing (NaN) value, updateMetricsAndFit ignores the
observation. Consequently, updateMetricsAndFit uses fewer than n
observations to compute the model performance and create an updated model, where
n is the number of observations in X.
Name-Value Arguments
Specify optional pairs of arguments as
Name1=Value1,...,NameN=ValueN, where Name is
the argument name and Value is the corresponding value.
Name-value arguments must appear after other arguments, but the order of the
pairs does not matter.
Example: ObservationsIn="columns",Weights=W specifies that the columns
of the predictor matrix correspond to observations, and the vector W
contains observation weights to apply during incremental learning.
Predictor data observation dimension, specified as "rows" or
"columns".
Example: ObservationsIn="columns"
Data Types: char | string
Chunk of observation weights, specified as a floating-point vector of positive values.
updateMetricsAndFit weighs the observations in X
with the corresponding values in Weights. The size of
Weights must equal n, which is the number of
observations in X.
By default, Weights is ones(.n,1)
For more details, including normalization schemes, see Observation Weights.
Example: Weights=W specifies the observation weights as the vector
W.
Data Types: double | single
Output Arguments
Updated ECOC classification model for incremental learning, returned as an
incremental learning model object of the same data type as the input model
Mdl, incrementalClassificationECOC.
If the model is not warm, updateMetricsAndFit does not compute
performance metrics. As a result, the Metrics property of
Mdl remains completely composed of NaN values.
If the model is warm, updateMetricsAndFit computes the cumulative and
window performance metrics on the new data X and
Y, and overwrites the corresponding elements of
Mdl.Metrics. For more details, see Performance Metrics.
If you do not specify all expected classes by using the
ClassNames name-value argument when you create the input model
Mdl using incrementalClassificationECOC, and Y contains expected, but
unprocessed, classes, then updateMetricsAndFit performs the following actions:
Append any new labels in
Yto the tail ofMdl.ClassNames.Expand
Mdl.Priorto a length c vector of an updated empirical class distribution, where c is the number of classes inMdl.ClassNames.
Algorithms
updateMetricsandupdateMetricsAndFittrack model performance metrics, specified by the row labels of the table inMdl.Metrics, from new data only when the incremental model is warm (IsWarmproperty istrue).If you create an incremental model by using
incrementalLearnerandMetricsWarmupPeriodis 0 (default forincrementalLearner), the model is warm at creation.Otherwise, an incremental model becomes warm after the
fitorupdateMetricsAndFitfunction performs both of these actions:Fit the incremental model to
Mdl.MetricsWarmupPeriodobservations, which is the metrics warm-up period.Fit the incremental model to all expected classes (see the
MaxNumClassesandClassNamesarguments ofincrementalClassificationECOC).
The
Mdl.Metricsproperty stores two forms of each performance metric as variables (columns) of a table,CumulativeandWindow, with individual metrics in rows. When the incremental model is warm,updateMetricsandupdateMetricsAndFitupdate 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 theMdl.MetricsWindowSizeproperty.Mdl.MetricsWindowSizealso determines the frequency at which the software updatesWindowmetrics. For example, ifMdl.MetricsWindowSizeis 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:
Store a buffer of length
Mdl.MetricsWindowSizefor each specified metric, and store 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.Windowwith the weighted average performance in the metrics window. If the buffer is overfilled when the function processes a batch of observations, the latest incomingMdl.MetricsWindowSizeobservations enter the buffer, and the earliest observations are removed from the buffer. For example, supposeMdl.MetricsWindowSizeis 20, the metrics buffer has 10 values from a previously processed batch, and 15 values are incoming. To compose the length 20 window, the function uses the measurements from the 15 incoming observations and the latest 5 measurements from the previous batch.
The software omits an observation with a
NaNscore when computing theCumulativeandWindowperformance metric values.
If the prior class probability distribution is known (in other words, the prior distribution is not empirical), updateMetricsAndFit normalizes observation weights to sum to the prior class probabilities in the respective classes. This action implies that the default observation weights are the respective prior class probabilities.
If the prior class probability distribution is empirical, the software normalizes the specified observation weights to sum to 1 each time you call updateMetricsAndFit.
References
[1] Bifet, Albert, Ricard Gavaldá, Geoffrey Holmes, and Bernhard Pfahringer. Machine Learning for Data Streams with Practical Example in MOA. Cambridge, MA: The MIT Press, 2007.
Extended Capabilities
Use
saveLearnerForCoder,loadLearnerForCoder, andcodegen(MATLAB Coder) to generate code for theupdateMetricsAndFitfunction. Save a trained model by usingsaveLearnerForCoder. Define an entry-point function that loads the saved model by usingloadLearnerForCoderand calls theupdateMetricsAndFitfunction. Then usecodegento generate code for the entry-point function.To generate single-precision C/C++ code for
updateMetricsAndFit, specifyDataType="single"when you call theloadLearnerForCoderfunction.This table contains notes about the arguments of
updateMetricsAndFit. Arguments not included in this table are fully supported.Argument Notes and Limitations MdlFor usage notes and limitations of the model object, see
incrementalClassificationECOC.XBatch-to-batch, the number of observations can be a variable size, but must equal the number of observations in
Y.The number of predictor variables must equal
Mdl.NumPredictors.Xmust besingleordouble.
YBatch-to-batch, the number of observations can be a variable size, but must equal the number of observations in
X.For classification problems, all labels in
Ymust be included inMdl.ClassNames.YandMdl.ClassNamesmust have the same data type.
The following restrictions apply:
Use a homogeneous data type for all floating-point input arguments and object properties, specifically, either
singleordouble.
For more information, see Introduction to Code Generation.
Version History
Introduced in R2022a
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.
웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- 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)