# incrementalRegressionLinear

Linear regression model for incremental learning

## Description

incrementalRegressionLinear creates an incrementalRegressionLinear model object, which represents an incremental linear model for regression problems. Supported learners include support vector machine (SVM) and least squares.

Unlike other Statistics and Machine Learning Toolbox™ model objects, incrementalRegressionLinear can be called directly. Also, you can specify learning options, such as performance metrics configurations, parameter values, and the objective solver, before fitting the model to data. After you create an incrementalRegressionLinear object, it is prepared for incremental learning.

incrementalRegressionLinear is best suited for incremental learning. For a traditional approach to training an SVM or linear regression model (such as creating a model by fitting it to data, performing cross-validation, tuning hyperparameters, and so on), see fitrsvm or fitrlinear.

## Creation

You can create an incrementalRegressionLinear model object in several ways:

• Call the function directly — Configure incremental learning options, or specify initial values for linear model parameters and hyperparameters, by calling incrementalRegressionLinear directly. This approach is best when you do not have data yet or you want to start incremental learning immediately.

• Convert a traditionally trained model — To initialize an linear regression model for incremental learning using the model coefficients and hyperparameters of a trained SVM or linear regression model object, you can convert the traditionally trained model to an incrementalRegressionLinear model object by passing it to the incrementalLearner function. This table contains links to the appropriate reference pages.

• Call an incremental learning functionfit, updateMetrics, and updateMetricsAndFit accept a configured incrementalRegressionLinear model object and data as input, and return an incrementalRegressionLinear model object updated with information learned from the input model and data.

### Syntax

Mdl = incrementalRegressionLinear()
Mdl = incrementalRegressionLinear(Name,Value)

### Description

example

Mdl = incrementalRegressionLinear() returns a default incremental linear model object for regression Mdl. Properties of a default model contain placeholders for unknown model parameters. You must train a default model before you can track its performance or generate predictions from it.

example

Mdl = incrementalRegressionLinear(Name,Value) sets properties and additional options using name-value pair arguments. Enclose each name in quotes. For example, incrementalRegressionLinear('Beta',[0.1 0.3],'Bias',1,'MetricsWarmupPeriod',100) sets the vector of linear model coefficients β to [0.1 0.3], the bias β0 to 1, and the metrics warm-up period to 100.

### Input Arguments

expand all

Name-Value Pair Arguments

Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and Value is the corresponding value. Name must appear inside quotes. You can specify several name and value pair arguments in any order as Name1,Value1,...,NameN,ValueN.

Example: 'Standardize',true standardizes the predictor data using the predictor means and standard deviations estimated during the estimation period.

Model performance metrics to track during incremental learning, specified as the comma-separated pair consisting of 'Metrics' and a built-in loss function name, string vector of names, function handle (@metricName), structure array of function handles, or cell vector of names, function handles, or structure arrays.

When Mdl is warm (see IsWarm), updateMetrics and updateMetricsAndFit track performance metrics in the Metrics property of Mdl.

The following table lists the built-in loss-function names and which learners, specified in Mdl.Learner, support them. You can specify more than one loss function by using a string vector.

NameDescriptionLearners Supporting Metric
"epsiloninsensitive"Epsilon insensitive loss'svm'
"mse"Weighted mean squared error'svm' and 'leastsquares'

For more details on the built-in loss functions, see loss.

Example: 'Metrics',["epsiloninsensitive" "mse"]

To specify a custom function that returns a performance metric, use function handle notation. The function must have this form:

metric = customMetric(Y,YFit)

• The output argument metric is an n-by-1 numeric vector, where each element is the loss of the corresponding observation in the data processed by the incremental learning functions during a learning cycle.

• You select the function name (customMetric).

• Y is a length n numeric vector of observed responses, where n is the sample size.

• YFit is a length n numeric vector of corresponding predicted responses.

To specify multiple custom metrics and assign a custom name to each, use a structure array. To specify a combination of built-in and custom metrics, use a cell vector.

Example: 'Metrics',struct('Metric1',@customMetric1,'Metric2',@customMetric2)

Example: 'Metrics',{@customMetric1 @customeMetric2 'mse' struct('Metric3',@customMetric3)}

updateMetrics and updateMetricsAndFit store specified metrics in a table in the property Metrics. The data type of Metrics determines the row names of the table.

