updateMetrics
R2026bUpdate performance metrics in neural network incremental learning model given new data
Since R2026b
Description
Given streaming data, updateMetrics measures the performance of
a configured incremental neural network model for classification (incrementalClassificationNeuralNetwork model object) or regression (incrementalRegressionNeuralNetwork model object). updateMetrics
stores the performance metrics in the output model.
updateMetrics allows for flexible incremental learning. After you call
the function to update model performance metrics on an incoming chunk of data, you can perform
other actions before you train the model to the data. For example, you can decide whether you
need to train the model based on its performance on a chunk of data. Alternatively, you can
both update model performance metrics and train the model on the data as it arrives, in one
call, by using the updateMetricsAndFit
function.
To measure the model performance on a specified batch of data, call loss
instead.
returns an incremental learning model Mdl = updateMetrics(Mdl,X,Y)Mdl, which is the input incremental learning model Mdl modified to contain the model performance metrics on the incoming
predictor and response data, X and Y
respectively.
When the input model is warm (Mdl.IsWarm is
true), updateMetrics overwrites previously computed
metrics, stored in the Metrics property, with the new values. Otherwise,
updateMetrics stores NaN values in
Metrics instead.
Examples
Train a neural network classification model by using fitcnet, convert it to an incremental learner, and then track its performance to streaming data.
Load and Preprocess Data
Load the human activity data set. Randomly shuffle the data.
load humanactivity rng(0,"twister") % 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.
Train Neural Network Classification Model
Fit a neural network classification model to a random sample of half the data.
idxtt = randsample([true false],n,true); TTMdl = fitcnet(X(idxtt,:),Y(idxtt))
TTMdl =
ClassificationNeuralNetwork
ResponseName: 'Y'
CategoricalPredictors: []
ClassNames: [1 2 3 4 5]
ScoreTransform: 'none'
NumObservations: 12039
LayerSizes: 10
Activations: 'relu'
OutputLayerActivation: 'softmax'
Solver: 'LBFGS'
ConvergenceInfo: [1×1 struct]
TrainingHistory: [1000×7 table]
Properties, Methods
TTMdl is a ClassificationNeuralNetwork model object representing a traditionally trained model.
Convert Trained Model
Convert the traditionally trained classification model to a model for incremental learning. Specify to track the classification error metric and use the FreeRex solver, which does not require a solver tuning period.
IncrementalMdl = incrementalLearner(TTMdl,Metrics="classiferror", ... TrainingOptions=incrementalTrainingOptions("freerex"))
IncrementalMdl =
incrementalClassificationNeuralNetwork
IsWarm: 1
Metrics: [2×2 table]
ClassNames: [1 2 3 4 5]
ScoreTransform: 'none'
LayerSizes: 10
Activations: "relu"
OutputLayerActivation: "softmax"
Solver: "freerex"
Properties, Methods
IncrementalMdl is an incrementalClassificationNeuralNetwork model. The model display shows that the model is warm (IsWarm is 1). Therefore, updateMetrics can track model performance metrics given data.
Track Performance Metrics
Track the model performance on the rest of the data by using the updateMetrics function. Simulate a data stream by processing 50 observations at a time. At each iteration:
Call
updateMetricsto update the cumulative and window classification error of the model given the incoming chunk of observations. Overwrite the previous incremental model to update theMetricsproperty. Note that the function does not fit the model to the chunk of data—the chunk is "new" data for the model.Store the classification error and mean bias of the second layer.
% Preallocation idxil = ~idxtt; nil = sum(idxil); numObsPerChunk = 50; nchunk = floor(nil/numObsPerChunk); mc = array2table(zeros(nchunk,2),VariableNames=["Cumulative","Window"]); lb2 = zeros(nchunk,1); Xil = X(idxil,:); Yil = Y(idxil); % Incremental fitting for j = 1:nchunk ibegin = min(nil,numObsPerChunk*(j-1) + 1); iend = min(nil,numObsPerChunk*j); idx = ibegin:iend; IncrementalMdl = updateMetrics(IncrementalMdl,Xil(idx,:),Yil(idx)); mc{j,:} = IncrementalMdl.Metrics{"ClassificationError",:}; lb2(j) = mean(IncrementalMdl.LayerBiases{2}); end
IncrementalMdl is an incrementalClassificationNeuralNetwork model object that has tracked the model performance to observations in the data stream.
To see how the parameters evolve during incremental learning, plot them on separate tiles.
t = tiledlayout(2,1); nexttile plot(mc.Variables) xlim([0 nchunk]) ylabel("Classification Error") legend(mc.Properties.VariableNames) nexttile plot(lb2) ylabel("Mean Layer 2 Bias") xlim([0 nchunk]); xlabel(t,"Iteration")

