Fit Gaussian kernel regression model using random feature expansion
fitrkernel
trains or crossvalidates a Gaussian kernel
regression model for nonlinear regression. fitrkernel
is more
practical to use for big data applications that have large training sets, but can also
be applied to smaller data sets that fit in memory.
fitrkernel
maps data in a lowdimensional space into a
highdimensional space, then fits a linear model in the highdimensional space by
minimizing the regularized objective function. Obtaining the linear model in the
highdimensional space is equivalent to applying the Gaussian kernel to the model in the
lowdimensional space. Available linear regression models include regularized support
vector machine (SVM) and leastsquares regression models.
To train a nonlinear SVM regression model on inmemory data, see fitrsvm
.
returns a kernel regression model Mdl
= fitrkernel(Tbl
,ResponseVarName
)Mdl
trained using the
predictor variables contained in the table Tbl
and the
response values in Tbl.ResponseVarName
.
specifies options using one or more namevalue pair arguments in addition to any
of the input argument combinations in previous syntaxes. For example, you can
implement leastsquares regression, specify the number of dimension of the
expanded space, or specify crossvalidation options.Mdl
= fitrkernel(___,Name,Value
)
[
also returns the hyperparameter optimization results when you optimize
hyperparameters by using the Mdl
,FitInfo
,HyperparameterOptimizationResults
] = fitrkernel(___)'OptimizeHyperparameters'
namevalue pair argument.
Train a kernel regression model for a tall array by using SVM.
When you perform calculations on tall arrays, MATLAB® uses either a parallel pool (default if you have Parallel Computing Toolbox™) or the local MATLAB session. To run the example using the local MATLAB session when you have Parallel Computing Toolbox, change the global execution environment by using the mapreducer
function.
mapreducer(0)
Create a datastore that references the folder location with the data. The data can be contained in a single file, a collection of files, or an entire folder. Treat 'NA'
values as missing data so that datastore
replaces them with NaN
values. Select a subset of the variables to use. Create a tall table on top of the datastore.
varnames = {'ArrTime','DepTime','ActualElapsedTime'}; ds = datastore('airlinesmall.csv','TreatAsMissing','NA',... 'SelectedVariableNames',varnames); t = tall(ds);
Specify DepTime
and ArrTime
as the predictor variables (X
) and ActualElapsedTime
as the response variable (Y
). Select the observations for which ArrTime
is later than DepTime
.
daytime = t.ArrTime>t.DepTime; Y = t.ActualElapsedTime(daytime); % Response data X = t{daytime,{'DepTime' 'ArrTime'}}; % Predictor data
Standardize the predictor variables.
Z = zscore(X); % Standardize the data
Train a default Gaussian kernel regression model with the standardized predictors. Extract a fit summary to determine how well the optimization algorithm fits the model to the data.
[Mdl,FitInfo] = fitrkernel(Z,Y)
Found 6 chunks. =========================================================================  Solver  Iteration /  Objective  Gradient  Beta relative    Data Pass   magnitude  change  =========================================================================  INIT  0 / 1  4.313465e+01  6.296907e02  NaN   LBFGS  0 / 2  3.704335e+01  1.789316e02  9.985854e01   LBFGS  1 / 3  3.703211e+01  2.880402e02  1.044172e03   LBFGS  2 / 4  3.701616e+01  2.297788e02  5.115891e04   LBFGS  2 / 5  3.700183e+01  1.750937e02  1.023672e03   LBFGS  3 / 6  3.679055e+01  4.815047e02  1.113182e02   LBFGS  4 / 7  3.637852e+01  1.058657e01  2.994089e02   LBFGS  5 / 8  3.565372e+01  1.406536e01  7.033477e02   LBFGS  6 / 9  3.478061e+01  1.479288e01  1.185262e01   LBFGS  7 / 10  3.616955e+01  1.544917e01  2.790848e01   LBFGS  7 / 11  3.459534e+01  1.212256e01  1.229242e01   LBFGS  8 / 12  3.379859e+01  8.791025e02  5.417481e02   LBFGS  9 / 13  3.339981e+01  3.077806e02  4.638645e02   LBFGS  10 / 14  3.325224e+01  3.082755e02  2.867793e02   LBFGS  11 / 15  3.320036e+01  4.168377e02  9.376887e03   LBFGS  12 / 16  3.309321e+01  5.018195e02  1.831484e02   LBFGS  13 / 17  3.288069e+01  4.506485e02  3.732443e02   LBFGS  14 / 18  3.245691e+01  3.787163e02  1.036929e01   LBFGS  15 / 19  3.210116e+01  2.418833e02  1.190984e01   LBFGS  16 / 20  3.190585e+01  2.666398e02  3.921991e02  =========================================================================  Solver  Iteration /  Objective  Gradient  Beta relative    Data Pass   magnitude  change  =========================================================================  LBFGS  17 / 21  3.172622e+01  2.548259e02  3.805655e02   LBFGS  18 / 22  3.154538e+01  1.280266e02  4.363429e02   LBFGS  19 / 23  3.138533e+01  1.446779e02  8.822868e02   LBFGS  20 / 24  3.283513e+01  2.218528e01  1.318597e01   LBFGS  20 / 25  3.158782e+01  1.019184e01  6.992082e02   LBFGS  20 / 26  3.136869e+01  4.678412e02  3.603399e02  ========================================================================
Mdl = RegressionKernel PredictorNames: {'x1' 'x2'} ResponseName: 'Y' Learner: 'svm' NumExpansionDimensions: 64 KernelScale: 1 Lambda: 8.5385e06 BoxConstraint: 1 Epsilon: 5.9303 Properties, Methods
FitInfo = struct with fields:
Solver: 'LBFGStall'
LossFunction: 'epsiloninsensitive'
Lambda: 8.5385e06
BetaTolerance: 1.0000e03
GradientTolerance: 1.0000e05
ObjectiveValue: 31.3687
GradientMagnitude: 0.0468
RelativeChangeInBeta: 0.0360
FitTime: 77.2197
History: [1x1 struct]
Mdl
is a RegressionKernel
model. To inspect the regression error, you can pass Mdl
and the training data or new data to the loss
function. Or, you can pass Mdl
and new predictor data to the predict
function to predict responses for new observations. You can also pass Mdl
and the training data to the resume
function to continue training.
FitInfo
is a structure array containing optimization information. Use FitInfo
to determine whether optimization termination measurements are satisfactory.
For improved accuracy, you can increase the maximum number of optimization iterations ('IterationLimit'
) and decrease the tolerance values ('BetaTolerance'
and 'GradientTolerance'
) by using the namevalue pair arguments of fitrkernel
. Doing so can improve measures like ObjectiveValue
and RelativeChangeInBeta
in FitInfo
. You can also optimize model parameters by using the 'OptimizeHyperparameters'
namevalue pair argument.
Load the carbig
data set.
load carbig
Specify the predictor variables (X
) and the response variable (Y
).
X = [Acceleration,Cylinders,Displacement,Horsepower,Weight]; Y = MPG;
Delete rows of X
and Y
where either array has NaN
values. Removing rows with NaN
values before passing data to fitrkernel
can speed up training and reduce memory usage.
R = rmmissing([X Y]); % Data with missing entries removed
X = R(:,1:5);
Y = R(:,end);
Standardize the predictor variables.
Z = zscore(X);
Crossvalidate a kernel regression model using 5fold crossvalidation.
Mdl = fitrkernel(Z,Y,'Kfold',5)
Mdl = RegressionPartitionedKernel CrossValidatedModel: 'Kernel' ResponseName: 'Y' NumObservations: 392 KFold: 5 Partition: [1x1 cvpartition] ResponseTransform: 'none' Properties, Methods
numel(Mdl.Trained)
ans = 5
Mdl
is a RegressionPartitionedKernel
model. Because fitrkernel
implements fivefold crossvalidation, Mdl
contains five RegressionKernel
models that the software trains on trainingfold (infold) observations.
Examine the crossvalidation loss (mean squared error) for each fold.
kfoldLoss(Mdl,'mode','individual')
ans = 5×1
13.0610
14.0975
24.0104
21.1223
24.3979
Optimize hyperparameters automatically using the 'OptimizeHyperparameters'
namevalue pair argument.
Load the carbig
data set.
load carbig
Specify the predictor variables (X
) and the response variable (Y
).
X = [Acceleration,Cylinders,Displacement,Horsepower,Weight]; Y = MPG;
Delete rows of X
and Y
where either array has NaN
values. Removing rows with NaN
values before passing data to fitrkernel
can speed up training and reduce memory usage.
R = rmmissing([X Y]); % Data with missing entries removed
X = R(:,1:5);
Y = R(:,end);
Standardize the predictor variables.
Z = zscore(X);
Find hyperparameters that minimize fivefold crossvalidation loss by using automatic hyperparameter optimization. Specify 'OptimizeHyperparameters'
as 'auto'
so that fitrkernel
finds the optimal values of the 'KernelScale'
, 'Lambda'
, and 'Epsilon'
namevalue pair arguments. For reproducibility, set the random seed and use the 'expectedimprovementplus'
acquisition function.
rng('default') [Mdl,FitInfo,HyperparameterOptimizationResults] = fitrkernel(Z,Y,'OptimizeHyperparameters','auto',... 'HyperparameterOptimizationOptions',struct('AcquisitionFunctionName','expectedimprovementplus'))
====================================================================================================================  Iter  Eval  Objective:  Objective  BestSoFar  BestSoFar  KernelScale  Lambda  Epsilon    result  log(1+loss)  runtime  (observed)  (estim.)     ====================================================================================================================  1  Best  4.8295  4.6067  4.8295  4.8295  0.011518  6.8068e05  0.95918 
 2  Best  4.1488  0.50472  4.1488  4.1855  477.57  0.066115  0.091828 
 3  Accept  4.1521  0.29307  4.1488  4.1747  0.0080478  0.0052867  520.84 
 4  Accept  4.1506  0.73901  4.1488  4.1488  0.10935  0.35931  0.013372 
 5  Best  4.1446  0.92415  4.1446  4.1446  326.29  2.5457  0.22475 
 6  Accept  4.1521  0.26444  4.1446  4.1447  719.11  0.19478  881.84 
 7  Accept  4.1501  0.34758  4.1446  4.1461  0.052426  2.5402  0.051319 
 8  Accept  4.1521  0.42136  4.1446  4.1447  990.71  0.014203  702.34 
 9  Accept  4.1521  0.79374  4.1446  4.1465  415.85  0.054602  81.005 
 10  Accept  4.1454  0.88854  4.1446  4.1455  972.49  1.1601  1.8715 
 11  Accept  4.1495  0.70652  4.1446  4.1473  121.79  1.4077  0.061055 
 12  Accept  4.1521  0.68302  4.1446  4.1474  985.81  0.83297  213.45 
 13  Best  4.1374  0.59647  4.1374  4.1441  167.34  2.5497  4.8997 
 14  Accept  4.1434  0.40922  4.1374  4.1437  74.527  2.55  6.1044 
 15  Accept  4.1402  0.50162  4.1374  4.1407  877.17  2.5391  2.2888 
 16  Accept  4.1436  0.20406  4.1374  4.1412  0.0010354  0.017613  0.11811 
 17  Best  4.1346  0.3256  4.1346  4.1375  0.0010362  0.010401  8.9719 
 18  Accept  4.1521  0.21696  4.1346  4.1422  0.0010467  0.0094817  563.96 
 19  Accept  4.1508  0.19558  4.1346  4.1367  760.12  0.0079557  0.009087 
 20  Accept  4.1435  0.31833  4.1346  4.143  0.020647  0.0089063  2.3699 
