主要内容

updateMetrics

R2026b

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

Mdl = updateMetrics(Mdl,X,Y) returns an incremental learning model 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.

example

Mdl = updateMetrics(Mdl,X,Y,Name=Value) uses additional options specified by one or more name-value arguments. For example, you can specify that the columns of the predictor data matrix correspond to observations, and set observation weights.

example

Examples

collapse all

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:

  1. 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 Metrics property. Note that the function does not fit the model to the chunk of data—the chunk is "new" data for the model.

  2. 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")

Figure contains 2 axes objects. Axes object 1 with ylabel Classification Error contains 2 objects of type line. These objects represent Cumulative, Window. Axes object 2 with ylabel Mean Layer 2 Bias contains an object of type line.

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:

  1. Simulate a data stream by processing 50 observations at a time.

  2. 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 that the observations are oriented in columns, and specify the observation weights.

  3. Store the classification error.

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

% 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")

Figure contains an axes object. The axes object with xlabel Iteration, ylabel Classification Error contains 3 objects of type line, constantline. These objects represent Cumulative, Window.

After the metrics warm-up period (vertical red line), the cumulative loss gradually stabilizes, whereas the window loss jumps throughout the training.

Input Arguments

collapse all

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(j) is the response (label) of observation j (row or column) in X.

Note

  • updateMetrics supports only floating-point input predictor data. If your input data includes categorical data, you must prepare an encoded version of the categorical data. Use dummyvar to 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(j) is the response of observation j (row or column) in X.

For classification problems, updateMetrics issues an error when one or both of these conditions are met:

  • Y contains a new label and the maximum number of classes has already been reached (see the ClassNames and MaxNumClasses arguments of incrementalClassificationNeuralNetwork).

  • The ClassNames property of the input model Mdl is nonempty, and the data types of Y and Mdl.ClassNames are 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

collapse all

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

collapse all

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 the Mdl.MetricsWindowSize property.

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 updateMetrics before training the model on the same data using fit.

Algorithms

collapse all

Version History

Introduced in R2026b