incrementalRegressionKernel
Description
The incrementalRegressionKernel function creates an
        incrementalRegressionKernel model object, which represents a binary Gaussian kernel
      regression model for incremental learning. The kernel model maps data in a low-dimensional
      space into a high-dimensional space, then fits a linear model in the high-dimensional space.
      Supported linear models include support vector machine (SVM) and least-squares
      regression.
Unlike other Statistics and Machine Learning Toolbox™ model objects, incrementalRegressionKernel can be called directly. Also,
      you can specify learning options, such as performance metrics configurations and the objective
      solver, before fitting the model to data. After you create an incrementalRegressionKernel
      object, it is prepared for incremental learning.
incrementalRegressionKernel is best suited for incremental learning. For a traditional
      approach to training a kernel regression model (such as creating a model by fitting it to
      data, performing cross-validation, tuning hyperparameters, and so on), see fitrkernel.
Creation
You can create an incrementalRegressionKernel model object in several ways:
- Call the function directly — Configure incremental learning options, or specify learner-specific options, by calling - incrementalRegressionKerneldirectly. 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 a model for incremental learning using the model parameters and hyperparameters of a trained model object ( - RegressionKernel), you can convert the traditionally trained model to an- incrementalRegressionKernelmodel object by passing it to the- incrementalLearnerfunction.
- Call an incremental learning function — - fit,- updateMetrics, and- updateMetricsAndFitaccept a configured- incrementalRegressionKernelmodel object and data as input, and return an- incrementalRegressionKernelmodel object updated with information learned from the input model and data.
Description
Mdl = incrementalRegressionKernel()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.
Mdl = incrementalRegressionKernel(Name=Value)incrementalRegressionKernel(Solver="sgd",LearnRateSchedule="constant")
          specifies to use the stochastic gradient descent (SGD) solver with a constant learning
          rate.
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: Metrics="mse",MetricsWarmupPeriod=100 sets the model
          performance metric to the weighted mean squared error and the metrics warm-up period to
            100.
Regression Options
Random number stream for reproducibility of data transformation, specified as a random stream object. For details, see Random Feature Expansion.
Use RandomStream to reproduce the random basis functions used by
                incrementalRegressionKernel to transform the predictor data to a
            high-dimensional space. For details, see Managing the Global Stream Using RandStream
            and Creating and Controlling a Random Number Stream.
Example: RandomStream=RandStream("mlfg6331_64")
Since R2023b
Flag to standardize the predictor data, specified as a value in this table.
| Value | Description | 
|---|---|
| "auto" | incrementalRegressionKerneldetermines whether the predictor
                          variables need to be standardized. See Standardize Data. | 
| true | The software standardizes the predictor data. For more details, see Standardize Data. | 
| false | The software does not standardize the predictor data. | 
Example: Standardize=true
Data Types: logical | char | string
SGD and ASGD (Average SGD) Solver Options
Mini-batch size, specified as a positive integer. At each learning cycle during
            training, incrementalRegressionKernel uses BatchSize
            observations to compute the subgradient.
The number of observations in the last mini-batch (last learning cycle in each
            function call of fit or
                updateMetricsAndFit) can be smaller than BatchSize.
            For example, if you supply 25 observations to fit or
                updateMetricsAndFit, the function uses 10 observations for the
            first two learning cycles and 5 observations for the last learning cycle.
Example: BatchSize=5
Data Types: single | double
Ridge (L2) regularization term strength, specified as a nonnegative scalar.
Example: Lambda=0.01
Data Types: single | double
Initial learning rate, specified as "auto" or a positive
            scalar.
The learning rate controls the optimization step size by scaling the objective
            subgradient. LearnRate specifies an initial value for the learning
            rate, and LearnRateSchedule
            determines the learning rate for subsequent learning cycles.
When you specify "auto":
- The initial learning rate is - 0.7.
- If - EstimationPeriod>- 0,- fitand- updateMetricsAndFitchange the rate to- 1/sqrt(1+max(sum(X.^2,2)))at the end of- EstimationPeriod.
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. 
| Value | Description | 
|---|---|
| "constant" | The learning rate is ɣ0 for all learning cycles. | 
| "decaying" | The learning rate at learning cycle t is 
 
 | 