====================================================================================================================  Iter  Eval  Objective:  Objective  BestSoFar  BestSoFar  KernelScale  Lambda  Epsilon    result  log(1+loss)  runtime  (observed)  (estim.)     ====================================================================================================================  21  Best  3.7172  0.21841  3.7172  3.7174  818.08  2.5529e06  2.1058 
 22  Accept  4.1521  0.28442  3.7172  3.7177  0.006272  2.5598e06  93.063 
 23  Accept  4.0567  0.73954  3.7172  3.7176  940.43  2.6941e06  0.12016 
 24  Best  2.8979  1.757  2.8979  2.8979  37.141  2.5677e06  2.71 
 25  Accept  4.1521  0.40243  2.8979  2.898  13.817  2.5755e06  863.91 
 26  Best  2.795  2.3515  2.795  2.7953  20.022  2.6098e06  1.6561 
 27  Accept  2.8284  1.0168  2.795  2.7956  17.252  2.7719e06  0.82777 
 28  Best  2.7896  0.95814  2.7896  2.7898  11.432  7.621e06  2.094 
 29  Accept  2.8188  1.5983  2.7896  2.7899  8.5133  2.5872e06  2.0567 
 30  Accept  2.8061  0.99575  2.7896  2.7968  15.823  6.1956e06  2.0085 