'Metrics' Value Data TypeDescription of Metrics Property Row NameExample
String or character vectorName of corresponding built-in metricRow name for "epsiloninsensitive" is "EpsilonInsensitiveLoss"
Structure arrayField nameRow name for struct('Metric1',@customMetric1) is "Metric1"
Function handle to function stored in a program fileName of functionRow name for @customMetric is "customMetric"
Anonymous functionCustomMetric_j, where j is metric j in MetricsRow name for @(Y,YFit)customMetric(Y,YFit)... is CustomMetric_1

By default:

• Metrics is "epsiloninsensitive" if Mdl.Learner is 'svm'.

• Metrics is "mse" if Mdl.Learner is 'leastsquares'.

For more details on performance metrics options, see Performance Metrics.

Data Types: char | string | struct | cell | function_handle

Flag to standardize the predictor data, specified as the comma-separated pair consisting of 'Standardize' and a value in this table.

ValueDescription
'auto'incrementalRegressionLinear determines whether the predictor variables need to be standardized. See Standardize Data.
trueThe software standardizes the predictor data. For more details, see Standardize Data.
falseThe software does not standardize the predictor data.

Example: 'Standardize',true

Data Types: logical | char | string

## Properties

expand all

You can set most properties by using name-value pair argument syntax only when you call incrementalRegressionLinear. You can set some properties when you call incrementalLearner to convert a traditionally trained model. You cannot set the properties FittedLoss, NumTrainingObservations, Mu, Sigma, SolverOptions , and IsWarm.

## Regression Model Parameters

Linear model coefficients β, specified as a NumPredictors-by-1 numeric vector.

If you convert a traditionally trained model to create Mdl, Beta is specified by the value of the Beta property of the traditionally trained model. Otherwise, by default, Beta is zeros(NumPredictors,1).

Data Types: single | double

Model intercept β0, or bias term, specified as a numeric scalar.

If you convert a traditionally trained model to create Mdl, Bias is specified by the value of the Bias property of the traditionally trained model. Otherwise, by default, Bias is 0.

Data Types: single | double

Half of the width of the epsilon insensitive-band, specified as 'auto' or a nonnegative scalar.

If you specify 'auto' when you call incrementalRegressionLinear, incremental fitting functions estimate Epsilon during the estimation period, specified by EstimationPeriod, using this procedure:

• If iqr(Y) ≠ 0, Epsilon is iqr(Y)/13.49, where Y is the estimation period response data.

• If iqr(Y) = 0 or before you fit Mdl to data, Epsilon is 0.1.

If you convert a traditionally trained SVM regression model to create Mdl (Learner is 'svm'), Epsilon is specified by the value of the Epsilon property of the traditionally trained model.

If Learner is 'leastsquares', you cannot set Epsilon and its value is NaN.

Data Types: single | double

Loss function used to fit the linear model, specified as 'epsiloninsensitive' or 'mse'.

ValueAlgorithmLoss functionLearner Value
'epsiloninsensitive'Support vector machine regressionEpsilon insensitive: $\ell \left[y,f\left(x\right)\right]=\mathrm{max}\left[0,|y-f\left(x\right)|-\epsilon \right]$'svm'
'mse'Linear regression through ordinary least squaresMean squared error (MSE): $\ell \left[y,f\left(x\right)\right]=\frac{1}{2}{\left[y-f\left(x\right)\right]}^{2}$'leastsquares'

Linear regression model type, specified as 'leastsquares' or 'svm'.

In the following table, $f\left(x\right)=x\beta +b.$

• β is Beta.

• x is an observation from p predictor variables.

• β0 is Bias.

ValueAlgorithmLoss functionFittedLoss Value
'leastsquares'Linear regression through ordinary least squaresMean squared error (MSE): $\ell \left[y,f\left(x\right)\right]=\frac{1}{2}{\left[y-f\left(x\right)\right]}^{2}$'mse'
'svm'Support vector machine regressionEpsilon insensitive: $\ell \left[y,f\left(x\right)\right]=\mathrm{max}\left[0,|y-f\left(x\right)|-\epsilon \right]$'epsiloninsensitive'

If you convert a traditionally trained model to create Mdl, Learner is the learner of the traditionally trained model.

• If the traditionally trained model is CompactRegressionSVM or RegressionSVM, Learner is 'svm'.