The cumulative loss is stable after approximately the tenth iteration, whereas the window loss jumps throughout the training. The mean layer 2 bias does not change because updateMetrics does not fit the model to the data.
Train a neural network classification model by using fitcnet, convert it to an incremental learner, track its performance on streaming data, and then fit the model to the data. For incremental learning functions, orient the observations in columns, and specify observation weights.
Load and Preprocess Data
Load the human activity data set. Randomly shuffle the data.
load humanactivity rng(0,"twister"); % 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 the 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 Neural Network Classification Model
Fit a neural network classification model to a random sample of half the data. Specify observation weights.
idxtt = randsample([true false],n,true); TTMdl = fitcnet(X(idxtt,:),Y(idxtt),Weights=W(idxtt))
TTMdl =
ClassificationNeuralNetwork
ResponseName: 'Y'
CategoricalPredictors: []
ClassNames: [1 2 3 4 5]
ScoreTransform: 'none'
NumObservations: 12039
LayerSizes: 10
Activations: 'relu'
OutputLayerActivation: 'softmax'
Solver: 'LBFGS'
ConvergenceInfo: [1×1 struct]
TrainingHistory: [1000×7 table]
Properties, Methods
TTMdl is a ClassificationNeuralNetwork model object representing a traditionally trained neural network classification model.
Convert Trained Model
Convert the traditionally trained model to a model for incremental learning. Specify to use the FreeRex solver, a metrics warm-up period of 1000 observations, and to track the classification error metric.
IncrementalMdl = incrementalLearner(TTMdl, ... TrainingOptions=incrementalTrainingOptions("freerex"), ... MetricsWarmupPeriod=1000,Metrics="classiferror")
IncrementalMdl =
incrementalClassificationNeuralNetwork
IsWarm: 0
Metrics: [2×2 table]
ClassNames: [1 2 3 4 5]
ScoreTransform: 'none'
LayerSizes: 10
Activations: "relu"
OutputLayerActivation: "softmax"
Solver: "freerex"
Properties, Methods
IncrementalMdl is an incrementalClassificationNeuralNetwork model. Because class names are specified in IncrementalMdl.ClassNames, labels encountered during incremental learning must be in IncrementalMdl.ClassNames.
Separately Track Performance Metrics and Fit Model
Perform incremental learning on the rest of the data by using the updateMetrics and fit functions. For incremental learning, orient the observations of the predictor data in columns. At each iteration:
Simulate a data stream by processing 50 observations at a time.
Call
updateMetricsto 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 theMetricsproperty. 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.Store the classification error.
Call
fitto 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.
% 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 = updateMetrics(IncrementalMdl,Xil(:,idx),Yil(idx), ... Weights=Wil(idx),ObservationsIn="columns"); mc{j,:} = IncrementalMdl.Metrics{"ClassificationError",:}; IncrementalMdl = fit(IncrementalMdl,Xil(:,idx),Yil(idx), ... Weights=Wil(idx),ObservationsIn="columns"); end
IncrementalMdl is an incrementalClassificationNeuralNetwork 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.
plot(mc.Variables) xlim([0 nchunk]) xline(IncrementalMdl.MetricsWarmupPeriod/numObsPerChunk,"r-."); legend(mc.Properties.VariableNames) ylabel("Classification Error") xlabel("Iteration")

After the metrics warm-up period (vertical red line), the cumulative loss gradually stabilizes, whereas the window loss jumps throughout the training.
Input Arguments
Incremental learning model whose performance is measured, specified as an incrementalClassificationNeuralNetwork or incrementalRegressionNeuralNetwork model object. You can create
Mdl directly or by converting a supported, traditionally trained
machine learning model using the incrementalLearner function. For
more details, see the corresponding reference page.
If Mdl.IsWarm is false,
updateMetrics does not track the performance of the model. For more
details, see Incremental Training Periods.
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 responses (labels) Y and the
number of observations in X must be equal;
Y( is the response (label) of
observation j (row or column) in j)X.
Note
updateMetricssupports 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 responses (labels), specified as a categorical, character, or string array, a logical or floating-point vector, or a cell array of character vectors for classification problems; or a floating-point vector for regression problems.
The length of the observation responses Y and the number of
observations in X must be equal;
Y( is the response of observation
j (row or column) in j)X.
For classification problems, updateMetrics 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 theClassNamesandMaxNumClassesarguments ofincrementalClassificationNeuralNetwork).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, updateMetrics ignores the
observation. Consequently, updateMetrics 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: updateMetrics(Mdl,X,Y,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.
updateMetrics 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 incremental learning model, returned as an incremental learning model object
of the same data type as the input model Mdl, either incrementalClassificationNeuralNetwork or incrementalRegressionNeuralNetwork.
If the input model is warm, updateMetrics updates the
Metrics property of the output model. Specifically:
Cumulative— The function computes cumulative metrics since the start of model performance tracking. The function updates metrics every time you call it and bases the calculation on the entire supplied data set.Window— The function computes metrics based on all observations within a window determined by theMdl.MetricsWindowSizeproperty.
Tips
Unlike traditional training, incremental learning might not have a separate test (holdout) set. Therefore, to treat each incoming chunk of data as a test set, pass the incremental model and each incoming chunk to
updateMetricsbefore training the model on the same data usingfit.
Algorithms
The
updateMetricsandupdateMetricsAndFitfunctions track model performance metrics from new data only when the incremental model is warm (IsWarmproperty istrue).The
Metricsproperty of the incremental model 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 theMetricsWindowSizename-value argument.MetricsWindowSizealso determines the frequency at which the software updatesWindowmetrics. For example, ifMetricsWindowSizeis 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
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 full, overwrite
Mdl.Metrics.Windowwith the weighted average performance in the metrics window. If the buffer overfills when the function processes a batch of observations, the latest incomingMetricsWindowSizeobservations enter the buffer, and the earliest observations are removed from the buffer. For example, supposeMetricsWindowSizeis 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.
The incremental fitting functions omit an observation
with a NaN score when computing the Cumulative and
Window performance metric values.
For classification problems, if the prior class probability distribution is known (in other words, the prior distribution is not empirical), updateMetrics normalizes observation weights to sum to the prior class probabilities in the respective classes. This action implies that observation weights are the respective prior class probabilities by default.
For regression problems or if the prior class probability distribution is empirical, the software normalizes the specified observation weights to sum to 1 each time you call updateMetrics.
Version History
Introduced in R2026b
See Also
Objects
Functions
fitcnet|fitrnet|fit|updateMetricsAndFit|dlnetwork(Deep Learning Toolbox)
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)