__________________________________________________________ Optimization completed. MaxObjectiveEvaluations of 30 reached. Total function evaluations: 30 Total elapsed time: 84.236 seconds Total objective function evaluation time: 24.2628 Best observed feasible point: KernelScale Lambda Epsilon ___________ _________ _______ 11.432 7.621e06 2.094 Observed objective function value = 2.7896 Estimated objective function value = 2.7983 Function evaluation time = 0.95814 Best estimated feasible point (according to models): KernelScale Lambda Epsilon ___________ __________ _______ 15.823 6.1956e06 2.0085 Estimated objective function value = 2.7968 Estimated function evaluation time = 0.996
Mdl = RegressionKernel ResponseName: 'Y' Learner: 'svm' NumExpansionDimensions: 256 KernelScale: 15.8229 Lambda: 6.1956e06 BoxConstraint: 411.7488 Epsilon: 2.0085 Properties, Methods
FitInfo = struct with fields:
Solver: 'LBFGSfast'
LossFunction: 'epsiloninsensitive'
Lambda: 6.1956e06
BetaTolerance: 1.0000e04
GradientTolerance: 1.0000e06
ObjectiveValue: 1.3582
GradientMagnitude: 0.0051
RelativeChangeInBeta: 5.3944e05
FitTime: 0.2303
History: []
HyperparameterOptimizationResults = BayesianOptimization with properties: ObjectiveFcn: @createObjFcn/inMemoryObjFcn VariableDescriptions: [5x1 optimizableVariable] Options: [1x1 struct] MinObjective: 2.7896 XAtMinObjective: [1x3 table] MinEstimatedObjective: 2.7968 XAtMinEstimatedObjective: [1x3 table] NumObjectiveEvaluations: 30 TotalElapsedTime: 84.2360 NextPoint: [1x3 table] XTrace: [30x3 table] ObjectiveTrace: [30x1 double] ConstraintsTrace: [] UserDataTrace: {30x1 cell} ObjectiveEvaluationTimeTrace: [30x1 double] IterationTimeTrace: [30x1 double] ErrorTrace: [30x1 double] FeasibilityTrace: [30x1 logical] FeasibilityProbabilityTrace: [30x1 double] IndexOfMinimumTrace: [30x1 double] ObjectiveMinimumTrace: [30x1 double] EstimatedObjectiveMinimumTrace: [30x1 double]
For big data, the optimization procedure can take a long time. If the data set is too large to run the optimization procedure, you can try to optimize the parameters using only partial data. Use the datasample
function and specify 'Replace','false'
to sample data without replacement.
X
— Predictor dataPredictor data to which the regression model is fit, specified as an nbyp numeric matrix, where n is the number of observations and p is the number of predictor variables.
The length of Y
and the number of observations in
X
must be equal.
Data Types: single
 double
Tbl
— Sample dataSample data used to train the model, specified as a table. Each row of Tbl
corresponds to one observation, and each column corresponds to one predictor variable.
Optionally, Tbl
can contain one additional column for the response
variable. Multicolumn variables and cell arrays other than cell arrays of character
vectors are not allowed.
If Tbl
contains the response variable, and you want to use all remaining
variables in Tbl
as predictors, then specify the response variable by
using ResponseVarName
.
If Tbl
contains the response variable, and you want to use only a subset of
the remaining variables in Tbl
as predictors, then specify a formula
by using formula
.
If Tbl
does not contain the response variable, then specify a response
variable by using Y
. The length of the response variable and the
number of rows in Tbl
must be equal.
Data Types: table
ResponseVarName
— Response variable nameTbl
Response variable name, specified as the name of a variable in
Tbl
. The response variable must be a numeric vector.
You must specify ResponseVarName
as a character vector or string
scalar. For example, if Tbl
stores the response variable
Y
as Tbl.Y
, then specify it as
'Y'
. Otherwise, the software treats all columns of
Tbl
, including Y
, as predictors when
training the model.
Data Types: char
 string
formula
— Explanatory model of response variable and subset of predictor variablesExplanatory model of the response variable and a subset of the predictor variables,
specified as a character vector or string scalar in the form
'Y~X1+X2+X3'
. In this form, Y
represents the
response variable, and X1
, X2
, and
X3
represent the predictor variables.
To specify a subset of variables in Tbl
as predictors for
training the model, use a formula. If you specify a formula, then the software does not
use any variables in Tbl
that do not appear in
formula
.
The variable names in the formula must be both variable names in Tbl
(Tbl.Properties.VariableNames
) and valid MATLAB^{®} identifiers.
You can verify the variable names in Tbl
by using the isvarname
function. The following code returns logical 1
(true
) for each variable that has a valid variable name.
cellfun(@isvarname,Tbl.Properties.VariableNames)
Tbl
are not valid, then convert them by using the
matlab.lang.makeValidName
function.Tbl.Properties.VariableNames = matlab.lang.makeValidName(Tbl.Properties.VariableNames);
Data Types: char
 string
