fit
R2026bDescription
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.
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.Mdl = fit(Mdl,X,Y,Name=Value)
[
also returns solver convergence information in the structure
Mdl,ConvergenceInfo] = fit(___)ConvergenceInfo, using any of the input arguments from the previous
syntaxes.
Examples
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")

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

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
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( is the response (label) of
observation j (row or column) in j)X.
Note
fitsupports 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, fit 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
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
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
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.Gradientshas 2*K cells, where K is the number of cells in theLayerWeightsproperty ofMdl. The first K cells correspond to the gradients with respect toMdl.LayerWeights, and the remaining cells correspond to the gradients with respect toMdl.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
updateMetricsbefore training the model on the same data.
Algorithms
For classification problems, if the prior class probability distribution is known (in other words, the prior distribution is not empirical), fit 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.
The fit function uses the solver specified in
Mdl.TrainingOptions to update the neural network weights and biases.
The supported solvers are:
"minibatch-lbfgs"— A mini-batch L-BFGS (limited-memory Broyden-Fletcher-Goldfarb-Shanno) solver that processes the incoming data chunk as a mini-batch and performs multiple iterations of L-BFGS optimization on it."freerex"— An adaptive, scale-invariant online learning algorithm that does not require tuning a learning rate.
You can configure training options, including the solver choice, by using the
incrementalTrainingOptions function and passing the result to the
TrainingOptions name-value argument when creating the model.
When you train an incremental neural network model with the incremental fitting functions
fit and updateMetricsAndFit, then depending on the model's properties, up to three
incremental training periods can occur in the following order: the estimation period, the
solver tuning period, and the metrics warm-up period. Following these periods, the incremental
model is warm and the incremental fitting functions track model
performance metrics from new data.
During the estimation period, fit does not fit the model, and updateMetricsAndFit does not fit the model or update the performance metrics. The incremental fitting functions use the first incoming EstimationPeriod observations to estimate the predictor means and standard deviation hyperparameters required to standardize the data during incremental training. The fitting functions store the hyperparameter estimates in the Mu and Sigma properties of Mdl.
The hyperparameters are estimated when both of these conditions apply:
Incremental fitting functions are configured to standardize predictor data (see Standardize Data).
MuandSigmaare empty arrays[].
When you create the model object using the
incrementalLearner function, EstimationPeriod
is always 0.
During the solver tuning period, the incremental fitting functions use Mdl.TrainingOptions.TuningPeriod observations to tune the parameters of the mini-batch LBFGS solver (the default solver). There is no solver turning period for the FreeREX solver. You can select the solver algorithm and the length of the solver tuning period using the TrainingOptions name-value argument when you create the model object. For more information, see the Limited-Memory BFGS and FreeRex sections of the incrementalTrainingOptions reference page.
During the metrics warm-up period, the incremental fitting functions fit the incremental model.
An
incrementalClassificationNeuralNetworkmodel object is warm and tracks the performance metrics in itsMetricsproperty after the incremental fitting functions processMetricsWarmupPeriodobservations and fit at least one observation from each expected class (see theMaxNumClassesandClassNamesarguments ofincrementalClassificationNeuralNetwork).An
incrementalRegressionNeuralNetworkmodel object is warm after the incremental fitting functions processMetricsWarmupPeriodobservations.
Version History
Introduced in R2026b
See Also
Objects
Functions
fitcnet|fitrnet|predict|incrementalTrainingOptions|updateMetrics|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.
Sélectionner un site web
Choisissez un site web pour accéder au contenu traduit dans votre langue (lorsqu'il est disponible) et voir les événements et les offres locales. D’après votre position, nous vous recommandons de sélectionner la région suivante : .
Vous pouvez également sélectionner un site web dans la liste suivante :
Comment optimiser les performances du site
Pour optimiser les performances du site, sélectionnez la région Chine (en chinois ou en anglais). Les sites de MathWorks pour les autres pays ne sont pas optimisés pour les visites provenant de votre région.
Amériques
- 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)