Main Content

incrementalClassificationKernel

Binary classification kernel model for incremental learning

Since R2022a

    Description

    The incrementalClassificationKernel function creates an incrementalClassificationKernel model object, which represents a binary Gaussian kernel classification 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 logistic regression.

    Unlike other Statistics and Machine Learning Toolbox™ model objects, incrementalClassificationKernel 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 incrementalClassificationKernel object, it is prepared for incremental learning.

    incrementalClassificationKernel is best suited for incremental learning. For a traditional approach to training a kernel model for binary classification (such as creating a model by fitting it to data, performing cross-validation, tuning hyperparameters, and so on), see fitckernel. For multiclass incremental learning, see incrementalClassificationECOC and incrementalClassificationNaiveBayes.

    Creation

    You can create an incrementalClassificationKernel model object in several ways:

    • Call the function directly — Configure incremental learning options, or specify learner-specific options, by calling incrementalClassificationKernel 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 a model for incremental learning using the model parameters and hyperparameters of a trained model object, you can convert the traditionally trained model (ClassificationKernel) to an incrementalClassificationKernel model object by passing it to the incrementalLearner function.

    • Convert a template object — You can convert a template object (templateKernel) to an incrementalClassificationKernel model object by passing it to the incrementalLearner function.

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

    Description

    example

    Mdl = incrementalClassificationKernel() returns a default incremental learning model object for binary Gaussian kernel classification, 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 = incrementalClassificationKernel(Name=Value) sets properties and additional options using name-value arguments. For example, incrementalClassificationKernel(Solver="sgd",LearnRateSchedule="constant") specifies to use the stochastic gradient descent (SGD) solver with a constant learning rate.

    Input Arguments

    expand all

    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="logit",MetricsWarmupPeriod=100 sets the model performance metric to the logistic loss and the metrics warm-up period to 100.

    Classification Options

    expand all

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

    ValueDescription
    "auto"incrementalClassificationKernel 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

    SGD and ASGD (Average SGD) Solver Options

    expand all

    Mini-batch size, specified as a positive integer. At each learning cycle during training, incrementalClassificationKernel 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, fit and updateMetricsAndFit change 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.

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

    The learning rate at learning cycle t is

    γt=γ0(1+λγ0t)c.

    • λ is the value of Lambda.

    • If Solver is "sgd", then c = 1.

    • If Solver is "asgd", then c = 0.75 [4].

    Example: LearnRateSchedule="constant"

    Data Types: char | string

    Adaptive Scale-Invariant Solver Options

    expand all

    Flag for shuffling the observations at each iteration, specified as logical 1 (true) or 0 (false).

    ValueDescription
    logical 1 (true)The software shuffles the observations in an incoming chunk of data before the fit function 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

    expand all

    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. You can specify more than one by using a string vector.

    NameDescription
    "binodeviance"Binomial deviance
    "classiferror"Classification error
    "exponential"Exponential loss
    "hinge"Hinge loss
    "logit"Logistic loss
    "quadratic"Quadratic loss

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

    Example: Metrics=["classiferror","hinge"]

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

    metric = customMetric(C,S)

    • 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 specify the function name (customMetric).

    • C is an n-by-2 logical matrix with rows indicating the class to which the corresponding observation belongs. The column order corresponds to the class order in the ClassNames property. Create C by setting C(p,q) = 1, if observation p is in class q, for each observation in the specified data. Set the other element in row p to 0.

    • S is an n-by-2 numeric matrix of predicted classification scores. S is similar to the score output of predict, where rows correspond to observations in the data and the column order corresponds to the class order in the ClassNames property. S(p,q) is the classification score of observation p being classified in class q.

    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,"logit",struct(Metric3=@customMetric3)}

    updateMetrics and updateMetricsAndFit store specified metrics in a table in the Metrics property. 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 "classiferror" is "ClassificationError"
    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 @(C,S)customMetric(C,S)... is CustomMetric_1

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

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

    Properties

    expand all

    You can set most properties by using name-value argument syntax when you call incrementalClassificationKernel directly. You can set some properties when you call incrementalLearner to convert a traditionally trained model object or model template object. You cannot set the properties FittedLoss, NumTrainingObservations, SolverOptions, and IsWarm.

    Classification Model Parameters

    This property is read-only.

    Unique class labels used in training the model, specified as a categorical, character, or string array, a logical or numeric vector, or a cell array of character vectors. ClassNames and the response data must have the same data type. (The software treats string arrays as cell arrays of character vectors.)

    The default ClassNames value depends on how you create the model:

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

    • Otherwise, incremental fitting functions infer ClassNames during training.

    Data Types: single | double | logical | char | string | cell | categorical

    This property is read-only.

    Loss function used to fit the linear model, specified as 'hinge' or 'logit'.

    ValueAlgorithmLoss FunctionLearner Value
    'hinge'Support vector machineHinge: [y,f(x)]=max[0,1yf(x)]'svm'
    'logit'Logistic regressionDeviance (logistic): [y,f(x)]=log{1+exp[yf(x)]}'logistic'

    This property is read-only.

    Kernel scale parameter, specified as "auto" or a positive scalar. incrementalClassificationKernel 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 can 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 object or template model object to create Mdl, KernelScale is specified by the corresponding property of the object.

    • Otherwise, the default value is 1.

    Data Types: char | string | single | double

    This property is read-only.

    Linear classification model type, specified as "svm" or "logistic". incrementalClassificationKernel stores the Learner value as a character vector.

    In the following table, f(x)=T(x)β+b.

    • x is an observation (row vector) from p predictor variables.

    • T(·) is a transformation of an observation (row vector) for feature expansion. T(x) maps x in p to a high-dimensional space (m).

    • β is a vector of coefficients.

    • b is the scalar bias.

    ValueAlgorithmLoss FunctionFittedLoss Value
    "svm"Support vector machineHinge loss: [y,f(x)]=max[0,1yf(x)]'hinge'
    "logistic"Logistic regressionDeviance (logistic loss): [y,f(x)]=log{1+exp[yf(x)]}'logit'

    The default Learner value depends on how you create the model:

    • If you convert a traditionally trained model object or template model object to create Mdl, Learner is specified by the corresponding property of the object.

    • Otherwise, the default value is "svm".

    Data Types: char | string

    This property is read-only.

    Number of dimensions of the expanded space, specified as "auto" or a positive integer. incrementalClassificationKernel 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 object or template model object to create Mdl, NumExpansionDimensions is specified by the corresponding property of the object.

    • 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, NumPredictors is specified by the corresponding property of the traditionally trained model.

    • If you create Mdl by calling incrementalClassificationKernel directly, you can specify NumPredictors by using name-value argument syntax.

    • Otherwise, the default value is 0, and incremental fitting functions infer NumPredictors from 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, incrementalClassificationKernel does not add the number of observations fit to the traditionally trained model to NumTrainingObservations.

    Data Types: double

    This property is read-only.

    Prior class probabilities, specified as "empirical", "uniform", or a numeric vector. incrementalClassificationKernel stores the Prior value as a numeric vector.

    ValueDescription
    "empirical"Incremental learning functions infer prior class probabilities from the observed class relative frequencies in the response data during incremental training (after the estimation period EstimationPeriod).
    "uniform"For each class, the prior probability is 1/2.
    numeric vectorCustom, normalized prior probabilities. The order of the elements of Prior corresponds to the elements of the ClassNames property.

    The default Prior value depends on how you create the model:

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

    • Otherwise, the default value is "empirical".

    Data Types: single | double | char | string

    This property is read-only.

    Score transformation function describing how incremental learning functions transform raw response values, specified as a character vector, string scalar, or function handle. incrementalClassificationKernel stores the ScoreTransform value as a character vector or function handle.

    This table describes the available built-in functions for score transformation.

    ValueDescription
    "doublelogit"1/(1 + e–2x)
    "invlogit"log(x / (1 – x))
    "ismax"Sets the score for the class with the largest score to 1, and sets the scores for all other classes to 0
    "logit"1/(1 + ex)
    "none" or "identity"x (no transformation)
    "sign"–1 for x < 0
    0 for x = 0
    1 for x > 0
    "symmetric"2x – 1
    "symmetricismax"Sets the score for the class with the largest score to 1, and sets the scores for all other classes to –1
    "symmetriclogit"2/(1 + ex) – 1

    For a MATLAB® function or a function that you define, enter its function handle; for example, ScoreTransform=@function, where:

    • function accepts an n-by-2 matrix (the original scores) and returns a matrix of the same size (the transformed scores). The column order corresponds to the class order in the ClassNames property.

    • n is the number of observations, and row j of the matrix contains the class scores of observation j.

    The default ScoreTransform value depends on how you create the model:

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

    • Otherwise, the default value is "none" (when Learner is "svm") or "logit" (when Learner is "logistic").

    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 Mdl is prepared for incremental learning (all hyperparameters required for training are specified), incrementalClassificationKernel forces EstimationPeriod to 0.

    • If Mdl is not prepared for incremental learning, incrementalClassificationKernel sets EstimationPeriod to 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". incrementalClassificationKernel stores the Solver value as a character vector.

    ValueDescriptionNotes
    "scale-invariant"

    Adaptive scale-invariant solver for incremental learning [1]

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

    • To shuffle an incoming chunk of data before the fit function fits the model, set Shuffle to true.

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

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

    • The fit function always shuffles an incoming chunk 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 (Average SGD) Solver Options.

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

    The default Solver value depends on how you create the model:

    • If you convert a traditionally trained model to create Mdl, the Solver name-value argument of the incrementalLearner function 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.

    You can specify the field values using the corresponding name-value arguments when you create the model object by calling incrementalClassificationKernel 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.

    ValueDescription
    true or 1The incremental model Mdl is warm. Consequently, updateMetrics and updateMetricsAndFit track performance metrics in the Metrics property of Mdl.
    false or 0updateMetrics and updateMetricsAndFit do 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 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 the Metrics name-value argument of incrementalLearner or incrementalClassificationKernel.

    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 MetricsWarmupPeriod name-value argument of the incrementalLearner function 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 MetricsWindowSize name-value argument of the incrementalLearner function 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

    fitTrain kernel model for incremental learning
    updateMetricsUpdate performance metrics in kernel incremental learning model given new data
    updateMetricsAndFitUpdate performance metrics in kernel incremental learning model given new data and train model
    lossLoss of kernel incremental learning model on batch of data
    predictPredict responses for new observations from kernel incremental learning model
    perObservationLossPer observation classification error of model for incremental learning
    resetReset incremental classification model

    Examples

    collapse all

    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 binary classification.

    Mdl = incrementalClassificationKernel()
    Mdl = 
      incrementalClassificationKernel
    
                        IsWarm: 0
                       Metrics: [1x2 table]
                    ClassNames: [1x0 double]
                ScoreTransform: 'none'
        NumExpansionDimensions: 0
                   KernelScale: 1
    
    
    

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

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

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

    Responses can be one of five classes: Sitting, Standing, Walking, Running, or Dancing. Dichotomize the response by identifying whether the subject is moving (actid > 2).

    Y = Y > 2;

    Fit the incremental model to the training data by using the updateMetricsAndFit function. Simulate a data stream by processing 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
    numObsPerChunk = 50;
    nchunk = floor(n/numObsPerChunk);
    ce = array2table(zeros(nchunk,2),VariableNames=["Cumulative","Window"]);    
    numtrainobs = zeros(nchunk,1);
    
    % Incremental learning
    for j = 1:nchunk
        ibegin = min(n,numObsPerChunk*(j-1) + 1);
        iend   = min(n,numObsPerChunk*j);
        idx = ibegin:iend;    
        Mdl = updateMetricsAndFit(Mdl,X(idx,:),Y(idx));
        ce{j,:} = Mdl.Metrics{"ClassificationError",:};
        numtrainobs(j) = Mdl.NumTrainingObservations;
    end

    Mdl is an incrementalClassificationKernel 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(2,1);
    nexttile
    plot(numtrainobs)
    xline(Mdl.MetricsWarmupPeriod/numObsPerChunk,"--")
    xlim([0 nchunk])
    ylabel("Number of Training Observations")
    nexttile
    plot(ce.Variables)
    xline(Mdl.MetricsWarmupPeriod/numObsPerChunk,"--")
    xlim([0 nchunk])
    ylabel("Classification Error")
    legend(ce.Properties.VariableNames,Location="best")
    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 200 observations (4 iterations).

    Prepare an incremental kernel SVM 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 human activity data set. Randomly shuffle the data.

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

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

    Responses can be one of five classes: Sitting, Standing, Walking, Running, or Dancing. Dichotomize the response by identifying whether the subject is moving (actid > 2).

    Y = Y > 2;

    Create an incremental kernel model for binary classification. Configure the model as follows:

    • Specify the SGD solver.

    • Assume that a ridge regularization parameter value of 0.001, SGD batch size of 20, and learning rate of 0.002 work well for the problem.

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

    • Specify a metrics window size of 500 observations.

    • Track the classification and hinge error metrics to measure the performance of the model.

    Mdl = incrementalClassificationKernel( ...
        Solver="sgd",Lambda=0.001,BatchSize=20,LearnRate=0.002, ...
        MetricsWarmupPeriod=5000,MetricsWindowSize=500, ...
        Metrics=["classiferror","hinge"])
    Mdl = 
      incrementalClassificationKernel
    
                        IsWarm: 0
                       Metrics: [2x2 table]
                    ClassNames: [1x0 double]
                ScoreTransform: 'none'
        NumExpansionDimensions: 0
                   KernelScale: 1
    
    
    

    Mdl is an incrementalClassificationKernel model object configured for incremental learning.

    Fit the incremental model to the rest of 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);
    ce = array2table(zeros(nchunk,2),VariableNames=["Cumulative","Window"]);
    hinge = array2table(zeros(nchunk,2),VariableNames=["Cumulative","Window"]);
    numtrainobs = 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,X(idx,:),Y(idx));
        ce{j,:} = Mdl.Metrics{"ClassificationError",:};
        hinge{j,:} = Mdl.Metrics{"HingeLoss",:};
        numtrainobs(j) = Mdl.NumTrainingObservations;
    end

    Mdl is an incrementalClassificationKernel 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(3,1);
    nexttile
    plot(numtrainobs)
    xlim([0 nchunk])
    ylabel(["Number of","Training Observations"])
    xline(Mdl.MetricsWarmupPeriod/numObsPerChunk,"--")
    nexttile
    plot(ce.Variables)
    xlim([0 nchunk])
    ylabel("Classification Error")
    xline(Mdl.MetricsWarmupPeriod/numObsPerChunk,"--")
    legend(ce.Properties.VariableNames,Location="best")
    nexttile
    plot(hinge.Variables)
    xlim([0 nchunk])
    ylabel("Hinge Loss")
    xline(Mdl.MetricsWarmupPeriod/numObsPerChunk,"--")
    legend(hinge.Properties.VariableNames,Location="best")
    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 model for binary classification by using fitckernel, 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 human activity data set. Randomly shuffle the data.

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

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

    Responses can be one of five classes: Sitting, Standing, Walking, Running, or Dancing. Dichotomize the response by identifying whether the subject is moving (actid > 2).

    Y = Y > 2;

    Suppose that the data collected when the subject was stationary (Y = false) has double the quality than when the subject was moving. Create a weight variable that attributes 2 to observations collected from a stationary subject, and 1 to a moving subject.

    W = ones(n,1) + ~Y;

    Train Kernel Model for Binary Classification

    Fit a kernel model for binary classification to a random sample of half the data.

    idxtt = randsample([true false],n,true);
    Mdl = fitckernel(X(idxtt,:),Y(idxtt),Weights=W(idxtt))
    Mdl = 
      ClassificationKernel
                  ResponseName: 'Y'
                    ClassNames: [0 1]
                       Learner: 'svm'
        NumExpansionDimensions: 2048
                   KernelScale: 1
                        Lambda: 8.2967e-05
                 BoxConstraint: 1
    
    
    

    Mdl is a ClassificationKernel model object representing a traditionally trained kernel model for binary classification.

    Convert Trained Model

    Convert the traditionally trained classification model to a model for incremental learning.

    IncrementalMdl = incrementalLearner(Mdl)
    IncrementalMdl = 
      incrementalClassificationKernel
    
                        IsWarm: 1
                       Metrics: [1x2 table]
                    ClassNames: [0 1]
                ScoreTransform: 'none'
        NumExpansionDimensions: 2048
                   KernelScale: 1
    
    
    

    IncrementalMdl is an incrementalClassificationKernel 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 50 observations at a time. At each iteration:

    1. Call updateMetrics to update the cumulative and window classification error of the model given the incoming chunk of observations. Overwrite the previous incremental model to update the Metrics property. Note that the function does not fit the model to the chunk of data—the chunk is "new" data for the model. 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 the observation weights.

    3. Store the classification error and number of training observations.

    % Preallocation
    idxil = ~idxtt;
    nil = sum(idxil);
    numObsPerChunk = 50;
    nchunk = floor(nil/numObsPerChunk);
    ce = array2table(zeros(nchunk,2),VariableNames=["Cumulative","Window"]);
    numtrainobs = zeros(nchunk,1);
    Xil = X(idxil,:);
    Yil = Y(idxil);
    Wil = W(idxil);
    
    % Incremental fitting
    for j = 1:nchunk
        ibegin = min(nil,numObsPerChunk*(j-1) + 1);
        iend   = min(nil,numObsPerChunk*j);
        idx = ibegin:iend;
        IncrementalMdl = updateMetrics(IncrementalMdl,Xil(idx,:),Yil(idx), ...
            Weights=Wil(idx));
        ce{j,:} = IncrementalMdl.Metrics{"ClassificationError",:};
        IncrementalMdl = fit(IncrementalMdl,Xil(idx,:),Yil(idx), ...
            Weights=Wil(idx));
        numtrainobs(j) = IncrementalMdl.NumTrainingObservations;
    end

    IncrementalMdl is an incrementalClassificationKernel 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.

    t = tiledlayout(2,1);
    nexttile
    plot(numtrainobs)
    xlim([0 nchunk])
    ylabel("Number of Training Observations")
    nexttile
    plot(ce.Variables)
    xlim([0 nchunk])
    legend(ce.Properties.VariableNames)
    ylabel("Classification Error")
    xlabel(t,"Iteration")

    The cumulative loss is stable and decreases gradually, whereas the window loss jumps.

    More About

    expand all

    Algorithms

    expand all

    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 R2022a

    expand all