Note
The software treats NaN
, empty character vector
(''
), empty string (""
),
<missing>
, and <undefined>
elements as missing values, and removes observations with any of these characteristics:
Missing value in the response variable
At least one missing value in a predictor observation (row in
X
or Tbl
)
NaN
value or 0
weight
('Weights'
)
Specify optional
commaseparated 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
.
Mdl =
fitrkernel(X,Y,'Learner','leastsquares','NumExpansionDimensions',2^15,'KernelScale','auto')
implements leastsquares regression after mapping the predictor data to the
2^15
dimensional space using feature expansion with a kernel
scale parameter selected by a heuristic procedure.Note
You cannot use any crossvalidation namevalue pair argument along with the
'OptimizeHyperparameters'
namevalue pair argument. You can modify
the crossvalidation for 'OptimizeHyperparameters'
only by using the
'HyperparameterOptimizationOptions'
namevalue pair
argument.
'BoxConstraint'
— Box constraint1
(default)  positive scalarBox
constraint, specified as the commaseparated pair consisting
of 'BoxConstraint'
and a positive scalar.
This argument is valid only when 'Learner'
is
'svm'
(default) and you do not specify a value for
the regularization term strength 'Lambda'
. You can
specify either 'BoxConstraint'
or
'Lambda'
because the box constraint
(C) and the regularization term strength
(λ) are related by C =
1/(λn), where n is the number of
observations (rows in X
).
Example: 'BoxConstraint',100
Data Types: single
 double
'Epsilon'
— Half width of epsiloninsensitive band'auto'
(default)  nonnegative scalar valueHalf the width of the epsiloninsensitive band, specified as the
commaseparated pair consisting of 'Epsilon'
and
'auto'
or a nonnegative scalar value.
For 'auto'
, the fitrkernel
function determines the value of Epsilon
as
iqr(Y)/13.49
, which is an estimate of a tenth of
the standard deviation using the interquartile range of the response
variable Y
. If iqr(Y)
is equal to
zero, then fitrkernel
sets the value of
Epsilon
to 0.1.
'Epsilon'
is valid only when
Learner
is svm
.
Example: 'Epsilon',0.3
Data Types: single
 double
'NumExpansionDimensions'
— Number of dimensions of expanded space'auto'
(default)  positive integerNumber of dimensions of the expanded space, specified as the
commaseparated pair consisting of
'NumExpansionDimensions'
and
'auto'
or a positive integer. For
'auto'
, the fitrkernel
function selects the number of dimensions using
2.^ceil(min(log2(p)+5,15))
, where
p
is the number of predictors.
Example: 'NumExpansionDimensions',2^15
Data Types: char
 string
 single
 double
'KernelScale'
— Kernel scale parameter1
(default)  'auto'
 positive scalarKernel scale parameter, specified as the commaseparated pair
consisting of 'KernelScale'
and
'auto'
or a positive scalar. MATLAB obtains the random basis for random feature expansion by
using the kernel scale parameter. For details, see Random Feature Expansion.
If you specify 'auto'
, then MATLAB selects an appropriate kernel scale parameter using a
heuristic procedure. This heuristic 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.
Example: 'KernelScale','auto'
Data Types: char
 string
 single
 double
'Lambda'
— Regularization term strength'auto'
(default)  nonnegative scalarRegularization term strength, specified as the commaseparated pair
consisting of 'Lambda'
and 'auto'
or a nonnegative scalar.
For 'auto'
, the value of
'Lambda'
is 1/n, where
n is the number of observations (rows in
X
).
You can specify either 'BoxConstraint'
or
'Lambda'
because the box constraint
(C) and the regularization term strength
(λ) are related by C =
1/(λn).
Example: 'Lambda',0.01
Data Types: char
 string
 single
 double
'Learner'
— Linear regression model type'svm'
(default)  'leastsquares'
Linear regression model type, specified as the commaseparated pair
consisting of 'Learner'
and 'svm'
or 'leastsquares'
.
In the following table, $$f\left(x\right)=T(x)\beta +b.$$
x is an observation (row vector) from p predictor variables.
$$T(\xb7)$$ is a transformation of an observation (row vector) for feature expansion. T(x) maps x in $${\mathbb{R}}^{p}$$ to a highdimensional space ($${\mathbb{R}}^{m}$$).
β is a vector of m coefficients.
b is the scalar bias.
Value  Algorithm  Response range  Loss function 

'leastsquares'  Linear regression via ordinary least squares  y ∊ (∞,∞)  Mean squared error (MSE): $$\ell \left[y,f\left(x\right)\right]=\frac{1}{2}{\left[yf\left(x\right)\right]}^{2}$$ 
'svm'  Support vector machine regression  Same as 'leastsquares'  Epsiloninsensitive: $$\ell \left[y,f\left(x\right)\right]=\mathrm{max}\left[0,\leftyf\left(x\right)\right\epsilon \right]$$ 
Example: 'Learner','leastsquares'
'Verbose'
— Verbosity level0
(default)  1
Verbosity level, specified as the commaseparated pair consisting of
'Verbose'
and either 0
or
1
. Verbose
controls the amount
of diagnostic information fitrkernel
displays at
the command line.
Value  Description 

0  fitrkernel does not display
diagnostic information. 
1  fitrkernel displays and stores
the value of the objective function, gradient magnitude,
and other diagnostic information.
FitInfo.History contains the
diagnostic information. 
Example: 'Verbose',1
Data Types: single
 double
'BlockSize'
— Maximum amount of allocated memory4e^3
(4GB) (default)  positive scalarMaximum amount of allocated memory (in megabytes), specified as the
commaseparated pair consisting of 'BlockSize'
and a
positive scalar.
If fitrkernel
requires more memory than the value
of BlockSize
to hold the transformed predictor data,
then MATLAB uses a blockwise strategy. For details about the
blockwise strategy, see Algorithms.
Example: 'BlockSize',1e4
Data Types: single
 double
'RandomStream'
— Random number streamRandom number stream for reproducibility of data transformation,
specified as the commaseparated pair consisting of
'RandomStream'
and a random stream object. For
details, see Random Feature Expansion.
Use 'RandomStream'
to reproduce the random basis
functions that fitrkernel
uses to transform the data
in X
to a highdimensional space. For details, see
Managing the Global Stream Using RandStream and Creating and Controlling a Random Number Stream.
Example: 'RandomStream',RandStream('mlfg6331_64')
'CategoricalPredictors'
— Categorical predictors list'all'
Categorical predictors
list, specified as the commaseparated pair consisting of
'CategoricalPredictors'
and one of the values in this table.
Value  Description 