Example: LearnRateSchedule="constant"
Data Types: char | string
Adaptive Scale-Invariant Solver Options
Flag for shuffling the observations at each iteration, specified as logical
                1 (true) or 0
                (false).
| Value | Description | 
|---|---|
| logical 1(true) | The software shuffles the observations in an incoming chunk of
                                data before the fitfunction fits the model. This
                                action reduces bias induced by the sampling scheme. | 
| logical 0(false) | The software processes the data in the order received. | 
Example: Shuffle=false
Data Types: logical
Performance Metrics Options
Model performance metrics to track during incremental learning, specified as 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 Learner, support them. You can specify
                more than one loss function by using a string vector.
| Name | Description | Learner 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 - metricis 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 specify the function name ( - customMetric).
- Yis a length n numeric vector of observed responses, where n is the sample size.
- YFitis 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,@customMetric2,"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.
| MetricsValue Data Type | Description of MetricsProperty Row Name | Example | 
|---|---|---|
| String or character vector | Name of corresponding built-in metric | Row name for "epsiloninsensitive"is"EpsilonInsensitiveLoss" | 
| Structure array | Field name | Row name for struct(Metric1=@customMetric1)is"Metric1" | 
| Function handle to function stored in a program file | Name of function | Row name for @customMetricis"customMetric" | 
| Anonymous function | CustomMetric_, whereis metricinMetrics | Row name for @(Y,YFit)customMetric(Y,YFit)...isCustomMetric_1 | 
By default:
- Metricsis- "epsiloninsensitive"if- Learneris- "svm".
- Metricsis- "mse"if- Learneris- "leastsquares".
For more details on performance metrics options, see Performance Metrics.
Data Types: char | string | struct | cell | function_handle
Properties
You can set most properties by using name-value argument syntax when you call
        incrementalRegressionKernel directly. You can set some properties when you call
        incrementalLearner to convert a traditionally trained model. You cannot
      set the properties FittedLoss,
        NumTrainingObservations, SolverOptions, and
        IsWarm.
Regression Model Parameters
This property is read-only.
Half of the width of the epsilon insensitive band, specified as
                "auto" or a nonnegative scalar. incrementalRegressionKernel
              stores the Epsilon value as a numeric scalar.
If you specify "auto" when you call
                incrementalRegressionKernel, incremental fitting functions estimate
                Epsilon during the estimation period, specified by EstimationPeriod, using
              this procedure:
- If - iqr(Y)≠ 0,- Epsilonis- iqr(Y)/13.49, where- Yis the estimation period response data.
- If - iqr(Y)= 0 or before you fit- Mdlto data,- Epsilonis- 0.1.
The default Epsilon value depends on how you create the model:
- If you convert a traditionally trained model whose - Learnerproperty is- 'svm',- Epsilonis specified by the corresponding property of the traditionally trained model.
- Otherwise, the default value is - "auto".
If Learner is "leastsquares", you cannot
              set Epsilon and its value is NaN.
Data Types: single | double
This property is read-only.
Loss function used to fit the linear model, specified as
                'epsiloninsensitive' or 'mse'.
| Value | Algorithm | Loss Function | LearnerValue | 
|---|---|---|---|
| 'epsiloninsensitive' | Support vector machine regression | Epsilon insensitive: | 'svm' | 
| 'mse' | Linear regression through ordinary least squares | Mean squared error (MSE): | 'leastsquares' | 
This property is read-only.
Kernel scale parameter, specified as "auto" or a positive scalar.
                incrementalRegressionKernel stores the KernelScale value
            as a numeric scalar. The software obtains a random basis for feature expansion by using
            the kernel scale parameter. For details, see Random Feature Expansion.
If you specify "auto" when creating the model object, the software
            selects an appropriate kernel scale parameter using a heuristic procedure. This
            procedure uses subsampling, so estimates might vary from one call to another. Therefore,
            to reproduce results, set a random number seed by using rng before training.