• If the traditionally trained model is RegressionLinear, Learner is the value of the Learner property of the traditionally trained model.

Number of predictor variables, specified as a nonnegative numeric scalar.

If you convert a traditionally trained model to create Mdl, NumPredictors is specified by the congruent property of the traditionally trained model. Otherwise, incremental fitting functions infer NumPredictors from the predictor data during training.

Data Types: double

Number of observations fit to the incremental model Mdl, specified as a nonnegative numeric scalar. NumTrainingObservations increases when you pass Mdl and training data to fit or updateMetricsAndFit.

Note

If you convert a traditionally trained model to create Mdl, incrementalRegressionLinear does not add the number of observations fit to the traditionally trained model to NumTrainingObservations.

Data Types: double

Response transformation function, specified as 'none' or a function handle. ResponseTransform describes how incremental learning functions transform raw response values.

For a MATLAB® function or a function that you define, enter its function handle; for example, 'ResponseTransform',@function, where function accepts an n-by-1 vector (the original responses) and returns a vector of the same length (the transformed responses).

• If you convert a traditionally trained model to create Mdl, ResponseTransform is specified by the congruent property of the traditionally trained model.

• Otherwise, ResponseTransform is 'none'.

Data Types: char | function_handle

## Training Parameters

Number of observations processed by the incremental model to estimate hyperparameters before training or tracking performance metrics, specified as a nonnegative integer.

Note

• If Mdl is prepared for incremental learning (all hyperparameters required for training are specified), incrementalRegressionLinear forces 'EstimationPeriod' to 0.

• If Mdl is not prepared for incremental learning, incrementalRegressionLinear sets 'EstimationPeriod' to 1000.

For more details, see Estimation Period.

Data Types: single | double

Linear model intercept inclusion flag, specified as true or false.

ValueDescription
trueincrementalRegressionLinear includes the bias term β0 in the linear model, which incremental fitting functions fit to data.
falseincrementalRegressionLinear sets β0 = 0.

If Bias ≠ 0, FitBias must be true. In other words, incrementalRegressionLinear does not support an equality constraint on β0.

If you convert a traditionally trained linear regression model (RegressionLinear) to create Mdl, FitBias is specified by the value of the ModelParameters.FitBias property of the traditionally trained model.

Data Types: logical

Predictor means, specified as a numeric vector.

If Mu is an empty array [] and you specify 'Standardize',true, incremental fitting functions set Mu to the predictor variable means estimated during the estimation period specified by EstimationPeriod.

You cannot specify Mu directly.

Data Types: single | double

Predictor standard deviations, specified as a numeric vector.

If Sigma is an empty array [] and you specify 'Standardize',true, incremental fitting functions set Sigma to the predictor variable standard deviations estimated during the estimation period specified by EstimationPeriod.

You cannot specify Sigma directly.

Data Types: single | double

Objective function minimization technique, specified as a value in this table.

ValueDescriptionNotes
'scale-invariant'

• This algorithm is parameter free and can adapt to differences in predictor scales. Try this algorithm before using SGD or ASGD.

• To shuffle incoming batches before the fit function fits the model, set Shuffle to true.

'sgd'Stochastic gradient descent (SGD) [3][2]

• To train effectively with SGD, standardize the data and specify adequate values for hyperparameters using options listed in SGD and ASGD Solver Parameters.

• The fit function always shuffles an incoming batch of data before fitting the model.

'asgd'Average stochastic gradient descent (ASGD) [4]

• To train effectively with ASGD, standardize the data and specify adequate values for hyperparameters using options listed in SGD and ASGD Solver Parameters.

• The fit function always shuffles an incoming batch of data before fitting the model.

If you convert a traditionally trained linear regression model (RegressionLinear) to create Mdl, whose ModelParameters.Solver property is 'sgd' or 'asgd', Solver is specified by the ModelParameters.Solver property of the traditionally trained model.

Data Types: char | string

Objective solver configurations, specified as a structure array. The fields of SolverOptions are properties specific to the specified solver Solver.

Data Types: struct

## SGD and ASGD Solver Parameters

Mini-batch size, specified as a positive integer. At each iteration during training, incrementalRegressionLinear uses min(BatchSize,numObs) observations to compute the subgradient, where numObs is the number of observations in the training data passed to fit or updateMetricsAndFit.