Vector of positive integers  Each entry in the vector is an index value corresponding to the column of the
predictor data (X or Tbl ) that contains a
categorical variable. 
Logical vector  A true entry means that the corresponding column of predictor
data (X or Tbl ) is a categorical
variable. 
Character matrix  Each row of the matrix is the name of a predictor variable. The names must match
the entries in PredictorNames . Pad the names with extra blanks so
each row of the character matrix has the same length. 
String array or cell array of character vectors  Each element in the array is the name of a predictor variable. The names must match
the entries in PredictorNames . 
'all'  All predictors are categorical. 
By default, if the
predictor data is in a table (Tbl
), fitrkernel
assumes that a variable is categorical if it is a logical vector, categorical vector, character
array, string array, or cell array of character vectors. If the predictor data is a matrix
(X
), fitrkernel
assumes that all predictors are
continuous. To identify any other predictors as categorical predictors, specify them by using
the 'CategoricalPredictors'
namevalue pair argument.
For the identified categorical predictors, fitrkernel
creates dummy variables using two different schemes, depending on whether a
categorical variable is unordered or ordered. For an unordered categorical
variable, fitrkernel
creates one dummy variable for
each level of the categorical variable. For an ordered categorical variable,
fitrkernel
creates one less dummy variable
than the number of categories. For details, see Automatic Creation of Dummy Variables.
Example: 'CategoricalPredictors','all'
Data Types: single
 double
 logical
 char
 string
 cell
'PredictorNames'
— Predictor variable namesPredictor variable names, specified as the commaseparated pair consisting of
'PredictorNames'
and a string array of unique names or cell array
of unique character vectors. The functionality of 'PredictorNames'
depends on the way you supply the training data.
If you supply X
and Y
, then you
can use 'PredictorNames'
to assign names to the predictor
variables in X
.
The order of the names in PredictorNames
must correspond to the column order of X
.
That is, PredictorNames{1}
is the name of
X(:,1)
,
PredictorNames{2}
is the name of
X(:,2)
, and so on. Also,
size(X,2)
and
numel(PredictorNames)
must be
equal.
By default, PredictorNames
is
{'x1','x2',...}
.
If you supply Tbl
, then you can use
'PredictorNames'
to choose which predictor variables
to use in training. That is, fitrkernel
uses only the
predictor variables in PredictorNames
and the response
variable during training.
PredictorNames
must be a subset of
Tbl.Properties.VariableNames
and cannot
include the name of the response variable.
By default, PredictorNames
contains the
names of all predictor variables.
A good practice is to specify the predictors for training
using either 'PredictorNames'
or
formula
, but not both.
Example: 'PredictorNames',{'SepalLength','SepalWidth','PetalLength','PetalWidth'}
Data Types: string
 cell
'ResponseName'
— Response variable name'Y'
(default)  character vector  string scalarResponse variable name, specified as the commaseparated pair consisting of
'ResponseName'
and a character vector or string scalar.
If you supply Y
, then you can
use 'ResponseName'
to specify a name for the response
variable.
If you supply ResponseVarName
or formula
,
then you cannot use 'ResponseName'
.
Example: 'ResponseName','response'
Data Types: char
 string
'ResponseTransform'
— Response transformation'none'
(default)  function handleResponse transformation, specified as the commaseparated pair consisting of
'ResponseTransform'
and either 'none'
or a
function handle. The default is 'none'
, which means
@(y)y
, or no transformation. For a MATLAB function or a function you define, use its function handle. The function
handle must accept a vector (the original response values) and return a vector of the
same size (the transformed response values).
Example: Suppose you create a function handle that applies an exponential
transformation to an input vector by using myfunction = @(y)exp(y)
.
Then, you can specify the response transformation as
'ResponseTransform',myfunction
.
Data Types: char
 string
 function_handle
'Weights'
— Observation weightsTbl
Observation weights, specified as the commaseparated pair consisting
of 'Weights'
and a vector of scalar values or the
name of a variable in Tbl
. The software weights
each observation (or row) in X
or
Tbl
with the corresponding value in
Weights
. The length of
Weights
must equal the number of rows in
X
or Tbl
.
If you specify the input data as a table Tbl
,
then Weights
can be the name of a variable in
Tbl
that contains a numeric vector. In this
case, you must specify Weights
as a character
vector or string scalar. For example, if weights vector
W
is stored as Tbl.W
, then
specify it as 'W'
. Otherwise, the software treats all
columns of Tbl
, including W
, as
predictors when training the model.
By default, Weights
is
ones(n,1)
, where n
is the
number of observations in X
or
Tbl
.
fitrkernel
normalizes the weights to sum to
1.
Data Types: single
 double
 char
 string
'CrossVal'
— Crossvalidation flag'off'
(default)  'on'
Crossvalidation flag, specified as the commaseparated pair
consisting of 'Crossval'
and 'on'
or 'off'
.
If you specify 'on'
, then the software implements
10fold crossvalidation.
You can override this crossvalidation setting using the
CVPartition
, Holdout
,
KFold
, or Leaveout
namevalue pair argument. You can use only one crossvalidation
namevalue pair argument at a time to create a crossvalidated
model.
Example: 'Crossval','on'
'CVPartition'
— Crossvalidation partition[]
(default)  cvpartition
partition objectCrossvalidation partition, specified as the commaseparated pair consisting of
'CVPartition'
and a cvpartition
partition
object created by cvpartition
. The partition object
specifies the type of crossvalidation and the indexing for the training and validation
sets.
To create a crossvalidated model, you can use one of these four namevalue pair arguments
only: CVPartition
, Holdout
,
KFold
, or Leaveout
.
Example: Suppose you create a random partition for 5fold crossvalidation on 500
observations by using cvp = cvpartition(500,'KFold',5)
. Then, you can
specify the crossvalidated model by using
'CVPartition',cvp
.
'Holdout'
— Fraction of data for holdout validationFraction of the data used for holdout validation, specified as the commaseparated pair
consisting of 'Holdout'
and a scalar value in the range (0,1). If you
specify 'Holdout',p
, then the software completes these steps:
Randomly select and reserve p*100
% of the data as
validation data, and train the model using the rest of the data.
Store the compact, trained model in the Trained
property of the crossvalidated model.
To create a crossvalidated model, you can use one of these
four namevalue pair arguments only: CVPartition
, Holdout
, KFold
,
or Leaveout
.
Example: 'Holdout',0.1
Data Types: double
 single