The default KernelScale value depends on how you create the model:
- If you convert a traditionally trained model to create - Mdl,- KernelScaleis specified by the corresponding property of the traditionally trained model.
- Otherwise, the default value is - 1.
Data Types: char | string | single | double
This property is read-only.
Linear regression model type, specified as "svm" or
                "leastsquares".  incrementalRegressionKernel stores the
                Learner value as a character vector.
In the following table,
- x is an observation (row vector) from p predictor variables. 
- is a transformation of an observation (row vector) for feature expansion. T(x) maps x in to a high-dimensional space (). 
- β is a vector of coefficients. 
- b is the scalar bias. 
| Value | Algorithm | Loss Function | FittedLossValue | 
|---|---|---|---|
| "svm" | Support vector machine regression | Epsilon insensitive: | 'epsiloninsensitive' | 
| "leastsquares" | Linear regression through ordinary least squares | Mean squared error (MSE): | 'mse' | 
The default Learner value depends on how you create the model:
- If you convert a traditionally trained model to create - Mdl,- Learneris specified by the corresponding property of the traditionally trained model.
- Otherwise, the default value is - "svm".
This property is read-only.
Number of dimensions of the expanded space, specified as "auto" or
            a positive integer. incrementalRegressionKernel stores the
                NumExpansionDimensions value as a numeric scalar.
For "auto", the software selects the number of dimensions using
                2.^ceil(min(log2(p)+5,15)), where p is the
            number of predictors. For details, see Random Feature Expansion.
The default NumExpansionDimensions value depends on how you
            create the model:
- If you convert a traditionally trained model to create - Mdl,- NumExpansionDimensionsis specified by the corresponding property of the traditionally trained model.
- Otherwise, the default value is - "auto".
Data Types: char | string | single | double
This property is read-only.
Number of predictor variables, specified as a nonnegative numeric scalar.
The default NumPredictors value depends on how you create the model:
- If you convert a traditionally trained model to create - Mdl,- NumPredictorsis specified by the corresponding property of the traditionally trained model.
- If you create - Mdlby calling- incrementalRegressionKerneldirectly, you can specify- NumPredictorsby using name-value argument syntax. If you do not specify the value, then the default value is- 0, and incremental fitting functions infer- NumPredictorsfrom the predictor data during training.
Data Types: double
This property is read-only.
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, incrementalRegressionKernel does not add the number of observations fit to the traditionally trained model to NumTrainingObservations.
Data Types: double
This property is read-only.
Response transformation function, specified as "none" or a
              function handle. incrementalRegressionKernel stores the
                ResponseTransform value as a character vector or 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).
The default ResponseTransform value depends on how you create
              the model:
- If you convert a traditionally trained model to create - Mdl,- ResponseTransformis specified by the corresponding property of the traditionally trained model.
- Otherwise, the default value is - "none".
Data Types: char | string | function_handle
Training Parameters
This property is read-only.
Number of observations processed by the incremental model to estimate hyperparameters before training or tracking performance metrics, specified as a nonnegative integer.
Note
- If - Mdlis prepared for incremental learning (all hyperparameters required for training are specified),- incrementalRegressionKernelforces- EstimationPeriodto- 0.
- If - Mdlis not prepared for incremental learning,- incrementalRegressionKernelsets- EstimationPeriodto- 1000.
For more details, see Estimation Period.
Data Types: single | double
Since R2023b
This property is read-only.
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
Since R2023b
This property is read-only.
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
This property is read-only.
Objective function minimization technique, specified as "scale-invariant", "sgd", or "asgd". incrementalRegressionKernel stores the Solver value as a character vector.
| Value | Description | Notes | 
|---|---|---|
| "scale-invariant" | Adaptive scale-invariant solver for incremental learning [1] | 
 
 
 | 
| "sgd" | Stochastic gradient descent (SGD) [2][3] | 
 
 
 | 
| "asgd" | Average stochastic gradient descent (ASGD) [4] | 
 
 
 | 
The default Solver value depends on how you create the model:
- If you convert a traditionally trained model to create - Mdl, the- Solvername-value argument of the- incrementalLearnerfunction sets this property. The default value of the argument is- "scale-invariant".
- Otherwise, the default value is - "scale-invariant".
Data Types: char | string
This property is read-only.
Objective solver configurations, specified as a structure array. The fields of
                SolverOptions depend on Solver. 
