主要内容

fit

R2026b

Train neural network model for incremental learning

Since R2026b

Description

The fit function fits a configured incremental neural network model for classification (incrementalClassificationNeuralNetwork model object) or regression (incrementalRegressionNeuralNetwork model object) to streaming data. To additionally track performance metrics using the data as it arrives, use updateMetricsAndFit instead.

To fit or cross-validate a neural network classification or regression model to an entire batch of data at once, see fitcnet or fitrnet, respectively.

Mdl = fit(Mdl,X,Y) returns an incremental learning model Mdl, which represents the input learning model Mdl trained using the predictor and response data, X and Y respectively. Specifically, fit updates the neural network weights and biases using the specified solver algorithm.

example

Mdl = fit(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

[Mdl,ConvergenceInfo] = fit(___) also returns solver convergence information in the structure ConvergenceInfo, using any of the input arguments from the previous syntaxes.

Examples

collapse all

Fit an incremental neural network classifier when you know only the expected maximum number of classes in the data.

Create an incremental neural network model. Specify that the maximum number of expected classes is 5.

clear
Mdl = incrementalClassificationNeuralNetwork(MaxNumClasses=5)
Mdl = 
  incrementalClassificationNeuralNetwork

                   IsWarm: 0
                  Metrics: [1×2 table]
               ClassNames: [1×0 double]
           ScoreTransform: 'none'
               LayerSizes: 10
              Activations: "relu"
    OutputLayerActivation: "softmax"
                   Solver: "minibatch-lbfgs"


  Properties, Methods

Mdl is an incrementalClassificationNeuralNetwork model. All its properties are read-only. Mdl can process at most 5 unique classes. By default, the prior class distribution Mdl.Prior is empirical, which means the software updates the prior distribution as it encounters labels.

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(0,"twister") % For reproducibility
idx = randsample(n,n);
X = feat(idx,:);
Y = actid(idx);

For details on the data set, enter Description at the command line.

Fit the incremental model to the training data, in chunks of 50 observations at a time, by using the fit function. At each iteration:

  • Simulate a data stream by processing 50 observations.

  • Overwrite the previous incremental model with a new one fitted to the incoming observations.

  • Store the mean bias of the second layer and the prior probability that the subject is moving (Y > 2) to see how these parameters evolve during incremental learning.

% Preallocation
numObsPerChunk = 50;
nchunk = floor(n/numObsPerChunk);
lb2 = zeros(nchunk,1);    
priormoved = zeros(nchunk,1);
prev = zeros(10,60);
% Incremental fitting
for j = 1:nchunk
    ibegin = min(n,numObsPerChunk*(j-1) + 1);
    iend   = min(n,numObsPerChunk*j);
    idx = ibegin:iend;    
    Mdl = fit(Mdl,X(idx,:),Y(idx));
    lb2(j) = mean(Mdl.LayerBiases{2});
    priormoved(j) = sum(Mdl.Prior(Mdl.ClassNames > 2));
    c = Mdl.LayerWeights{1};
    c-prev;
    prev = c;
end

Mdl is an incrementalClassificationNeuralNetwork model object trained on all the data in the stream.

To see how the parameters evolve during incremental learning, plot them on separate tiles.

t = tiledlayout(2,1);
nexttile
plot(lb2)
xlim([0 nchunk])
xline(Mdl.TrainingOptions.TuningPeriod/numObsPerChunk,"b--");
ylabel("Mean Layer 2 Bias")
nexttile
plot(priormoved)
xlim([0 nchunk])
ylabel("\pi(Subject Is Moving)")
xlabel(t,"Iteration")

Figure contains 2 axes objects. Axes object 1 with ylabel Mean Layer 2 Bias contains 2 objects of type line, constantline. Axes object 2 with ylabel \pi(Subject Is Moving) contains an object of type line.

The plots indicate that Fit performs the following actions:

  • Fit the layer biases after the solver tuning period (blue vertical line) only.

  • Compute the prior probabilities during each iteration.

Because the prior class distribution is empirical, π(subject is moving) changes as fit processes each chunk.

Incrementally train a neural network classification model only when its performance degrades.

Load the human activity data set. Randomly shuffle the data.

load humanactivity
n = numel(actid);
rng(0,"twister") % For reproducibility
idx = randsample(n,n);
X = feat(idx,:);
Y = actid(idx);

For details on the data set, enter Description at the command line.

Configure a neural network classification model for incremental learning so that the maximum number of expected classes is 5, and the metrics window size is 1000. Prepare the model for updateMetrics by fitting the model to the first 2000 observations, and store the classification error metric.

Mdl = incrementalClassificationNeuralNetwork(MaxNumClasses=5, ...
    MetricsWindowSize=1000,Metrics="classiferror");
initobs = 2000;
Mdl = fit(Mdl,X(1:initobs,:),Y(1:initobs));

Mdl is an incrementalClassificationNeuralNetwork model object.

Determine whether the model is warm by querying the model property.

isWarm = Mdl.IsWarm
isWarm = logical
   1

Mdl.IsWarm is 1; therefore, Mdl is warm.

Perform incremental learning, with conditional fitting, by following this procedure for each iteration:

  • Simulate a data stream by processing a chunk of 100 observations at a time.

  • Update the model performance on the incoming chunk of data.

  • Fit the model to the chunk of data only when the window misclassification error rate is greater than 0.05.

  • When tracking performance and fitting, overwrite the previous incremental model.

  • Store the misclassification error rate and the mean bias of the second layer to see how they evolve during training.

  • Track when fit trains the model.

% Preallocation
numObsPerChunk = 100;
nchunk = floor((n - initobs)/numObsPerChunk);
lb2 = zeros(nchunk,1);
ce = array2table(nan(nchunk,2),VariableNames=["Cumulative","Window"]);
trained = false(nchunk,1);

% Incremental fitting
for j = 1:nchunk
    ibegin = min(n,numObsPerChunk*(j-1) + 1 + initobs);
    iend = min(n,numObsPerChunk*j + initobs);
    idx = ibegin:iend;
    Mdl = updateMetrics(Mdl,X(idx,:),Y(idx));
    ce{j,:} = Mdl.Metrics{"ClassificationError",:};
    if ce{j,2} > 0.05
        Mdl = fit(Mdl,X(idx,:),Y(idx));
        trained(j) = true;
    end    
    lb2(j) = mean(Mdl.LayerBiases{2});
end

Mdl is an incrementalClassificationNeuralNetwork model object trained on all the data in the stream.

To see how the performance metrics and the mean bias of the second layer evolve during training, plot them on separate tiles.

t = tiledlayout(2,1);
nexttile
plot(lb2)
hold on
plot(find(trained),lb2(trained),"r.")
ylabel("Mean Layer 2 Bias")
xlim([0 nchunk]);
legend("Mean Layer 2 Bias","Training occurs",Location="best")
hold off
nexttile
plot(ce.Variables)
yline(0.05,"--")
xlim([0 nchunk])
ylabel("Misclassification Error Rate")
legend(ce.Properties.VariableNames,Location="best")
xlabel(t,"Iteration")

Figure contains 2 axes objects. Axes object 1 with ylabel Mean Layer 2 Bias contains 2 objects of type line. One or more of the lines displays its values using only markers These objects represent Mean Layer 2 Bias, Training occurs. Axes object 2 with ylabel Misclassification Error Rate contains 3 objects of type line, constantline. These objects represent Cumulative, Window.

The trace plot of the mean layer 2 bias shows periods of constant values, during which the loss within the previous observation window is at most 0.05.

Input Arguments

collapse all

Incremental learning model to fit to streaming data, 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.

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

  • fit 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, fit 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

fit ignores an observation with a NaN value in the predictor data X, in the labels Y, or in the weights Weights.

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: 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. fit 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 model is warm, the output model Mdl is the input model trained on the incoming data. Specifically, fit updates the LayerWeights, LayerBiases, and NumTrainingObservations properties.

Solver convergence information, returned as a structure containing the following fields:

  • GradientsNorm — A real nonnegative scalar specifying the L-infinity norm of the gradient at the last iteration.

  • StepNorm — A real nonnegative scalar specifying the L2 norm of the step taken at the last iteration.

  • Gradients — A cell array of numeric matrices specifying the gradients of the loss with respect to the parameters at the last iteration. Gradients has 2*K cells, where K is the number of cells in the LayerWeights property of Mdl. The first K cells correspond to the gradients with respect to Mdl.LayerWeights, and the remaining cells correspond to the gradients with respect to Mdl.LayerBiases.

During the estimation and solver tuning periods, the function returns NaN values for all fields.

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.

Algorithms

collapse all

Version History

Introduced in R2026b