'KFold'
— Number of folds10
(default)  positive integer value greater than 1Number of folds to use in a crossvalidated model, specified as the commaseparated pair
consisting of 'KFold'
and a positive integer value greater than 1. If
you specify 'KFold',k
, then the software completes these steps:
Randomly partition the data into k
sets.
For each set, reserve the set as validation data, and train the model
using the other k
– 1 sets.
Store the k
compact, trained models in the cells of a
k
by1 cell vector in the Trained
property of the crossvalidated model.
To create a crossvalidated model, you can use one of these
four namevalue pair arguments only: CVPartition
, Holdout
, KFold
,
or Leaveout
.
Example: 'KFold',5
Data Types: single
 double
'Leaveout'
— Leaveoneout crossvalidation flag'off'
(default)  'on'
Leaveoneout crossvalidation flag, specified as the commaseparated pair consisting of
'Leaveout'
and 'on'
or
'off'
. If you specify 'Leaveout','on'
, then,
for each of the n observations (where n is the
number of observations excluding missing observations), the software completes these
steps:
Reserve the observation as validation data, and train the model using the other n – 1 observations.
Store the n compact, trained models in the cells of an
nby1 cell vector in the Trained
property of the crossvalidated model.
To create a crossvalidated model, you can use one of these
four namevalue pair arguments only: CVPartition
, Holdout
, KFold
,
or Leaveout
.
Example: 'Leaveout','on'
'BetaTolerance'
— Relative tolerance on linear coefficients and bias term1e5
(default)  nonnegative scalarRelative tolerance on the linear coefficients and the bias term (intercept), specified as the commaseparated pair consisting of 'BetaTolerance'
and a nonnegative scalar.
Let $${B}_{t}=\left[{\beta}_{t}{}^{\prime}\text{\hspace{0.17em}}\text{\hspace{0.17em}}{b}_{t}\right]$$, that is, the vector of the coefficients and the bias term at optimization iteration t. If $${\Vert \frac{{B}_{t}{B}_{t1}}{{B}_{t}}\Vert}_{2}<\text{BetaTolerance}$$, then optimization terminates.
If you also specify GradientTolerance
, then optimization terminates when the software satisfies either stopping criterion.
Example: 'BetaTolerance',1e6
Data Types: single
 double
'GradientTolerance'
— Absolute gradient tolerance1e6
(default)  nonnegative scalarAbsolute gradient tolerance, specified as the commaseparated pair consisting of 'GradientTolerance'
and a nonnegative scalar.
Let $$\nabla {\mathcal{L}}_{t}$$ be the gradient vector of the objective function with respect to the coefficients and bias term at optimization iteration t. If $${\Vert \nabla {\mathcal{L}}_{t}\Vert}_{\infty}=\mathrm{max}\left\nabla {\mathcal{L}}_{t}\right<\text{GradientTolerance}$$, then optimization terminates.
If you also specify BetaTolerance
, then optimization terminates when the
software satisfies either stopping criterion.
Example: 'GradientTolerance',1e5
Data Types: single
 double
'HessianHistorySize'
— Size of history buffer for Hessian approximation15
(default)  positive integerSize of the history buffer for Hessian approximation, specified as the
commaseparated pair consisting of
'HessianHistorySize'
and a positive integer. At
each iteration, fitrkernel
composes the Hessian by
using statistics from the latest HessianHistorySize
iterations.
Example: 'HessianHistorySize',10
Data Types: single
 double
'IterationLimit'
— Maximum number of optimization iterationsMaximum number of optimization iterations, specified as the
commaseparated pair consisting of 'IterationLimit'
and a positive integer.
The default value is 1000 if the transformed data fits in memory, as
specified by BlockSize
. Otherwise, the default
value is 100.
Example: 'IterationLimit',500
Data Types: single
 double
'OptimizeHyperparameters'
— Parameters to optimize'none'
(default)  'auto'
 'all'
 string array or cell array of eligible parameter names  vector of optimizableVariable
objectsParameters to optimize, specified as the commaseparated pair
consisting of 'OptimizeHyperparameters'
and one of
these values:
'none'
— Do not optimize.
'auto'
— Use
{'KernelScale','Lambda','Epsilon'}
.
'all'
— Optimize all eligible
parameters.
Cell array of eligible parameter names.
Vector of optimizableVariable
objects,
typically the output of hyperparameters
.
The optimization attempts to minimize the crossvalidation loss
(error) for fitrkernel
by varying the parameters.
To control the crossvalidation type and other aspects of the
optimization, use the
HyperparameterOptimizationOptions
namevalue
pair argument.
Note
'OptimizeHyperparameters'
values override any values you set using
other namevalue pair arguments. For example, setting
'OptimizeHyperparameters'
to 'auto'
causes the
'auto'
values to apply.
The eligible parameters for fitrkernel
are:
Epsilon
—
fitrkernel
searches among positive
values, by default logscaled in the range
[1e3,1e2]*iqr(Y)/1.349
.
KernelScale
—
fitrkernel
searches among positive
values, by default logscaled in the range
[1e3,1e3]
.
Lambda
—
fitrkernel
searches among positive
values, by default logscaled in the range
[1e3,1e3]/n
, where n
is the number of observations.
Learner
—
fitrkernel
searches among
'svm'
and
'leastsquares'
.
NumExpansionDimensions
—
fitrkernel
searches among positive
integers, by default logscaled in the range
[100,10000]
.
Set nondefault parameters by passing a vector of
optimizableVariable
objects that have nondefault
values. For example:
load carsmall params = hyperparameters('fitrkernel',[Horsepower,Weight],MPG); params(2).Range = [1e4,1e6];
Pass params
as the value of
'OptimizeHyperparameters'
.
By default, iterative display appears at the command line, and
plots appear according to the number of hyperparameters in the optimization. For the
optimization and plots, the objective function is log(1 + crossvalidation loss) for regression and the misclassification rate for classification. To control
the iterative display, set the Verbose
field of the
'HyperparameterOptimizationOptions'
namevalue pair argument. To
control the plots, set the ShowPlots
field of the
'HyperparameterOptimizationOptions'
namevalue pair argument.
For an example, see Optimize Kernel Regression.
Example: 'OptimizeHyperparameters','auto'
'HyperparameterOptimizationOptions'
— Options for optimizationOptions for optimization, specified as the commaseparated pair consisting of
'HyperparameterOptimizationOptions'
and a structure. This
argument modifies the effect of the OptimizeHyperparameters
namevalue pair argument. All fields in the structure are optional.
Field Name  Values  Default 