- For the SGD and ASGD solvers, the structure array includes the - Solver,- BatchSize,- Lambda,- LearnRate, and- LearnRateSchedulefields.
- For the adaptive scale-invariant solver, the structure array includes the - Solverand- Shufflefields.
You can specify the field values using the corresponding name-value arguments when you
            create the model object by calling incrementalRegressionKernel directly, or when you
            convert a traditionally trained model using the incrementalLearner
            function.
Data Types: struct
Performance Metrics Parameters
This property is read-only.
Flag indicating whether the incremental model tracks performance metrics, specified as
            logical 0 (false) or 1
                (true).
The incremental model Mdl is warm
                (IsWarm becomes true) after incremental
            fitting functions fit (EstimationPeriod +
                MetricsWarmupPeriod) observations to the incremental
            model.
| Value | Description | 
|---|---|
| trueor1 | The incremental model Mdlis warm. Consequently,updateMetricsandupdateMetricsAndFittrack performance metrics
                            in theMetricsproperty ofMdl. | 
| falseor0 | updateMetricsandupdateMetricsAndFitdo not track performance
                            metrics. | 
Data Types: logical
This property is read-only.
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
            argument.
The columns of Metrics are labeled Cumulative and Window.
- Cumulative: Element- jis the model performance, as measured by metric- j, from the time the model became warm (- IsWarmis- 1).
- Window: Element- jis the model performance, as measured by metric- j, evaluated over all observations within the window specified by the- MetricsWindowSizeproperty. The software updates- Windowafter it processes- MetricsWindowSizeobservations.
Rows are labeled by the specified metrics. For details, see the
                Metrics name-value argument of
                incrementalLearner or incrementalRegressionKernel.
Data Types: table
This property is read-only.
Number of observations the incremental model must be fit to before it tracks performance metrics in its Metrics property, specified as a nonnegative integer.
The default MetricsWarmupPeriod value depends on how you create
            the model:
- If you convert a traditionally trained model to create - Mdl, the- MetricsWarmupPeriodname-value argument of the- incrementalLearnerfunction sets this property. The default value of the argument is- 0.
- Otherwise, the default value is - 1000.
For more details, see Performance Metrics.
Data Types: single | double
This property is read-only.
Number of observations to use to compute window performance metrics, specified as a positive integer.
The default MetricsWindowSize value depends on how you create the model:
- If you convert a traditionally trained model to create - Mdl, the- MetricsWindowSizename-value argument of the- incrementalLearnerfunction sets this property. The default value of the argument is- 200.
- Otherwise, the default value is - 200.
For more details on performance metrics options, see Performance Metrics.
Data Types: single | double
Object Functions
| fit | Train kernel model for incremental learning | 
| updateMetrics | Update performance metrics in kernel incremental learning model given new data | 
| updateMetricsAndFit | Update performance metrics in kernel incremental learning model given new data and train model | 
| loss | Loss of kernel incremental learning model on batch of data | 
| predict | Predict responses for new observations from kernel incremental learning model | 
| perObservationLoss | Per observation regression error of model for incremental learning | 
| reset | Reset incremental regression model | 
Examples
Create an incremental kernel model without any prior information. Track the model performance on streaming data, and fit the model to the data.
Create a default incremental kernel SVM model for regression.
Mdl = incrementalRegressionKernel()
Mdl = 
  incrementalRegressionKernel
                    IsWarm: 0
                   Metrics: [1×2 table]
         ResponseTransform: 'none'
    NumExpansionDimensions: 0
               KernelScale: 1
  Properties, Methods