If you convert a traditionally trained linear regression model (RegressionLinear) to create Mdl, whose ModelParameters.Solver property is 'sgd' or 'asgd', BatchSize is specified by the ModelParameters.BatchSize property of the traditionally trained model. Otherwise, the default is 10.

Data Types: single | double

Ridge (L2) regularization term strength, specified as a nonnegative scalar.

If you convert a traditionally trained linear model for ridge regression (RegressionLinear object with the Regularization property equal to 'ridge (L2)') to create Mdl, Lambda is specified by the value of the Lambda property of the traditionally trained model. Otherwise, the default is 1e-5.

Data Types: double | single

Learning rate, specified as 'auto' or a positive scalar. LearnRate controls the optimization step size by scaling the objective subgradient.

When you specify 'auto':

• If EstimationPeriod is 0, the initial learning rate is 0.7.

• If EstimationPeriod > 0, the initial learning rate is 1/sqrt(1+max(sum(X.^2,obsDim))), where obsDim is 1 if the observations compose the columns of the predictor data, and 2 otherwise. fit and updateMetricsAndFit set the value when you pass the model and training data to either.

If you convert a traditionally trained linear regression model (RegressionLinear) to create Mdl, whose ModelParameters.Solver property is 'sgd' or 'asgd', LearnRate is specified by the ModelParameters.LearnRate property of the traditionally trained model.

The LearnRateSchedule property determines the learning rate for subsequent learning cycles.

Example: 'LearnRate',0.001

Data Types: single | double | char | string

Learning rate schedule, specified as a value in this table, where LearnRate specifies the initial learning rate ɣ0.

ValueDescription
'constant'The learning rate is ɣ0 for all learning cycles.
'decaying'

The learning rate at learning cycle t is

${\gamma }_{t}=\frac{{\gamma }_{0}}{{\left(1+\lambda {\gamma }_{0}t\right)}^{c}}.$

• λ is the value of Lambda.

• If Solver is 'sgd', c = 1.

• If Solver is 'asgd':

• c = 2/3 if Learner is 'leastsquares'

• c = 3/4 if Learner is 'svm' [4]

If you convert a traditionally trained linear regression model (RegressionLinear) to create Mdl, whose ModelParameters.Solver property is 'sgd' or 'asgd', LearnRate is 'decaying'.

Data Types: char | string

Flag for shuffling the observations in the batch at each learning cycle, specified as a value in this table.

ValueDescription
trueThe software shuffles observations in each incoming batch of data before processing the set. This action reduces bias induced by the sampling scheme.
falseThe software processes the data in the order received.

Data Types: logical

## Performance Metrics Parameters

Flag indicating whether the incremental model tracks performance metrics, specified as false or true. The incremental model Mdl is warm (IsWarm becomes true) after incremental fitting functions fit MetricsWarmupPeriod observations to the incremental model (that is, EstimationPeriod + MetricsWarmupPeriod observations).

ValueDescription
trueThe incremental model Mdl is warm. Consequently, updateMetrics and updateMetricsAndFit track performance metrics in the Metrics property of Mdl.
falseupdateMetrics and updateMetricsAndFit do not track performance metrics.

Data Types: logical

Model performance metrics updated during incremental learning by updateMetrics and updateMetricsAndFit, specified as a table with two columns and m rows, where m is the number of metrics specified by the 'Metrics' name-value pair argument.

The columns of Metrics are labeled Cumulative and Window.

• Cumulative: Element j is the model performance, as measured by metric j, from the time the model became warm (IsWarm is 1).

• Window: Element j is the model performance, as measured by metric j, evaluated over all observations within the window specified by the MetricsWindowSize property. The software updates Window after it processes MetricsWindowSize observations.

Rows are labeled by the specified metrics. For details, see 'Metrics'.

Data Types: table

Number of observations the incremental model must be fit to before it tracks performance metrics in its Metrics property, specified as a nonnegative integer.

For more details, see Performance Metrics.

Data Types: single | double

Number of observations to use to compute window performance metrics, specified as a positive integer.

For more details on performance metrics options, see Performance Metrics.

Data Types: single | double

## Object Functions

 fit Train linear model for incremental learning updateMetricsAndFit Update performance metrics in linear model for incremental learning given new data and train model updateMetrics Update performance metrics in linear model for incremental learning given new data loss Loss of linear model for incremental learning on batch of data predict Predict responses for new observations from linear model for incremental learning