Optimizer 
 'bayesopt' 
AcquisitionFunctionName 
Acquisition functions whose names include
 'expectedimprovementpersecondplus' 
MaxObjectiveEvaluations  Maximum number of objective function evaluations.  30 for 'bayesopt' or 'randomsearch' , and the entire grid for 'gridsearch' 
MaxTime  Time limit, specified as a positive real. The time limit is in seconds, as measured by  Inf 
NumGridDivisions  For 'gridsearch' , the number of values in each dimension. The value can be
a vector of positive integers giving the number of
values for each dimension, or a scalar that
applies to all dimensions. This field is ignored
for categorical variables.  10 
ShowPlots  Logical value indicating whether to show plots. If true , this field plots
the best objective function value against the
iteration number. If there are one or two
optimization parameters, and if
Optimizer is
'bayesopt' , then
ShowPlots also plots a model of
the objective function against the
parameters.  true 
SaveIntermediateResults  Logical value indicating whether to save results when Optimizer is
'bayesopt' . If
true , this field overwrites a
workspace variable named
'BayesoptResults' at each
iteration. The variable is a BayesianOptimization object.  false 
Verbose  Display to the command line.
For details, see the
 1 
UseParallel  Logical value indicating whether to run Bayesian optimization in parallel, which requires Parallel Computing Toolbox™. Due to the nonreproducibility of parallel timing, parallel Bayesian optimization does not necessarily yield reproducible results. For details, see Parallel Bayesian Optimization.  false 
Repartition  Logical value indicating whether to repartition the crossvalidation at every iteration. If
 false 
Use no more than one of the following three field names.  
CVPartition  A cvpartition object, as created by cvpartition .  'Kfold',5 if you do not specify any crossvalidation
field 
Holdout  A scalar in the range (0,1) representing the holdout fraction.  
Kfold  An integer greater than 1. 
Example: 'HyperparameterOptimizationOptions',struct('MaxObjectiveEvaluations',60)
Data Types: struct
Mdl
— Trained kernel regression modelRegressionKernel
model object  RegressionPartitionedKernel
crossvalidated model
objectTrained kernel regression model, returned as a RegressionKernel
model object or RegressionPartitionedKernel
crossvalidated model
object.
If you set any of the namevalue pair arguments
CrossVal
, CVPartition
,
Holdout
, KFold
, or
Leaveout
, then Mdl
is a
RegressionPartitionedKernel
crossvalidated model.
Otherwise, Mdl
is a RegressionKernel
model.
To reference properties of Mdl
, use dot notation. For
example, enter Mdl.NumExpansionDimensions
in the Command
Window to display the number of dimensions of the expanded space.
Note
Unlike other regression models, and for economical memory usage, a
RegressionKernel
model object does not store the
training data or training process details (for example, convergence
history).
FitInfo
— Optimization detailsOptimization details, returned as a structure array including fields described in this table. The fields contain final values or namevalue pair argument specifications.
Field  Description 

Solver  Objective function minimization technique:

LossFunction  Loss function. Either mean squared error (MSE) or
epsiloninsensitive, depending on the type of linear
regression model. See Learner . 
Lambda  Regularization term strength. See
Lambda . 
BetaTolerance  Relative tolerance on the linear coefficients and the
bias term. See BetaTolerance . 
GradientTolerance  Absolute gradient tolerance. See
GradientTolerance . 
ObjectiveValue  Value of the objective function when optimization terminates. The regression loss plus the regularization term compose the objective function. 
GradientMagnitude  Infinite norm of the gradient vector of the objective
function when optimization terminates. See
GradientTolerance . 
RelativeChangeInBeta  Relative changes in the linear coefficients and the bias
term when optimization terminates. See
BetaTolerance . 
FitTime  Elapsed, wallclock time (in seconds) required to fit the model to the data. 
History  History of optimization information. This field also
includes the optimization information from training
Mdl . This field is empty
([] ) if you specify
'Verbose',0 . For details, see
Verbose and Algorithms. 
To access fields, use dot notation. For example, to access the vector of
objective function values for each iteration, enter
FitInfo.ObjectiveValue
in the Command Window.
Examine the information provided by FitInfo
to assess
whether convergence is satisfactory.
HyperparameterOptimizationResults
— Crossvalidation optimization of hyperparametersBayesianOptimization
object  table of hyperparameters and associated valuesCrossvalidation optimization of hyperparameters, returned as a BayesianOptimization
object or a table of hyperparameters and associated
values. The output is nonempty when the value of
'OptimizeHyperparameters'
is not 'none'
. The
output value depends on the Optimizer
field value of the
'HyperparameterOptimizationOptions'
namevalue pair
argument:
Value of Optimizer Field  Value of HyperparameterOptimizationResults 