Mdl.EstimationPeriod
ans = 1000
Mdl is an incrementalRegressionKernel 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 argument. This action results in a default estimation period of 0.
Load the robot arm data set.
load robotarmFor 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 observations. 
- Store the cumulative metrics, window metrics, and number of training observations 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"]); numtrainobs = zeros(nchunk+1,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",:}; numtrainobs(j+1) = Mdl.NumTrainingObservations; end
Mdl is an incrementalRegressionKernel model object trained on all the data in the stream. While updateMetricsAndFit processes the first 1000 observations, it stores the response values to estimate Epsilon; the function does not fit the model 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 observations, and then fits the model to those observations.
Plot a trace plot of the number of training observations and the performance metrics on separate tiles.
t = tiledlayout(2,1); nexttile plot(numtrainobs) xlim([0 nchunk]) ylabel("Number of Training Observations") xline(Mdl.EstimationPeriod/numObsPerChunk,"-.") xline((Mdl.EstimationPeriod + Mdl.MetricsWarmupPeriod)/numObsPerChunk,"--") nexttile plot(ei.Variables) xlim([0 nchunk]) ylabel("Epsilon Insensitive Loss") xline(Mdl.EstimationPeriod/numObsPerChunk,"-.") xline((Mdl.EstimationPeriod + Mdl.MetricsWarmupPeriod)/numObsPerChunk,"--") legend(ei.Properties.VariableNames,Location="best") xlabel(t,"Iteration")

The plot suggests that updateMetricsAndFit does the following:
- After the estimation period (first 20 iterations), fit the model during all incremental learning iterations. 
- Compute the performance metrics after the metrics warm-up period only. 
- Compute the cumulative metrics during each iteration. 
- Compute the window metrics after processing 200 observations (4 iterations). 
Prepare an incremental regression learner by specifying a metrics warm-up period and a metrics window size. 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 kernel model for regression. Configure the model as follows:
- Specify the SGD solver. 
- Assume that these settings work well for the problem: 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. 
- 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 - MeanAbsoluteErrorand its corresponding function.
maefcn = @(z,zfit)abs(z - zfit); maemetric = struct("MeanAbsoluteError",maefcn); Mdl = incrementalRegressionKernel(Solver="sgd", ... Lambda=0.001,BatchSize=20,LearnRate=0.002,Epsilon=0.05, ... MetricsWarmupPeriod=1000,MetricsWindowSize=500, ... Metrics={"epsiloninsensitive","mse",maemetric})
Mdl = 
  incrementalRegressionKernel
                    IsWarm: 0
                   Metrics: [3×2 table]
         ResponseTransform: 'none'
    NumExpansionDimensions: 0
               KernelScale: 1
  Properties, Methods
Mdl is an incrementalRegressionKernel model object configured for incremental learning without an estimation period.
Fit the incremental model to the data by using the updateMetricsAndFit function. At each iteration:
- Simulate a data stream by processing a chunk of 50 observations. Note that the chunk size is different from the SGD batch size. 
- Overwrite the previous incremental model with a new one fitted to the incoming observations. 
- Store the cumulative metrics, window metrics, and number of training observations 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"]); numtrainobs = zeros(nchunk,1); % Incremental fitting rng("default") % For reproducibility 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",:}; numtrainobs(j) = Mdl.NumTrainingObservations; end
Mdl is an incrementalRegressionKernel 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 observations, and then fits the model to those observations.
Plot a trace plot of the number of training observations and the performance metrics on separate tiles.
t = tiledlayout(4,1); nexttile plot(numtrainobs) xlim([0 nchunk]) ylabel(["Number of","Training Observations"]) xline(Mdl.MetricsWarmupPeriod/numObsPerChunk,"--") nexttile plot(ei.Variables) xlim([0 nchunk]) ylabel(["Epsilon Insensitive","Loss"]) xline(Mdl.MetricsWarmupPeriod/numObsPerChunk,"--") legend(ei.Properties.VariableNames) nexttile plot(mse.Variables) xlim([0 nchunk]) ylabel("MSE") xline(Mdl.MetricsWarmupPeriod/numObsPerChunk,"--") legend(mse.Properties.VariableNames) nexttile plot(mae.Variables) xlim([0 nchunk]) ylabel("MAE") xline(Mdl.MetricsWarmupPeriod/numObsPerChunk,"--") legend(mae.Properties.VariableNames) xlabel(t,"Iteration")