## Examples

collapse all

Create a default incremental linear model for regression.

Mdl = incrementalRegressionLinear()
Mdl = incrementalRegressionLinear IsWarm: 0 Metrics: [1x2 table] ResponseTransform: 'none' Beta: [0x1 double] Bias: 0 Learner: 'svm' Properties, Methods 
Mdl.EstimationPeriod
ans = 1000 

Mdl is an incrementalRegressionLinear model object. All its properties are read-only.

Mdl must be fit to data before you can use it to perform any other operations. The software sets the estimation period to 1000 because half the width of the epsilon insensitive band Epsilon is unknown. You can set Epsilon to a positive floating point scalar by using the 'Epsilon' name-value pair argument. This action results in a default estimation period of 0.

Load the robot arm data set.

load robotarm

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

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

• Process 50 observations.

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

• Store ${\beta }_{1}$, the cumulative metrics, and the window metrics to see how they evolve during incremental learning.

% Preallocation n = numel(ytrain); numObsPerChunk = 50; nchunk = floor(n/numObsPerChunk); ei = array2table(zeros(nchunk,2),'VariableNames',["Cumulative" "Window"]); beta1 = 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,Xtrain(idx,:),ytrain(idx)); ei{j,:} = Mdl.Metrics{"EpsilonInsensitiveLoss",:}; beta1(j + 1) = Mdl.Beta(1); end

IncrementalMdl is an incrementalRegressionLinear model object trained on all the data in the stream. While updateMetricsAndFit processes the first 1000 observations, it stores a buffer to estimate Epsilon; the function does not fit the coefficients until after this estimation period. During incremental learning and after the model is warmed up, updateMetricsAndFit checks the performance of the model on the incoming observation, and then fits the model to that observation.

To see how the performance metrics and ${\beta }_{1}$ evolved during training, plot them on separate subplots.

figure; subplot(2,1,1) plot(beta1) ylabel('\beta_1') xlim([0 nchunk]); xline(Mdl.EstimationPeriod/numObsPerChunk,'r-.'); subplot(2,1,2) h = plot(ei.Variables); xlim([0 nchunk]); ylabel('Epsilon Insensitive Loss') xline(Mdl.EstimationPeriod/numObsPerChunk,'r-.'); xline((Mdl.EstimationPeriod + Mdl.MetricsWarmupPeriod)/numObsPerChunk,'g-.'); legend(h,ei.Properties.VariableNames) xlabel('Iteration')

The plot suggests that updateMetricsAndFit does the following:

• After the estimation period (first 20 iterations), fit ${\beta }_{1}$ during all incremental learning iterations.

• Compute performance metrics after the metrics warm-up period only.

• Compute the cumulative metrics during each iteration.

• Compute the window metrics after processing 500 observations (4 iterations).

Prepare an incremental regression learner by specifying a metrics warm-up period, during which the updateMetricsAndFit function only fits the model. Specify a metrics window size of 500 observations. Train the model by using SGD, and adjust the SGD batch size, learning rate, and regularization parameter.

Load the robot arm data set.

load robotarm n = numel(ytrain);

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

Create an incremental linear model for regression. Configure the model as follows:

• Specify the SGD solver.

• Assume that a ridge regularization parameter value of 0.001, SGD batch size of 20, learning rate of 0.002, and half the width of the epsilon insensitive band for SVM of 0.05 work well for the problem.

• Specify that the incremental fitting functions process the raw (unstandardized) predictor data.

• Specify a metrics warm-up period of 1000 observations.

• Specify a metrics window size of 500 observations.

• Track the epsilon insensitive loss, MSE, and mean absolute error (MAE) to measure the performance of the model. The software supports epsilon insensitive loss and MSE. Create an anonymous function that measures the absolute error of each new observation. Create a structure array containing the name MeanAbsoluteError and its corresponding function.

maefcn = @(z,zfit)abs(z - zfit); maemetric = struct("MeanAbsoluteError",maefcn); Mdl = incrementalRegressionLinear('Epsilon',0.05,... 'Solver','sgd','Lambda',0.001,'BatchSize',20,'LearnRate',0.002,... 'Standardize',false,... 'MetricsWarmupPeriod',1000,'MetricsWindowSize',500,... 'Metrics',{'epsiloninsensitive' 'mse' maemetric})
Mdl = incrementalRegressionLinear IsWarm: 0 Metrics: [3x2 table] ResponseTransform: 'none' Beta: [0x1 double] Bias: 0 Learner: 'svm' Properties, Methods 