'bayesopt' (default)  Object of class BayesianOptimization 
'gridsearch' or 'randomsearch'  Table of hyperparameters used, observed objective function values (crossvalidation loss), and rank of observations from lowest (best) to highest (worst) 
fitrkernel
does not accept initial conditions for the
linear coefficients beta (β) and bias term
(b) used to determine the decision function, $$f\left(x\right)=T(x)\beta +b.$$
fitrkernel
does not support standardization.
Random feature expansion, such as Random Kitchen Sinks[1] and 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.
The kernel regression algorithm searches for an optimal function that deviates from each response data point (y_{i}) by values no greater than the epsilon margin (ε) after mapping the predictor data into a highdimensional space.
Some regression problems cannot be described adequately using a linear model. In such cases, obtain a nonlinear regression model by replacing the dot product x_{1}x_{2}′ with a nonlinear kernel function $$G({x}_{1},{x}_{2})=\langle \phi ({x}_{1}),\phi ({x}_{2})\rangle $$, where x_{i} is the ith observation (row vector) and φ(x_{i}) is a transformation that maps x_{i} to a highdimensional space (called the “kernel trick”). However, evaluating G(x_{1},x_{2}) , 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,
$$G({x}_{1},{x}_{2})=\langle \phi ({x}_{1}),\phi ({x}_{2})\rangle \approx T({x}_{1})T({x}_{2})\text{'},$$
where T(x) maps x in $${\mathbb{R}}^{p}$$ to a highdimensional space ($${\mathbb{R}}^{m}$$). The Random Kitchen Sink[1] scheme uses the random transformation
$$T(x)={m}^{1/2}\mathrm{exp}\left(iZx\text{'}\right)\text{'},$$
where $$Z\in {\mathbb{R}}^{m\times p}$$ is a sample drawn from $$N\left(0,{\sigma}^{2}\right)$$ and σ^{2} 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(mlog
p) and reduces storage to O(m).
You can specify values for m and σ^{2}, using the NumExpansionDimensions
and
KernelScale
namevalue pair arguments of
fitrkernel
, respectively.
The fitrkernel
function uses the Fastfood scheme for random feature
expansion and uses linear regression to train a Gaussian kernel regression model. Unlike
solvers in the fitrsvm
function, which require computation of the
nbyn Gram matrix, the solver in
fitrkernel
only needs to form a matrix of size
nbym, with m typically much
less than n for big data.
A box constraint is a parameter that controls the maximum penalty imposed on observations that lie outside the epsilon margin (ε), and helps to prevent overfitting (regularization). Increasing the box constraint can lead to longer training times.
The box constraint (C) and the regularization term strength (λ) are related by C = 1/(λn), where n is the number of observations.
fitrkernel
minimizes the regularized objective function using a Limitedmemory BroydenFletcherGoldfarbShanno (LBFGS) solver with ridge (L_{2}) regularization. To find the type of LBFGS solver used for training, type FitInfo.Solver
in the Command Window.
'LBFGSfast'
— LBFGS solver.
'LBFGSblockwise'
— LBFGS solver with a blockwise strategy. If fitrkernel
requires more memory than the value of BlockSize
to hold the transformed predictor data, then it uses a blockwise strategy.
'LBFGStall'
— LBFGS solver with a blockwise strategy for tall arrays.
When fitrkernel
uses a blockwise strategy, fitrkernel
implements LBFGS by distributing the calculation of the loss and gradient among different parts of the data at each iteration. Also, fitrkernel
refines the initial estimates of the linear coefficients and the bias term by fitting the model locally to parts of the data and combining the coefficients by averaging. If you specify 'Verbose',1
, then fitrkernel
displays diagnostic information for each data pass and stores the information in the History
field of FitInfo
.
When fitrkernel
does not use a blockwise strategy, the initial estimates are zeros. If you specify 'Verbose',1
, then fitrkernel
displays diagnostic information for each iteration and stores the information in the History
field of FitInfo
.
[1] Rahimi, A., and B. Recht. “Random Features for LargeScale Kernel Machines.” Advances in Neural Information Processing Systems. Vol. 20, 2008, pp. 1177–1184.
[2] 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.
[3] 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.
Usage notes and limitations:
fitrkernel
does not support tall table
data.
Some namevalue pair arguments have different defaults compared to the default values
for the inmemory fitrkernel
function. Supported namevalue pair
arguments, and any differences, are:
'BoxConstraint'
'Epsilon'
'NumExpansionDimensions'
'KernelScale'
'Lambda'
'Learner'
'Verbose'
— Default value is
1
.
'BlockSize'
'RandomStream'
'ResponseTransform'
'Weights'
— Value must be a tall array.
'BetaTolerance'
— Default value is relaxed to
1e–3
.
'GradientTolerance'
— Default value is relaxed to
1e–5
.
'HessianHistorySize'
'IterationLimit'
— Default value is relaxed to
20
.
'OptimizeHyperparameters'
'HyperparameterOptimizationOptions'
— For
crossvalidation, tall optimization supports only 'Holdout'
validation. For example, you can specify
fitrkernel(X,Y,'OptimizeHyperparameters','auto','HyperparameterOptimizationOptions',struct('Holdout',0.2))
.
If 'KernelScale'
is 'auto'
, then
fitrkernel
uses the random stream controlled by tallrng
for subsampling. For reproducibility, you must set a random number seed for both the
global stream and the random stream controlled by tallrng
.
If 'Lambda'
is 'auto'
, then
fitrkernel
might take an extra pass through the data to
calculate the number of observations in X
.
fitrkernel
uses a blockwise strategy. For details, see Algorithms.
For more information, see Tall Arrays.
To perform parallel hyperparameter optimization, use the
'HyperparameterOptimizationOptions', struct('UseParallel',true)
namevalue pair argument in the call to this function.
For more information on parallel hyperparameter optimization, see Parallel Bayesian Optimization.
For more general information about parallel computing, see Run MATLAB Functions with Automatic Parallel Support (Parallel Computing Toolbox).
bayesopt
 bestPoint
 fitrlinear
 fitrsvm
 loss
 predict
 RegressionKernel
 RegressionPartitionedKernel
 resume
A modified version of this example exists on your system. Do you want to open this version instead?
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.
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
Select web siteYou can also select a web site from the following list:
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.