The plot suggests that updateMetricsAndFit does the following:
- Fit the model during all incremental learning iterations. 
- Compute the 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 kernel regression model by using fitrkernel, 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 and Preprocess Data
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 = [];
To reduce computational cost for this example, remove the NEIGHBORHOOD column, which contains a categorical variable with 254 categories.
NYCHousing2015.NEIGHBORHOOD = [];
Create dummy variable matrices from the other categorical predictors.
catvars = ["BOROUGH","BUILDINGCLASSCATEGORY"]; dumvarstbl = varfun(@(x)dummyvar(categorical(x)),NYCHousing2015, ... InputVariables=catvars); dumvarmat = table2array(dumvarstbl); NYCHousing2015(:,catvars) = [];
Treat all other numeric variables in the table as predictors of sales price. Concatenate the matrix of dummy variables to the rest of the predictor data.
idxnum = varfun(@isnumeric,NYCHousing2015,OutputFormat="uniform");
X = [dumvarmat NYCHousing2015{:,idxnum}];Train Kernel Regression Model
Fit a kernel regression model to a random sample of half the data. Specify the observation weights.
idxtt = randsample([true false],n,true); Mdl = fitrkernel(X(idxtt,:),Y(idxtt),Weights=NYCHousing2015.W(idxtt))
Mdl = 
  RegressionKernel
              ResponseName: 'Y'
                   Learner: 'svm'
    NumExpansionDimensions: 2048
               KernelScale: 1
                    Lambda: 2.1977e-05
             BoxConstraint: 1
                   Epsilon: 0.0547
  Properties, Methods
Mdl is a RegressionKernel model object representing a traditionally trained kernel regression model. 
Convert Trained Model
Convert the traditionally trained kernel regression model to a model for incremental learning.
IncrementalMdl = incrementalLearner(Mdl)
IncrementalMdl = 
  incrementalRegressionKernel
                    IsWarm: 1
                   Metrics: [1×2 table]
         ResponseTransform: 'none'
    NumExpansionDimensions: 2048
               KernelScale: 1
  Properties, Methods