Mdl is an incrementalRegressionLinear model object configured for incremental learning without an estimation period.

Fit the incremental model to the data by using updateMetricsAndfit function. At each iteration:

• Simulate a data stream by processing a chunk of 50 observations. Note that chunk size is different from SGD batch size.

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

• Store the estimated coefficient ${\beta }_{10}$, the cumulative metrics, and the window metrics to see how they evolve during incremental learning.

% Preallocation numObsPerChunk = 50; nchunk = floor(n/numObsPerChunk); ei = array2table(zeros(nchunk,2),'VariableNames',["Cumulative" "Window"]); mse = array2table(zeros(nchunk,2),'VariableNames',["Cumulative" "Window"]); mae = array2table(zeros(nchunk,2),'VariableNames',["Cumulative" "Window"]); beta10 = 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,Xtrain(idx,:),ytrain(idx)); ei{j,:} = Mdl.Metrics{"EpsilonInsensitiveLoss",:}; mse{j,:} = Mdl.Metrics{"MeanSquaredError",:}; mae{j,:} = Mdl.Metrics{"MeanAbsoluteError",:}; beta10(j + 1) = Mdl.Beta(10); end

IncrementalMdl is an incrementalRegressionLinear 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 observation, and then fits the model to that observation.

To see how the performance metrics and ${\beta }_{10}$ evolved during training, plot them on separate subplots.

figure; subplot(2,2,1) plot(beta10) ylabel('\beta_{10}') xlim([0 nchunk]); xline(Mdl.MetricsWarmupPeriod/numObsPerChunk,'r-.'); xlabel('Iteration') subplot(2,2,2) h = plot(ei.Variables); xlim([0 nchunk]); ylabel('Epsilon Insensitive Loss') xline(Mdl.MetricsWarmupPeriod/numObsPerChunk,'r-.'); legend(h,ei.Properties.VariableNames) xlabel('Iteration') subplot(2,2,3) h = plot(mse.Variables); xlim([0 nchunk]); ylabel('MSE') xline(Mdl.MetricsWarmupPeriod/numObsPerChunk,'r-.'); legend(h,mse.Properties.VariableNames) xlabel('Iteration') subplot(2,2,4) h = plot(mae.Variables); xlim([0 nchunk]); ylabel('MAE') xline(Mdl.MetricsWarmupPeriod/numObsPerChunk,'r-.'); legend(h,mae.Properties.VariableNames) xlabel('Iteration')

The plot suggests that updateMetricsAndFit does the following:

• Fit ${\beta }_{10}$ during all incremental learning iterations.

• Compute performance metrics after the metrics warm-up period only.

• Compute the cumulative metrics during each iteration.

• Compute the window metrics after processing 500 observations (10 iterations).

Train a linear regression model by using fitrlinear, convert it to an incremental learner, track its performance, and fit it to streaming data. Carry over training options from traditional to incremental learning.

Load the 2015 NYC housing data set, and shuffle the data. For more details on the data, see NYC Open Data.

load NYCHousing2015 rng(1); % For reproducibility n = size(NYCHousing2015,1); idxshuff = randsample(n,n); NYCHousing2015 = NYCHousing2015(idxshuff,:);

Suppose that the data collected from Manhattan (BOROUGH = 1) was collected using a new method that doubles its quality. Create a weight variable that attributes 2 to observations collected from Manhattan, and 1 to all other observations.

NYCHousing2015.W = ones(n,1) + (NYCHousing2015.BOROUGH == 1);

Extract the response variable SALEPRICE from the table. For numerical stability, scale SALEPRICE by 1e6.

Y = NYCHousing2015.SALEPRICE/1e6; NYCHousing2015.SALEPRICE = [];

Create dummy variable matrices from the categorical predictors.

catvars = ["BOROUGH" "BUILDINGCLASSCATEGORY" "NEIGHBORHOOD"]; dumvarstbl = varfun(@(x)dummyvar(categorical(x)),NYCHousing2015,... 'InputVariables',catvars); dumvarmat = table2array(dumvarstbl); NYCHousing2015(:,catvars) = [];

