Fit Gaussian kernel classification model using random feature expansion
fitckernel
trains or crossvalidates a binary Gaussian
kernel classification model for nonlinear classification.
fitckernel
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.
fitckernel
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 classification models include regularized
support vector machine (SVM) and logistic regression models.
To train a nonlinear SVM model for binary classification of inmemory data, see
fitcsvm
.
returns a binary Gaussian kernel classification model trained using the
predictor data in Mdl
= fitckernel(X
,Y
)X
and the corresponding class labels in
Y
. The fitckernel
function maps
the predictors in a lowdimensional space into a highdimensional space, then
fits a binary SVM model to the transformed predictors and class labels. This
linear model is equivalent to the Gaussian kernel classification model in the
lowdimensional space.
returns a kernel classification model Mdl
= fitckernel(Tbl
,ResponseVarName
)Mdl
trained using the
predictor variables contained in the table Tbl
and the
class labels 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 logistic regression, specify the number of dimensions of the expanded
space, or specify to crossvalidate.Mdl
= fitckernel(___,Name,Value
)
[
also returns the hyperparameter optimization results
Mdl
,FitInfo
,HyperparameterOptimizationResults
] = fitckernel(___)HyperparameterOptimizationResults
when you optimize
hyperparameters by using the 'OptimizeHyperparameters'
namevalue pair argument.
Train a binary kernel classification model using SVM.
Load the ionosphere
data set. This data set has 34 predictors and 351 binary responses for radar returns, either bad ('b'
) or good ('g'
).
load ionosphere
[n,p] = size(X)
n = 351
p = 34
resp = unique(Y)
resp = 2x1 cell
{'b'}
{'g'}
Train a binary kernel classification model that identifies whether the radar return is bad ('b'
) or good ('g'
). Extract a fit summary to determine how well the optimization algorithm fits the model to the data.
rng('default') % For reproducibility [Mdl,FitInfo] = fitckernel(X,Y)
Mdl = ClassificationKernel ResponseName: 'Y' ClassNames: {'b' 'g'} Learner: 'svm' NumExpansionDimensions: 2048 KernelScale: 1 Lambda: 0.0028 BoxConstraint: 1 Properties, Methods
FitInfo = struct with fields:
Solver: 'LBFGSfast'
LossFunction: 'hinge'
Lambda: 0.0028
BetaTolerance: 1.0000e04
GradientTolerance: 1.0000e06
ObjectiveValue: 0.2604
GradientMagnitude: 0.0028
RelativeChangeInBeta: 8.2512e05
FitTime: 0.1526
History: []
Mdl
is a ClassificationKernel
model. To inspect the insample classification 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 class labels 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 better 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. 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 ionosphere
data set. This data set has 34 predictors and 351 binary responses for radar returns, either bad ('b'
) or good ('g'
).
load ionosphere rng('default') % For reproducibility
Crossvalidate a binary kernel classification model. By default, the software uses 10fold crossvalidation.
CVMdl = fitckernel(X,Y,'CrossVal','on')
CVMdl = ClassificationPartitionedKernel CrossValidatedModel: 'Kernel' ResponseName: 'Y' NumObservations: 351 KFold: 10 Partition: [1x1 cvpartition] ClassNames: {'b' 'g'} ScoreTransform: 'none' Properties, Methods
numel(CVMdl.Trained)
ans = 10
CVMdl
is a ClassificationPartitionedKernel
model. Because fitckernel
implements 10fold crossvalidation, CVMdl
contains 10 ClassificationKernel
models that the software trains on trainingfold (infold) observations.
Estimate the crossvalidated classification error.
kfoldLoss(CVMdl)
ans = 0.0940
The classification error rate is approximately 9%.
Optimize hyperparameters automatically using the 'OptimizeHyperparameters'
namevalue pair argument.
Load the ionosphere
data set. This data set has 34 predictors and 351 binary responses for radar returns, either bad ('b'
) or good ('g'
).
load ionosphere
Find hyperparameters that minimize fivefold crossvalidation loss by using automatic hyperparameter optimization. Specify 'OptimizeHyperparameters'
as 'auto'
so that fitckernel
finds optimal values of the 'KernelScale'
and 'Lambda'
namevalue pair arguments. For reproducibility, set the random seed and use the 'expectedimprovementplus'
acquisition function.
rng('default') [Mdl,FitInfo,HyperparameterOptimizationResults] = fitckernel(X,Y,'OptimizeHyperparameters','auto',... 'HyperparameterOptimizationOptions',struct('AcquisitionFunctionName','expectedimprovementplus'))
=====================================================================================================  Iter  Eval  Objective  Objective  BestSoFar  BestSoFar  KernelScale  Lambda    result   runtime  (observed)  (estim.)    =====================================================================================================  1  Best  0.35897  0.61226  0.35897  0.35897  64.836  4.4811e06   2  Accept  0.35897  0.89723  0.35897  0.35897  0.036335  0.015885   3  Accept  0.39601  1.0719  0.35897  0.36053  0.0022147  6.8254e06   4  Accept  0.35897  0.51388  0.35897  0.35898  5.1259  0.28097   5  Accept  0.35897  0.87527  0.35897  0.35897  0.24853  0.10828   6  Accept  0.35897  0.33667  0.35897  0.35897  885.09  0.00057316   7  Best  0.10826  1.4449  0.10826  0.10833  8.0346  0.0048286   8  Best  0.076923  0.60785  0.076923  0.076999  7.0902  0.0034068   9  Accept  0.091168  0.7268  0.076923  0.077059  9.1504  0.0020604   10  Best  0.062678  0.88783  0.062678  0.062723  3.5487  0.0025912   11  Accept  0.062678  0.90467  0.062678  0.062741  2.3869  0.003321   12  Accept  0.41026  0.76809  0.062678  0.062536  0.14075  0.0022499   13  Accept  0.062678  1.1677  0.062678  0.062532  3.4215  0.0036803   14  Accept  0.062678  1.1586  0.062678  0.061956  3.2928  0.0030533   15  Best  0.05698  0.95405  0.05698  0.057204  5.0598  0.0025499   16  Accept  0.062678  1.0064  0.05698  0.057186  5.3401  0.0015096   17  Accept  0.05698  0.70785  0.05698  0.057118  1.813  0.0069209   18  Accept  0.059829  0.6706  0.05698  0.057092  1.5122  0.0046637   19  Accept  0.059829  0.80386  0.05698  0.05718  1.9277  0.0056364   20  Accept  0.065527  0.76025  0.05698  0.057189  1.4064  0.0094306  =====================================================================================================  Iter  Eval  Objective  Objective  BestSoFar  BestSoFar  KernelScale  Lambda    result   runtime  (observed)  (estim.)    =====================================================================================================  21  Accept  0.05698  1.1415  0.05698  0.057033  5.1719  0.0023614   22  Best  0.054131  2.5181  0.054131  0.054176  1.9618  6.5704e05   23  Best  0.042735  0.7694  0.042735  0.042763  1.9463  1.0169e05   24  Accept  0.082621  1.2229  0.042735  0.042775  1.0661  1.3245e05   25  Accept  0.054131  2.0186  0.042735  0.042789  3.288  2.0035e05   26  Accept  0.062678  1.393  0.042735  0.042769  2.657  3.0334e06   27  Accept  0.059829  1.1079  0.042735  0.043054  2.0381  1.9791e05   28  Accept  0.042735  2.2283  0.042735  0.042764  3.5043  0.0001237   29  Accept  0.054131  0.89117  0.042735  0.042764  1.3897  3.2288e06   30  Accept  0.062678  1.2096  0.042735  0.042792  2.2414  0.0002259 
__________________________________________________________ Optimization completed. MaxObjectiveEvaluations of 30 reached. Total function evaluations: 30 Total elapsed time: 69.4698 seconds Total objective function evaluation time: 31.3772 Best observed feasible point: KernelScale Lambda ___________ __________ 1.9463 1.0169e05 Observed objective function value = 0.042735 Estimated objective function value = 0.043106 Function evaluation time = 0.7694 Best estimated feasible point (according to models): KernelScale Lambda ___________ _________ 3.5043 0.0001237 Estimated objective function value = 0.042792 Estimated function evaluation time = 1.6119
Mdl = ClassificationKernel ResponseName: 'Y' ClassNames: {'b' 'g'} Learner: 'svm' NumExpansionDimensions: 2048 KernelScale: 3.5043 Lambda: 1.2370e04 BoxConstraint: 23.0320 Properties, Methods
FitInfo = struct with fields:
Solver: 'LBFGSfast'
LossFunction: 'hinge'
Lambda: 1.2370e04
BetaTolerance: 1.0000e04
GradientTolerance: 1.0000e06
ObjectiveValue: 0.0426
GradientMagnitude: 0.0028
RelativeChangeInBeta: 8.9154e05
FitTime: 0.3753
History: []
HyperparameterOptimizationResults = BayesianOptimization with properties: ObjectiveFcn: @createObjFcn/inMemoryObjFcn VariableDescriptions: [4x1 optimizableVariable] Options: [1x1 struct] MinObjective: 0.0427 XAtMinObjective: [1x2 table] MinEstimatedObjective: 0.0428 XAtMinEstimatedObjective: [1x2 table] NumObjectiveEvaluations: 30 TotalElapsedTime: 69.4698 NextPoint: [1x2 table] XTrace: [30x2 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, specified as an nbyp numeric matrix, where n is the number of observations and p is the number of predictors.
The length of Y
and the number of observations in
X
must be equal.
Data Types: single
 double
Y
— Class labelsClass labels, specified as a categorical, character, or string array, logical or numeric vector, or cell array of character vectors.
fitckernel
supports only binary
classification. Either Y
must contain
exactly two distinct classes, or you must specify two classes
for training by using the ClassNames
namevalue pair argument.
If Y
is a character array, then each
element must correspond to one row of the array.
The length of Y
must be equal to the number
of observations in X
or
Tbl
.
A good practice is to specify the class order by using the
ClassNames
namevalue pair
argument.
Data Types: categorical
 char
 string
 logical
 single
 double
 cell
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
.
You must specify ResponseVarName
as a character vector or string scalar.
For example, if the response variable Y
is
stored as Tbl.Y
, then specify it as
'Y'
. Otherwise, the software
treats all columns of Tbl
, including
Y
, as predictors when training
the model.
The response variable must be a categorical, character, or string array; a logical or numeric
vector; or a cell array of character vectors. If
Y
is a character array, then each
element of the response variable must correspond to one row of
the array.
A good practice is to specify the order of the classes by using the
ClassNames
namevalue
argument.
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. If the variable names
are not valid, then you can convert them by using the matlab.lang.makeValidName
function.
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 =
fitckernel(X,Y,'Learner','logistic','NumExpansionDimensions',2^15,'KernelScale','auto')
implements logistic 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.
'Learner'
— Linear classification model type'svm'
(default)  'logistic'
Linear classification model type, specified as the commaseparated pair consisting of 'Learner'
and 'svm'
or 'logistic'
.
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 

'svm'  Support vector machine  y ∊ {–1,1}; 1 for the positive class and –1 otherwise  Hinge: $$\ell \left[y,f\left(x\right)\right]=\mathrm{max}\left[0,1yf\left(x\right)\right]$$ 
'logistic'  Logistic regression  Same as 'svm'  Deviance (logistic): $$\ell \left[y,f\left(x\right)\right]=\mathrm{log}\left\{1+\mathrm{exp}\left[yf\left(x\right)\right]\right\}$$ 
Example: 'Learner','logistic'
'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 fitckernel
function 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.
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.
The software obtains a random basis for random feature expansion by using the kernel
scale parameter. For details, see Random Feature Expansion.
If you specify 'auto'
, then the software 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
'BoxConstraint'
— Box constraintBox 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.
Example: 'BoxConstraint',100
Data Types: 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.
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
'CrossVal'
— Flag to train crossvalidated classifier'off'
(default)  'on'
Flag to train a crossvalidated classifier, specified as the
commaseparated pair consisting of 'Crossval'
and
'on'
or 'off'
.
If you specify 'on'
, then the software trains a
crossvalidated classifier with 10 folds.
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 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 specify only one of these four namevalue
arguments: 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 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 specify only one of these four namevalue
arguments: 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 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 a
k
by1 cell vector in the Trained
property of the crossvalidated model.
To create a crossvalidated model, you can specify only one of these four namevalue
arguments: 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 term1e–5
(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',1e–6
Data Types: single
 double
'GradientTolerance'
— Absolute gradient tolerance1e–6
(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',1e–5
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 the BlockSize
namevalue pair argument. Otherwise, the default value is 100.
Example: 'IterationLimit',500
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 fitckernel
requires more memory than the value of
'BlockSize'
to hold the transformed predictor data, then the
software 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
fitckernel
uses to transform the predictor data 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')
'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, fitckernel
composes the Hessian approximation by using
statistics from the latest HessianHistorySize
iterations.
Example: 'HessianHistorySize',10
Data Types: single
 double
'Verbose'
— Verbosity level0
(default)  1
Verbosity level, specified as the commaseparated pair consisting of
'Verbose'
and either 0
or
1
. Verbose
controls the
display of diagnostic information at the command line.
Value  Description 

0  fitckernel does not display
diagnostic information. 
1  fitckernel 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
'CategoricalPredictors'
— Categorical predictors list'all'
Categorical predictors list, specified as 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 that contains a categorical variable. The index values are between 1 and If 
Logical vector 
A 
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
), fitckernel
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
), fitckernel
assumes that all predictors are
continuous. To identify any other predictors as categorical predictors, specify them by using
the 'CategoricalPredictors'
namevalue argument.
For the identified categorical predictors, fitckernel
creates dummy variables using two different schemes, depending on whether a
categorical variable is unordered or ordered. For an unordered categorical
variable, fitckernel
creates one dummy variable for
each level of the categorical variable. For an ordered categorical variable,
fitckernel
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
'ClassNames'
— Names of classes to use for trainingNames of classes to use for training, specified as a categorical, character, or string array;
a logical or numeric vector; or a cell array of character vectors.
ClassNames
must have the same data type as the response variable
in Tbl
or Y
.
If ClassNames
is a character array, then each element must correspond to
one row of the array.
Use ClassNames
to:
Specify the order of the classes during training.
Specify the order of any input or output argument dimension that
corresponds to the class order. For example, use
ClassNames
to specify the order of the dimensions of
Cost
or the column order of classification scores
returned by predict
.
Select a subset of classes for training. For example, suppose that the set
of all distinct class names in Y
is
{'a','b','c'}
. To train the model using observations
from classes 'a'
and 'c'
only, specify
'ClassNames',{'a','c'}
.
The default value for ClassNames
is the set of all distinct class names in
the response variable in Tbl
or Y
.
Example: 'ClassNames',{'b','g'}
Data Types: categorical
 char
 string
 logical
 single
 double
 cell
'Cost'
— Misclassification costMisclassification cost, specified as the commaseparated pair consisting of
'Cost'
and a square matrix or structure.
If you specify the square matrix cost
('Cost',cost
), then cost(i,j)
is the
cost of classifying a point into class j
if its true class is
i
. That is, the rows correspond to the true class, and
the columns correspond to the predicted class. To specify the class order for
the corresponding rows and columns of cost
, use the
ClassNames
namevalue pair argument.
If you specify the structure S
('Cost',S
), then it must have two fields:
S.ClassNames
, which contains the class names as
a variable of the same data type as Y
S.ClassificationCosts
, which contains the cost
matrix with rows and columns ordered as in
S.ClassNames
The default value for Cost
is
ones(
, where K
) –
eye(K
)K
is
the number of distinct classes.
fitckernel
uses Cost
to adjust the prior
class probabilities specified in Prior
. Then,
fitckernel
uses the adjusted prior probabilities for training
and resets the cost matrix to its default.
Example: 'Cost',[0 2; 1 0]
Data Types: single
 double
 struct
'PredictorNames'
— Predictor variable namesPredictor variable names, specified as 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, fitckernel
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
'Prior'
— Prior probabilities'empirical'
(default)  'uniform'
 numeric vector  structure arrayPrior probabilities for each class, specified as the commaseparated pair consisting
of 'Prior'
and 'empirical'
,
'uniform'
, a numeric vector, or a structure array.
This table summarizes the available options for setting prior probabilities.
Value  Description 

'empirical'  The class prior probabilities are the class relative frequencies
in Y . 
'uniform'  All class prior probabilities are equal to
1/K , where
K is the number of classes. 
numeric vector  Each element is a class prior probability. Order the elements
according to their order in Y . If you specify
the order using the 'ClassNames' namevalue
pair argument, then order the elements accordingly. 
structure array 
A structure

fitckernel
normalizes the prior probabilities in
Prior
to sum to 1.
Example: 'Prior',struct('ClassNames',{{'setosa','versicolor'}},'ClassProbs',1:2)
Data Types: char
 string
 double
 single
 struct
'ResponseName'
— Response variable name'Y'
(default)  character vector  string scalarResponse variable name, specified as 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
'ScoreTransform'
— Score transformation'none'
(default)  'doublelogit'
 'invlogit'
 'ismax'
 'logit'
 function handle  ...Score transformation, specified as a character vector, string scalar, or function handle.
This table summarizes the available character vectors and string scalars.
Value  Description 

'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 + e^{–x}) 
'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 + e^{–x}) – 1 
For a MATLAB function or a function you define, use its function handle for the score transform. The function handle must accept a matrix (the original scores) and return a matrix of the same size (the transformed scores).
Example: 'ScoreTransform','logit'
Data Types: char
 string
 function_handle
'Weights'
— Observation weightsTbl
Observation weights, specified as a nonnegative numeric vector or the name of a
variable in Tbl
. The software weights each observation in
X
or Tbl
with the corresponding value in
Weights
. The length of Weights
must equal
the number of observations 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 the 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 or the response variable when training the model.
By default, Weights
is ones(n,1)
, where
n
is the number of observations in X
or
Tbl
.
The software normalizes Weights
to sum to the value of the prior
probability in the respective class.
Data Types: single
 double
 char
 string
'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'}
.
'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 fitckernel
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 fitckernel
are:
KernelScale
—
fitckernel
searches among positive
values, by default logscaled in the range
[1e3,1e3]
.
Lambda
—
fitckernel
searches among positive
values, by default logscaled in the range
[1e3,1e3]/n
, where n
is the number of observations.
Learner
—
fitckernel
searches among
'svm'
and
'logistic'
.
NumExpansionDimensions
—
fitckernel
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 fisheriris params = hyperparameters('fitckernel',meas,species); 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 Classifier.
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 classification modelClassificationKernel
model object  ClassificationPartitionedKernel
crossvalidated model
objectTrained kernel classification model, returned as a ClassificationKernel
model object or ClassificationPartitionedKernel
crossvalidated model
object.
If you set any of the namevalue pair arguments
CrossVal
, CVPartition
,
Holdout
, KFold
, or
Leaveout
, then Mdl
is a
ClassificationPartitionedKernel
crossvalidated
classifier. Otherwise, Mdl
is a
ClassificationKernel
classifier.
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 classification models, and for economical memory usage, a
ClassificationKernel
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 'hinge' or 'logit' depending on
the type of linear classification 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 classification 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 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.
A good practice is to examine 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) 
fitckernel
does not accept initial conditions for the
vector of coefficients beta (β) and bias term
(b) used to determine the decision function, $$f\left(x\right)=T(x)\beta +b.$$
fitckernel
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 classification algorithm to use 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 classification algorithm searches for an optimal hyperplane that separates the data into two classes after mapping features into a highdimensional space. Nonlinear features that are not linearly separable in a lowdimensional space can be separable in the expanded highdimensional space. All the calculations for hyperplane classification use only dot products. You can obtain a nonlinear classification model by replacing the dot product x_{1}x_{2}' with the 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}) (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 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 scheme introduces another random
basis V instead of Z using Hadamard matrices combined
with Gaussian scaling matrices. This random basis reduces the computation cost to O(mlog
p) and reduces storage to O(m).
The fitckernel
function uses the Fastfood scheme for random feature expansion and uses linear classification to train a Gaussian kernel classification model. Unlike solvers in the fitcsvm
function, which require computation of the nbyn Gram matrix, the solver in fitckernel
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 marginviolating observations, and aids in preventing 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.
fitckernel
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 fitckernel
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 fitckernel
uses a blockwise strategy, fitckernel
implements LBFGS by distributing the calculation of the loss and gradient among different parts of the data at each iteration. Also, fitckernel
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 fitckernel
displays diagnostic information for each data pass and stores the information in the History
field of FitInfo
.
When fitckernel
does not use a blockwise strategy, the initial estimates are zeros. If you specify 'Verbose',1
, then fitckernel
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:
fitckernel
does not support tall table
data.
Some namevalue pair arguments have different defaults compared to the default values
for the inmemory fitckernel
function. Supported namevalue pair
arguments, and any differences, are:
'Learner'
'NumExpansionDimensions'
'KernelScale'
'BoxConstraint'
'Lambda'
'BetaTolerance'
— Default value is relaxed to
1e–3
.
'GradientTolerance'
— Default value is relaxed to
1e–5
.
'IterationLimit'
— Default value is relaxed to
20
.
'BlockSize'
'RandomStream'
'HessianHistorySize'
'Verbose'
— Default value is
1
.
'ClassNames'
'Cost'
'Prior'
'ScoreTransform'
'Weights'
— Value must be a tall array.
'OptimizeHyperparameters'
'HyperparameterOptimizationOptions'
— For
crossvalidation, tall optimization supports only 'Holdout'
validation. By
default, the software selects and reserves 20% of the data as holdout validation data, and
trains the model using the rest of the data. You can specify a different value for the holdout
fraction by using this argument. For example, specify
'HyperparameterOptimizationOptions',struct('Holdout',0.3)
to reserve 30%
of the data as validation data.
If 'KernelScale'
is 'auto'
, then
fitckernel
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
fitckernel
might take an extra pass through the data to
calculate the number of observations in X
.
fitckernel
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 argument in the call to this function.
For more information on parallel hyperparameter optimization, see Parallel Bayesian Optimization.
For general information about parallel computing, see Run MATLAB Functions with Automatic Parallel Support (Parallel Computing Toolbox).
bayesopt
 bestPoint
 ClassificationKernel
 ClassificationPartitionedKernel
 fitclinear
 fitcsvm
 predict
 resume
 templateKernel
Sie haben eine abgeänderte Version dieses Beispiels. Möchten Sie dieses Beispiel mit Ihren Änderungen öffnen?
Sie haben auf einen Link geklickt, der diesem MATLABBefehl entspricht:
Führen Sie den Befehl durch Eingabe in das MATLABBefehlsfenster aus. Webbrowser unterstützen keine MATLABBefehle.
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.