IncrementalMdl is an incrementalRegressionKernel model object configured for incremental learning.
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:
- Call - updateMetricsto 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- Metricsproperty. Note that the function does not fit the model to the chunk of data—the chunk is "new" data for the model. Specify the observation weights.
- Call - fitto fit the model to the incoming chunk of observations. Overwrite the previous incremental model to update the model parameters. Specify the observation weights.
- Store the losses and number of training observations. 
% Preallocation idxil = ~idxtt; nil = sum(idxil); numObsPerChunk = 500; nchunk = floor(nil/numObsPerChunk); ei = array2table(zeros(nchunk,2),VariableNames=["Cumulative","Window"]); numtrainobs = 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), ... Weights=Wil(idx)); ei{j,:} = IncrementalMdl.Metrics{"EpsilonInsensitiveLoss",:}; IncrementalMdl = fit(IncrementalMdl,Xil(idx,:),Yil(idx), ... Weights=Wil(idx)); numtrainobs(j) = IncrementalMdl.NumTrainingObservations; end
IncrementalMdl is an incrementalRegressionKernel 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 number of training observations and the performance metrics on separate tiles.
t = tiledlayout(2,1); nexttile plot(numtrainobs) xlim([0 nchunk]) ylabel("Number of Training Observations") nexttile plot(ei.Variables) xlim([0 nchunk]) ylabel("Epsilon Insensitive Loss") legend(ei.Properties.VariableNames) xlabel(t,"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.
More About
Incremental learning, or online learning, is a branch of machine learning concerned with processing incoming data from a data stream, possibly given little to no knowledge of the distribution of the predictor variables, aspects of the prediction or objective function (including tuning parameter values), or whether the observations are labeled. Incremental learning differs from traditional machine learning, where enough labeled data is available to fit to a model, perform cross-validation to tune hyperparameters, and infer the predictor distribution.
Given incoming observations, an incremental learning model processes data in any of the following ways, but usually in this order:
- Predict labels. 
- Measure the predictive performance. 
- Check for structural breaks or drift in the model. 
- Fit the model to the incoming observations. 
For more details, see Incremental Learning Overview.
The adaptive scale-invariant solver for incremental learning, introduced in [1], is a gradient-descent-based objective solver for training linear predictive models. The solver is hyperparameter free, insensitive to differences in predictor variable scales, and does not require prior knowledge of the distribution of the predictor variables. These characteristics make it well suited to incremental learning.
The standard SGD and ASGD solvers are sensitive to differing scales among the predictor variables, resulting in models that can perform poorly. To achieve better accuracy using SGD and ASGD, you can standardize the predictor data, and tune the regularization and learning rate parameters. For traditional machine learning, enough data is available to enable hyperparameter tuning by cross-validation and predictor standardization. However, for incremental learning, enough data might not be available (for example, observations might be available only one at a time) and the distribution of the predictors might be unknown. These characteristics make parameter tuning and predictor standardization difficult or impossible to do during incremental learning.
The incremental fitting functions fit and
            updateMetricsAndFit use the more aggressive ScInOL2 version of the
        algorithm.
Random feature expansion, such as Random Kitchen Sinks [1] or Fastfood [2], is a scheme to approximate Gaussian kernels of the kernel regression algorithm for big data in a computationally efficient way. Random feature expansion is more practical for big data applications that have large training sets, but can also be applied to smaller data sets that fit in memory.
After mapping the predictor data into a high-dimensional space, the kernel regression algorithm searches for an optimal function that deviates from each response data point (yi) by values no greater than the epsilon margin (ε).
Some regression problems cannot be described adequately using a linear model. In such cases, obtain a nonlinear regression model by replacing the dot product x1x2′ with a nonlinear kernel function , where xi is the ith observation (row vector) and φ(xi) is a transformation that maps xi to a high-dimensional space (called the “kernel trick”). However, evaluating G(x1,x2), the Gram matrix, for each pair of observations is computationally expensive for a large data set (large n).
The random feature expansion scheme finds a random transformation so that its dot product approximates the Gaussian kernel. That is,
where T(x) maps x in to a high-dimensional space (). The Random Kitchen Sinks [1] scheme uses the random transformation
where  is a sample drawn from  and σ is a kernel scale. This scheme requires O(mp) computation and storage. The Fastfood [2] scheme introduces
        another random basis V instead of Z using Hadamard
        matrices combined with Gaussian scaling matrices. This random basis reduces computation cost
        to O(mlogp) and reduces storage to O(m).
incrementalRegressionKernel uses the Fastfood
    scheme for random feature expansion, and uses linear regression to train a Gaussian kernel
    regression model. You can specify values for m and σ using
    the NumExpansionDimensions and KernelScale name-value
    arguments, respectively, when you create a traditionally trained model using fitrkernel or when
    you call incrementalRegressionKernel directly to create the model
    object.
Algorithms
During the estimation period, the incremental fitting functions fit and updateMetricsAndFit use the
        first incoming EstimationPeriod observations
        to estimate (tune) hyperparameters required for incremental training. Estimation occurs only
        when EstimationPeriod is positive. This table describes the
        hyperparameters and when they are estimated, or tuned.
| Hyperparameter | Model Property | Usage | Conditions | 
|---|---|---|---|
| Predictor means and standard deviations | 
 | Standardize predictor data | The hyperparameters are estimated when both of these conditions apply: 
 
 | 
| Learning rate | LearnRatefield ofSolverOptions | Adjust the solver step size | The hyperparameter is estimated when both of these conditions apply: 
 | 
| Half the width of the epsilon insensitive band | Epsilon | Control the number of support vectors | The hyperparameter is estimated when all of these conditions apply: 
 | 
| Kernel scale parameter | KernelScale | Set a kernel scale parameter value for random feature expansion | The hyperparameter is estimated when you set the KernelScalename-value argument to"auto". | 
During the estimation period, fit does not fit the model, and updateMetricsAndFit does not fit the model or update the performance metrics. At the end of the estimation period, the functions update the properties that store the hyperparameters.
If incremental learning functions are configured to standardize predictor variables,
        they do so using the means and standard deviations stored in the Mu and
          Sigma properties, respectively, of the incremental learning model
          Mdl.
- When you set - Standardize=trueand specify a positive estimation period (see- EstimationPeriod), and- Mdl.Muand- Mdl.Sigmaare empty, incremental fitting functions estimate means and standard deviations using the estimation period observations.
- When you set - Standardize="auto"(the default), the following conditions apply:- If you create - incrementalRegressionKernelby converting a traditionally trained kernel regression model (- RegressionKernel), and the- Muand- Sigmaproperties of the model being converted are empty arrays- [], incremental learning functions do not standardize predictor variables. If the- Muand- Sigmaproperties of the model being converted are nonempty, incremental learning functions standardize the predictor variables using the specified means and standard deviations. Incremental fitting functions do not estimate new means and standard deviations, regardless of the length of the estimation period.
- If you do not convert a traditionally trained model, incremental learning functions standardize the predictor data only when you specify an SGD solver (see - Solver) and a positive estimation period (see- EstimationPeriod).
 
- When incremental fitting functions estimate predictor means and standard deviations, the functions compute weighted means and weighted standard deviations using the estimation period observations. Specifically, the functions standardize predictor j (xj) using - xj is predictor j, and xjk is observation k of predictor j in the estimation period. 
- wj is observation weight j. 
 
- The - updateMetricsand- updateMetricsAndFitfunctions are incremental learning functions that track model performance metrics (- Metrics) from new data only when the incremental model is warm (- IsWarmproperty is- true). An incremental model becomes warm after- fitor- updateMetricsAndFitfits the incremental model to- MetricsWarmupPeriodobservations, which is the metrics warm-up period.- If - EstimationPeriod> 0, the- fitand- updateMetricsAndFitfunctions estimate hyperparameters before fitting the model to data. Therefore, the functions must process an additional- EstimationPeriodobservations before the model starts the metrics warm-up period.
- The - Metricsproperty of the incremental model stores two forms of each performance metric as variables (columns) of a table,- Cumulativeand- Window, with individual metrics in rows. When the incremental model is warm,- updateMetricsand- updateMetricsAndFitupdate 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- MetricsWindowSize, which also determines the frequency at which the software updates- Windowmetrics. For example, if- MetricsWindowSizeis 20, the functions compute metrics based on the last 20 observations in the supplied data (- X((end – 20 + 1):end,:)and- Y((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 the - Windowfield of the- Metricsproperty with the weighted average performance in the metrics window. If the buffer overfills when the function processes a batch of observations, the latest incoming- MetricsWindowSizeobservations enter the buffer, and the earliest observations are removed from the buffer. For example, suppose- MetricsWindowSizeis 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 software omits an observation with a - NaNprediction when computing the- Cumulativeand- Windowperformance metric values.
References
[1] Kempka, Michał, Wojciech Kotłowski, and Manfred K. Warmuth. "Adaptive Scale-Invariant Online Algorithms for Learning Linear Models." Preprint, submitted February 10, 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.
[5] Rahimi, A., and B. Recht. “Random Features for Large-Scale Kernel Machines.” Advances in Neural Information Processing Systems. Vol. 20, 2008, pp. 1177–1184.
[6] Le, Q., T. Sarlós, and A. Smola. “Fastfood — Approximating Kernel Expansions in Loglinear Time.” Proceedings of the 30th International Conference on Machine Learning. Vol. 28, No. 3, 2013, pp. 244–252.
[7] Huang, P. S., H. Avron, T. N. Sainath, V. Sindhwani, and B. Ramabhadran. “Kernel methods match Deep Neural Networks on TIMIT.” 2014 IEEE International Conference on Acoustics, Speech and Signal Processing. 2014, pp. 205–209.
Version History
Introduced in R2022aincrementalRegressionKernel supports the standardization of numeric predictors. That is, you can specify the Standardize value as true to center and scale each numeric predictor variable by the corresponding column mean and standard deviation. The software does not standardize the categorical predictors.
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.
Seleccione un país/idioma
Seleccione un país/idioma para obtener contenido traducido, si está disponible, y ver eventos y ofertas de productos y servicios locales. Según su ubicación geográfica, recomendamos que seleccione: .
También puede seleccionar uno de estos países/idiomas:
Cómo obtener el mejor rendimiento
Seleccione China (en idioma chino o inglés) para obtener el mejor rendimiento. Los sitios web de otros países no están optimizados para ser accedidos desde su ubicación geográfica.
América
- América Latina (Español)
- Canada (English)
- United States (English)
Europa
- 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)