Treat all other numeric variables in the table as linear predictors of sales price. Concatenate the matrix of dummy variables to the rest of the predictor data. Transpose the resulting predictor matrix.

idxnum = varfun(@isnumeric,NYCHousing2015,'OutputFormat','uniform'); X = [dumvarmat NYCHousing2015{:,idxnum}]';

Train Linear Regression Model

Fit a linear regression model to a random sample of half the data.

idxtt = randsample([true false],n,true); TTMdl = fitrlinear(X(:,idxtt),Y(idxtt),'ObservationsIn','columns',... 'Weights',NYCHousing2015.W(idxtt))
TTMdl = RegressionLinear ResponseName: 'Y' ResponseTransform: 'none' Beta: [313x1 double] Bias: 0.1116 Lambda: 2.1977e-05 Learner: 'svm' Properties, Methods 

TTMdl is a RegressionLinear model object representing a traditionally trained linear regression model.

Convert Trained Model

Convert the traditionally trained linear regression model to a linear regression model for incremental learning.

IncrementalMdl = incrementalLearner(TTMdl)
IncrementalMdl = incrementalRegressionLinear IsWarm: 1 Metrics: [1x2 table] ResponseTransform: 'none' Beta: [313x1 double] Bias: 0.1116 Learner: 'svm' Properties, Methods 

Separately Track Performance Metrics and Fit Model

Perform incremental learning on the rest of the data by using the updateMetrics and fit functions. Simulate a data stream by processing 500 observations at a time. At each iteration:

1. Call updateMetrics to update the cumulative and window epsilon insensitive loss 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.

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

3. Store the losses and last estimated coefficient ${\beta }_{313}$.

% Preallocation idxil = ~idxtt; nil = sum(idxil); numObsPerChunk = 500; nchunk = floor(nil/numObsPerChunk); ei = array2table(zeros(nchunk,2),'VariableNames',["Cumulative" "Window"]); beta313 = [IncrementalMdl.Beta(end); zeros(nchunk,1)]; Xil = X(:,idxil); Yil = Y(idxil); Wil = NYCHousing2015.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),... 'ObservationsIn','columns','Weights',Wil(idx)); ei{j,:} = IncrementalMdl.Metrics{"EpsilonInsensitiveLoss",:}; IncrementalMdl = fit(IncrementalMdl,Xil(:,idx),Yil(idx),'ObservationsIn','columns',... 'Weights',Wil(idx)); beta313(j + 1) = IncrementalMdl.Beta(end); end

IncrementalMdl is an incrementalRegressionLinear 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 and estimated coefficient ${\beta }_{313}$.

figure; subplot(2,1,1) h = plot(ei.Variables); xlim([0 nchunk]); ylabel('Epsilon Insensitive Loss') legend(h,ei.Properties.VariableNames) subplot(2,1,2) plot(beta313) ylabel('\beta_{313}') xlim([0 nchunk]); xlabel('Iteration')

The cumulative loss gradually changes with each iteration (chunk of 500 observations), whereas the window loss jumps. Because the metrics window is 200 by default, updateMetrics measures the performance based on the latest 200 observations in each 500 observation chunk.

${\beta }_{313}$ changes abruptly, then levels off as fit processes chunks of observations.

expand all

## Tips

• After creating a model, you can generate C/C++ code that performs incremental learning on a data stream. Generating C/C++ code requires MATLAB Coder™. For details, see Introduction to Code Generation.

expand all

## References

[1] Kempka, Michał, Wojciech Kotłowski, and Manfred K. Warmuth. "Adaptive Scale-Invariant Online Algorithms for Learning Linear Models." CoRR (February 2019). https://arxiv.org/abs/1902.07528.

[2] Langford, J., L. Li, and T. Zhang. “Sparse Online Learning Via Truncated Gradient.” J. Mach. Learn. Res., Vol. 10, 2009, pp. 777–801.

[3] Shalev-Shwartz, S., Y. Singer, and N. Srebro. “Pegasos: Primal Estimated Sub-Gradient Solver for SVM.” Proceedings of the 24th International Conference on Machine Learning, ICML ’07, 2007, pp. 807–814.

[4] Xu, Wei. “Towards Optimal One Pass Large Scale Learning with Averaged Stochastic Gradient Descent.” CoRR, abs/1107.2490, 2011.

## Extended Capabilities

Introduced in R2020b