main content

fit k-凯发k8网页登录

fit k-nearest neighbor classifier

description

mdl = fitcknn(tbl,responsevarname) returns a k-nearest neighbor classification model based on the input variables (also known as predictors, features, or attributes) in the table tbl and output (response) tbl.responsevarname.

mdl = fitcknn(tbl,formula) returns a k-nearest neighbor classification model based on the input variables in the table tbl. formula is an explanatory model of the response and a subset of predictor variables in tbl.

mdl = fitcknn(tbl,y) returns a k-nearest neighbor classification model based on the predictor variables in the table tbl and response array y.

example

mdl = fitcknn(x,y) returns a k-nearest neighbor classification model based on the predictor data x and response y.

example

mdl = fitcknn(___,name,value) fits a model with additional options specified by one or more name-value pair arguments, using any of the previous syntaxes. for example, you can specify the tie-breaking algorithm, distance metric, or observation weights.

examples

train a k-nearest neighbor classifier for fisher's iris data, where k, the number of nearest neighbors in the predictors, is 5.

load fisher's iris data.

load fisheriris
x = meas;
y = species;

x is a numeric matrix that contains four petal measurements for 150 irises. y is a cell array of character vectors that contains the corresponding iris species.

train a 5-nearest neighbor classifier. standardize the noncategorical predictor data.

mdl = fitcknn(x,y,'numneighbors',5,'standardize',1)
mdl = 
  classificationknn
             responsename: 'y'
    categoricalpredictors: []
               classnames: {'setosa'  'versicolor'  'virginica'}
           scoretransform: 'none'
          numobservations: 150
                 distance: 'euclidean'
             numneighbors: 5
  properties, methods

mdl is a trained classificationknn classifier, and some of its properties appear in the command window.

to access the properties of mdl, use dot notation.

mdl.classnames
ans = 3x1 cell
    {'setosa'    }
    {'versicolor'}
    {'virginica' }
mdl.prior
ans = 1×3
    0.3333    0.3333    0.3333

mdl.prior contains the class prior probabilities, which you can specify using the 'prior' name-value pair argument in fitcknn. the order of the class prior probabilities corresponds to the order of the classes in mdl.classnames. by default, the prior probabilities are the respective relative frequencies of the classes in the data.

you can also reset the prior probabilities after training. for example, set the prior probabilities to 0.5, 0.2, and 0.3, respectively.

mdl.prior = [0.5 0.2 0.3];

you can pass mdl to to label new measurements or to cross-validate the classifier.

load fisher's iris data set.

load fisheriris
x = meas;
y = species;

x is a numeric matrix that contains four petal measurements for 150 irises. y is a cell array of character vectors that contains the corresponding iris species.

train a 3-nearest neighbors classifier using the minkowski metric. to use the minkowski metric, you must use an exhaustive searcher. it is good practice to standardize noncategorical predictor data.

mdl = fitcknn(x,y,'numneighbors',3,...
    'nsmethod','exhaustive','distance','minkowski',...
    'standardize',1);

mdl is a classificationknn classifier.

you can examine the properties of mdl by double-clicking mdl in the workspace window. this opens the variable editor.

train a k-nearest neighbor classifier using the chi-square distance.

load fisher's iris data set.

load fisheriris
x = meas;    % predictors
y = species; % response

the chi-square distance between j-dimensional points x and z is

χ(x,z)=j=1jwj(xj-zj)2,

where wj is a weight associated with dimension j.

specify the chi-square distance function. the distance function must:

  • take one row of x, e.g., x, and the matrix z.

  • compare x to each row of z.

  • return a vector d of length nz, where nz is the number of rows of z. each element of d is the distance between the observation corresponding to x and the observations corresponding to each row of z.

chisqrdist = @(x,z,wt)sqrt(((x-z).^2)*wt);

this example uses arbitrary weights for illustration.

train a 3-nearest neighbor classifier. it is good practice to standardize noncategorical predictor data.

k = 3;
w = [0.3; 0.3; 0.2; 0.2];
knnmdl = fitcknn(x,y,'distance',@(x,z)chisqrdist(x,z,w),...
    'numneighbors',k,'standardize',1);

knnmdl is a classificationknn classifier.

cross validate the knn classifier using the default 10-fold cross validation. examine the classification error.

rng(1); % for reproducibility
cvknnmdl = crossval(knnmdl);
classerror = kfoldloss(cvknnmdl)
classerror = 0.0600

cvknnmdl is a classifier.

compare the classifier with one that uses a different weighting scheme.

w2 = [0.2; 0.2; 0.3; 0.3];
cvknnmdl2 = fitcknn(x,y,'distance',@(x,z)chisqrdist(x,z,w2),...
    'numneighbors',k,'kfold',10,'standardize',1);
classerror2 = kfoldloss(cvknnmdl2)
classerror2 = 0.0400

the second weighting scheme yields a classifier that has better out-of-sample performance.

this example shows how to optimize hyperparameters automatically using fitcknn. the example uses the fisher iris data.

load the data.

load fisheriris
x = meas;
y = species;

find hyperparameters that minimize five-fold cross-validation loss by using automatic hyperparameter optimization.

for reproducibility, set the random seed and use the 'expected-improvement-plus' acquisition function.

rng(1)
mdl = fitcknn(x,y,'optimizehyperparameters','auto',...
    'hyperparameteroptimizationoptions',...
    struct('acquisitionfunctionname','expected-improvement-plus'))
|=====================================================================================================|
| iter | eval   | objective   | objective   | bestsofar   | bestsofar   | numneighbors |     distance |
|      | result |             | runtime     | (observed)  | (estim.)    |              |              |
|=====================================================================================================|
|    1 | best   |    0.026667 |     0.93272 |    0.026667 |    0.026667 |           30 |       cosine |
|    2 | accept |        0.04 |     0.22392 |    0.026667 |    0.027197 |            2 |    chebychev |
|    3 | accept |     0.19333 |     0.23713 |    0.026667 |    0.030324 |            1 |      hamming |
|    4 | accept |     0.33333 |     0.33057 |    0.026667 |    0.033313 |           31 |     spearman |
|    5 | best   |        0.02 |     0.21366 |        0.02 |    0.020648 |            6 |       cosine |
|    6 | accept |    0.073333 |      0.1918 |        0.02 |    0.023082 |            1 |  correlation |
|    7 | accept |        0.06 |     0.21582 |        0.02 |    0.020875 |            2 |    cityblock |
|    8 | accept |        0.04 |     0.19365 |        0.02 |    0.020622 |            1 |    euclidean |
|    9 | accept |        0.24 |     0.27736 |        0.02 |    0.020562 |           74 |  mahalanobis |
|   10 | accept |        0.04 |     0.26018 |        0.02 |    0.020649 |            1 |    minkowski |
|   11 | accept |    0.053333 |     0.31004 |        0.02 |    0.020722 |            1 |   seuclidean |
|   12 | accept |     0.19333 |     0.36758 |        0.02 |    0.020701 |            1 |      jaccard |
|   13 | accept |        0.04 |      0.3148 |        0.02 |    0.029203 |            1 |       cosine |
|   14 | accept |        0.04 |     0.42565 |        0.02 |    0.031888 |           75 |       cosine |
|   15 | accept |        0.04 |     0.28468 |        0.02 |    0.020076 |            1 |       cosine |
|   16 | accept |    0.093333 |     0.28414 |        0.02 |    0.020073 |           75 |    euclidean |
|   17 | accept |    0.093333 |     0.24074 |        0.02 |     0.02007 |           75 |    minkowski |
|   18 | accept |         0.1 |     0.19106 |        0.02 |    0.020061 |           75 |    chebychev |
|   19 | accept |     0.15333 |      0.2197 |        0.02 |    0.020044 |           75 |   seuclidean |
|   20 | accept |         0.1 |     0.13465 |        0.02 |    0.020044 |           75 |    cityblock |
|=====================================================================================================|
| iter | eval   | objective   | objective   | bestsofar   | bestsofar   | numneighbors |     distance |
|      | result |             | runtime     | (observed)  | (estim.)    |              |              |
|=====================================================================================================|
|   21 | accept |    0.033333 |     0.29323 |        0.02 |    0.020046 |           75 |  correlation |
|   22 | accept |    0.033333 |     0.19429 |        0.02 |     0.02656 |            9 |       cosine |
|   23 | accept |    0.033333 |     0.19591 |        0.02 |     0.02854 |            9 |       cosine |
|   24 | accept |        0.02 |     0.23934 |        0.02 |    0.028607 |            1 |    chebychev |
|   25 | accept |        0.02 |     0.26742 |        0.02 |    0.022264 |            1 |    chebychev |
|   26 | accept |        0.02 |     0.15246 |        0.02 |    0.021439 |            1 |    chebychev |
|   27 | accept |        0.02 |     0.26158 |        0.02 |    0.020999 |            1 |    chebychev |
|   28 | accept |     0.66667 |     0.25601 |        0.02 |    0.020008 |           75 |      hamming |
|   29 | accept |        0.04 |     0.25378 |        0.02 |    0.020008 |           12 |  correlation |
|   30 | best   |    0.013333 |     0.12752 |    0.013333 |    0.013351 |            6 |    euclidean |

figure contains an axes object. the axes object with title min objective vs. number of function evaluations, xlabel function evaluations, ylabel min objective contains 2 objects of type line. these objects represent min observed objective, estimated min objective.

figure contains an axes object. the axes object with title objective function model, xlabel numneighbors, ylabel distance contains 5 objects of type line, surface, contour. one or more of the lines displays its values using only markers these objects represent observed points, model mean, next point, model minimum feasible.

__________________________________________________________
optimization completed.
maxobjectiveevaluations of 30 reached.
total function evaluations: 30
total elapsed time: 52.8862 seconds
total objective function evaluation time: 8.0914
best observed feasible point:
    numneighbors    distance 
    ____________    _________
         6          euclidean
observed objective function value = 0.013333
estimated objective function value = 0.013351
function evaluation time = 0.12752
best estimated feasible point (according to models):
    numneighbors    distance 
    ____________    _________
         6          euclidean
estimated objective function value = 0.013351
estimated function evaluation time = 0.15594
mdl = 
  classificationknn
                         responsename: 'y'
                categoricalpredictors: []
                           classnames: {'setosa'  'versicolor'  'virginica'}
                       scoretransform: 'none'
                      numobservations: 150
    hyperparameteroptimizationresults: [1x1 bayesianoptimization]
                             distance: 'euclidean'
                         numneighbors: 6
  properties, methods

input arguments

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

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 name-value argument.

data types: char | string

explanatory 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

class labels, specified as a categorical, character, or string array, a logical or numeric vector, or a cell array of character vectors. each row of y represents the classification of the corresponding row of x.

the software considers nan, '' (empty character vector), "" (empty string), , and values in y to be missing values. consequently, the software does not train using observations with a missing response.

data types: categorical | char | string | logical | single | double | cell

predictor data, specified as numeric matrix.

each row corresponds to one observation (also known as an instance or example), and each column corresponds to one predictor variable (also known as a feature).

the length of y and the number of rows of x must be equal.

to specify the names of the predictors in the order of their appearance in x, use the predictornames name-value pair argument.

data types: double | single

name-value arguments

specify optional pairs of arguments as name1=value1,...,namen=valuen, where name is the argument name and value is the corresponding value. name-value arguments must appear after other arguments, but the order of the pairs does not matter.

before r2021a, use commas to separate each name and value, and enclose name in quotes.

example: 'numneighbors',3,'nsmethod','exhaustive','distance','minkowski' specifies a classifier for three-nearest neighbors using the nearest neighbor search method and the minkowski metric.

note

you cannot use any cross-validation name-value argument together with the 'optimizehyperparameters' name-value argument. you can modify the cross-validation for 'optimizehyperparameters' only by using the 'hyperparameteroptimizationoptions' name-value argument.

model parameters

tie-breaking algorithm used by the method if multiple classes have the same smallest cost, specified as the comma-separated pair consisting of 'breakties' and one of the following:

  • 'smallest' — use the smallest index among tied groups.

  • 'nearest' — use the class with the nearest neighbor among tied groups.

  • 'random' — use a random tiebreaker among tied groups.

by default, ties occur when multiple classes have the same number of nearest points among the k nearest neighbors.

example: 'breakties','nearest'

maximum number of data points in the leaf node of the kd-tree, specified as the comma-separated pair consisting of 'bucketsize' and a positive integer value. this argument is meaningful only when nsmethod is 'kdtree'.

example: 'bucketsize',40

data types: single | double

categorical predictor flag, specified as the comma-separated pair consisting of 'categoricalpredictors' and one of the following:

  • 'all' — all predictors are categorical.

  • [] — no predictors are categorical.

the predictor data for fitcknn must be either all continuous or all categorical.

  • if the predictor data is in a table (tbl), fitcknn 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 tbl includes both continuous and categorical values, then you must specify the value of 'categoricalpredictors' so that fitcknn can determine how to treat all predictors, as either continuous or categorical variables.

  • if the predictor data is a matrix (x), fitcknn assumes that all predictors are continuous. to identify all predictors in x as categorical, specify 'categoricalpredictors' as 'all'.

when you set categoricalpredictors to 'all', the default distance is 'hamming'.

example: 'categoricalpredictors','all'

names 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 of misclassification of a point, specified as the comma-separated pair consisting of 'cost' and one of the following:

  • square matrix, where cost(i,j) is the cost of classifying a point into class j if its true class is i (i.e., 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, additionally specify the classnames name-value pair argument.

  • structure s having two fields: s.classnames containing the group names as a variable of the same type as y, and s.classificationcosts containing the cost matrix.

the default is cost(i,j)=1 if i~=j, and cost(i,j)=0 if i=j.

data types: single | double | struct

covariance matrix, specified as the comma-separated pair consisting of 'cov' and a positive definite matrix of scalar values representing the covariance matrix when computing the mahalanobis distance. this argument is only valid when 'distance' is 'mahalanobis'.

you cannot simultaneously specify 'standardize' and either of 'scale' or 'cov'.

data types: single | double

distance metric, specified as the comma-separated pair consisting of 'distance' and a valid distance metric name or function handle. the allowable distance metric names depend on your choice of a neighbor-searcher method (see nsmethod).

nsmethoddistance metric names
exhaustiveany distance metric of
kdtree'cityblock', 'chebychev', 'euclidean', or 'minkowski'

this table includes valid distance metrics of .

distance metric namesdescription
'cityblock'city block distance.
'chebychev'chebychev distance (maximum coordinate difference).
'correlation'one minus the sample linear correlation between observations (treated as sequences of values).
'cosine'one minus the cosine of the included angle between observations (treated as vectors).
'euclidean'euclidean distance.
'hamming'hamming distance, percentage of coordinates that differ.
'jaccard'one minus the jaccard coefficient, the percentage of nonzero coordinates that differ.
'mahalanobis'mahalanobis distance, computed using a positive definite covariance matrix c. the default value of c is the sample covariance matrix of x, as computed by cov(x,'omitrows'). to specify a different value for c, use the 'cov' name-value pair argument.
'minkowski'minkowski distance. the default exponent is 2. to specify a different exponent, use the 'exponent' name-value pair argument.
'seuclidean'standardized euclidean distance. each coordinate difference between x and a query point is scaled, meaning divided by a scale value s. the default value of s is the standard deviation computed from x, s = std(x,'omitnan'). to specify another value for s, use the scale name-value pair argument.
'spearman'one minus the sample spearman's rank correlation between observations (treated as sequences of values).
@distfun

distance function handle. distfun has the form

function d2 = distfun(zi,zj)
% calculation of  distance
...
where
  • zi is a 1-by-n vector containing one row of x or y.

  • zj is an m2-by-n matrix containing multiple rows of x or y.

  • d2 is an m2-by-1 vector of distances, and d2(k) is the distance between observations zi and zj(k,:).

if you specify categoricalpredictors as 'all', then the default distance metric is 'hamming'. otherwise, the default distance metric is 'euclidean'.

change distance using dot notation: mdl.distance = newdistance.

if nsmethod is 'kdtree', you can use dot notation to change distance only for the metrics 'cityblock', 'chebychev', 'euclidean', and 'minkowski'.

for definitions, see .

example: 'distance','minkowski'

data types: char | string | function_handle

distance weighting function, specified as the comma-separated pair consisting of 'distanceweight' and either a function handle or one of the values in this table.

valuedescription
'equal'no weighting
'inverse'weight is 1/distance
'squaredinverse'weight is 1/distance2
@fcnfcn is a function that accepts a matrix of nonnegative distances, and returns a matrix the same size containing nonnegative distance weights. for example, 'squaredinverse' is equivalent to @(d)d.^(-2).

example: 'distanceweight','inverse'

data types: char | string | function_handle

minkowski distance exponent, specified as the comma-separated pair consisting of 'exponent' and a positive scalar value. this argument is only valid when 'distance' is 'minkowski'.

example: 'exponent',3

data types: single | double

tie inclusion flag, specified as the comma-separated pair consisting of 'includeties' and a logical value indicating whether includes all the neighbors whose distance values are equal to the kth smallest distance. if includeties is true, predict includes all these neighbors. otherwise, predict uses exactly k neighbors.

example: 'includeties',true

data types: logical

nearest neighbor search method, specified as the comma-separated pair consisting of 'nsmethod' and 'kdtree' or 'exhaustive'.

  • 'kdtree' — creates and uses a kd-tree to find nearest neighbors. 'kdtree' is valid when the distance metric is one of the following:

    • 'euclidean'

    • 'cityblock'

    • 'minkowski'

    • 'chebychev'

  • 'exhaustive' — uses the exhaustive search algorithm. when predicting the class of a new point xnew, the software computes the distance values from all points in x to xnew to find nearest neighbors.

the default is 'kdtree' when x has 10 or fewer columns, x is not sparse or a gpuarray, and the distance metric is a 'kdtree' type; otherwise, 'exhaustive'.

example: 'nsmethod','exhaustive'

number of nearest neighbors in x to find for classifying each point when predicting, specified as the comma-separated pair consisting of 'numneighbors' and a positive integer value.

example: 'numneighbors',3

data types: single | double

predictor 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, fitcknn 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 probabilities for each class, specified as the comma-separated pair consisting of 'prior' and a value in this table.

valuedescription
'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 vectoreach element is a class prior probability. order the elements according to mdl.classnames or specify the order using the classnames name-value pair argument. the software normalizes the elements such that they sum to 1.
structure

a structure s with two fields:

  • s.classnames contains the class names as a variable of the same type as y.

  • s.classprobs contains a vector of corresponding prior probabilities. the software normalizes the elements such that they sum to 1.

if you set values for both weights and prior, the weights are renormalized to add up to the value of the prior probability in the respective class.

example: 'prior','uniform'

data types: char | string | single | double | struct

response 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

distance scale, specified as the comma-separated pair consisting of 'scale' and a vector containing nonnegative scalar values with length equal to the number of columns in x. each coordinate difference between x and a query point is scaled by the corresponding element of scale. this argument is only valid when 'distance' is 'seuclidean'.

you cannot simultaneously specify 'standardize' and either of 'scale' or 'cov'.

data types: single | double

score transformation, specified as a character vector, string scalar, or function handle.

this table summarizes the available character vectors and string scalars.

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

for a matlab function or a function 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

flag to standardize the predictors, specified as the comma-separated pair consisting of 'standardize' and true (1) or false (0).

if you set 'standardize',true, then the software centers and scales each column of the predictor data (x) by the column mean and standard deviation, respectively.

the software does not standardize categorical predictors, and throws an error if all predictors are categorical.

you cannot simultaneously specify 'standardize',1 and either of 'scale' or 'cov'.

it is good practice to standardize the predictor data.

example: 'standardize',true

data types: logical

observation weights, specified as the comma-separated pair consisting of 'weights' and a numeric vector of positive values or name of a variable in tbl. the software weighs the observations in each row of x or tbl with the corresponding value in weights. the size of weights must equal the number of rows of 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 when training the model.

the software normalizes weights to sum up to the value of the prior probability in the respective class.

by default, weights is ones(n,1), where n is the number of observations in x or tbl.

data types: double | single | char | string

cross validation options

cross-validation flag, specified as the comma-separated pair consisting of 'crossval' and 'on' or 'off'.

if you specify 'on', then the software implements 10-fold cross-validation.

to override this cross-validation setting, use one of these name-value pair arguments: cvpartition, holdout, kfold, or leaveout. to create a cross-validated model, you can use one cross-validation name-value pair argument at a time only.

alternatively, cross validate mdl later using the method.

example: 'crossval','on'

cross-validation partition, specified as a cvpartition partition object created by cvpartition. the partition object specifies the type of cross-validation and the indexing for the training and validation sets.

to create a cross-validated model, you can specify only one of these four name-value arguments: cvpartition, holdout, kfold, or leaveout.

example: suppose you create a random partition for 5-fold cross-validation on 500 observations by using cvp = cvpartition(500,'kfold',5). then, you can specify the cross-validated model by using 'cvpartition',cvp.

fraction 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:

  1. randomly select and reserve p*100% of the data as validation data, and train the model using the rest of the data.

  2. store the compact, trained model in the trained property of the cross-validated model.

to create a cross-validated model, you can specify only one of these four name-value arguments: cvpartition, holdout, kfold, or leaveout.

example: 'holdout',0.1

data types: double | single

number of folds to use in a cross-validated model, specified as a positive integer value greater than 1. if you specify 'kfold',k, then the software completes these steps:

  1. randomly partition the data into k sets.

  2. for each set, reserve the set as validation data, and train the model using the other k – 1 sets.

  3. store the k compact, trained models in a k-by-1 cell vector in the trained property of the cross-validated model.

to create a cross-validated model, you can specify only one of these four name-value arguments: cvpartition, holdout, kfold, or leaveout.

example: 'kfold',5

data types: single | double

leave-one-out cross-validation flag, specified as '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, specified in the numobservations property of the model), the software completes these steps:

  1. reserve the one observation as validation data, and train the model using the other n – 1 observations.

  2. store the n compact, trained models in an n-by-1 cell vector in the trained property of the cross-validated model.

to create a cross-validated model, you can specify only one of these four name-value arguments: cvpartition, holdout, kfold, or leaveout.

example: 'leaveout','on'

hyperparameter optimization options

parameters to optimize, specified as the comma-separated pair consisting of 'optimizehyperparameters' and one of the following:

  • 'none' — do not optimize.

  • 'auto' — use {'distance','numneighbors'}.

  • 'all' — optimize all eligible parameters.

  • string array or cell array of eligible parameter names.

  • vector of optimizablevariable objects, typically the output of .

the optimization attempts to minimize the cross-validation loss (error) for fitcknn by varying the parameters. for information about cross-validation loss (albeit in a different context), see . to control the cross-validation type and other aspects of the optimization, use the hyperparameteroptimizationoptions name-value pair.

note

the values of 'optimizehyperparameters' override any values you specify using other name-value arguments. for example, setting 'optimizehyperparameters' to 'auto' causes fitcknn to optimize hyperparameters corresponding to the 'auto' option and to ignore any specified values for the hyperparameters.

the eligible parameters for fitcknn are:

  • distancefitcknn searches among 'cityblock', 'chebychev', 'correlation', 'cosine', 'euclidean', 'hamming', 'jaccard', 'mahalanobis', 'minkowski', 'seuclidean', and 'spearman'.

  • distanceweightfitcknn searches among 'equal', 'inverse', and 'squaredinverse'.

  • exponentfitcknn searches among positive real values, by default in the range [0.5,3].

  • numneighborsfitcknn searches among positive integer values, by default log-scaled in the range [1, max(2,round(numobservations/2))].

  • standardizefitcknn searches among the values 'true' and 'false'.

set nondefault parameters by passing a vector of optimizablevariable objects that have nondefault values. for example,

load fisheriris
params = hyperparameters('fitcknn',meas,species);
params(1).range = [1,20];

pass params as the value of optimizehyperparameters.

by default, the 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 the misclassification rate. to control the iterative display, set the verbose field of the 'hyperparameteroptimizationoptions' name-value argument. to control the plots, set the showplots field of the 'hyperparameteroptimizationoptions' name-value argument.

for an example, see optimize fitted knn classifier.

example: 'auto'

options for optimization, specified as a structure. this argument modifies the effect of the optimizehyperparameters name-value argument. all fields in the structure are optional.

field namevaluesdefault
optimizer
  • 'bayesopt' — use bayesian optimization. internally, this setting calls .

  • 'gridsearch' — use grid search with numgriddivisions values per dimension.

  • 'randomsearch' — search at random among maxobjectiveevaluations points.

'gridsearch' searches in a random order, using uniform sampling without replacement from the grid. after optimization, you can get a table in grid order by using the command sortrows(mdl.hyperparameteroptimizationresults).

'bayesopt'
acquisitionfunctionname
  • 'expected-improvement-per-second-plus'

  • 'expected-improvement'

  • 'expected-improvement-plus'

  • 'expected-improvement-per-second'

  • 'lower-confidence-bound'

  • 'probability-of-improvement'

acquisition functions whose names include per-second do not yield reproducible results because the optimization depends on the runtime of the objective function. acquisition functions whose names include plus modify their behavior when they are overexploiting an area. for more details, see acquisition function types.

'expected-improvement-per-second-plus'
maxobjectiveevaluationsmaximum number of objective function evaluations.30 for 'bayesopt' and 'randomsearch', and the entire grid for 'gridsearch'
maxtime

time limit, specified as a positive real scalar. the time limit is in seconds, as measured by tic and toc. the run time can exceed maxtime because maxtime does not interrupt function evaluations.

inf
numgriddivisionsfor '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
showplotslogical value indicating whether to show plots. if true, this field plots the best observed objective function value against the iteration number. if you use bayesian optimization (optimizer is 'bayesopt'), then this field also plots the best estimated objective function value. the best observed objective function values and best estimated objective function values correspond to the values in the bestsofar (observed) and bestsofar (estim.) columns of the iterative display, respectively. you can find these values in the properties objectiveminimumtrace and estimatedobjectiveminimumtrace of mdl.hyperparameteroptimizationresults. if the problem includes one or two optimization parameters for bayesian optimization, then showplots also plots a model of the objective function against the parameters.true
saveintermediateresultslogical 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 at the command line:

  • 0 — no iterative display

  • 1 — iterative display

  • 2 — iterative display with extra information

for details, see the bayesopt name-value argument and the example .

1
useparallellogical 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 .false
repartition

logical value indicating whether to repartition the cross-validation at every iteration. if this field is false, the optimizer uses a single partition for the optimization.

the setting true usually gives the most robust results because it takes partitioning noise into account. however, for good results, true requires at least twice as many function evaluations.

false
use no more than one of the following three options.
cvpartitiona cvpartition object, as created by cvpartition'kfold',5 if you do not specify a cross-validation field
holdouta scalar in the range (0,1) representing the holdout fraction
kfoldan integer greater than 1

example: 'hyperparameteroptimizationoptions',struct('maxobjectiveevaluations',60)

data types: struct

output arguments

trained k-nearest neighbor classification model, returned as a classificationknn model object or a cross-validated model object.

if you set any of the name-value pair arguments kfold, holdout, crossval, or cvpartition, then mdl is a classificationpartitionedmodel cross-validated model object. otherwise, mdl is a classificationknn model object.

to reference properties of mdl, use dot notation. for example, to display the distance metric at the command window, enter mdl.distance.

more about

prediction

classificationknn predicts the classification of a point xnew using a procedure equivalent to this:

  1. find the numneighbors points in the training set x that are nearest to xnew.

  2. find the numneighbors response values y to those nearest points.

  3. assign the classification label ynew that has the largest posterior probability among the values in y.

for details, see in the documentation.

tips

after training a model, you can generate c/c code that predicts labels for new data. generating c/c code requires matlab coder™. for details, see introduction to code generation.

algorithms

  • nans or s indicate missing observations. the following describes the behavior of fitcknn when the data set or weights contain missing observations.

    • if any value of y or any weight is missing, then fitcknn removes those values from y, the weights, and the corresponding rows of x from the data. the software renormalizes the weights to sum to 1.

    • if you specify to standardize predictors ('standardize',1) or the standardized euclidean distance ('distance','seuclidean') without a scale, then fitcknn removes missing observations from individual predictors before computing the mean and standard deviation. in other words, the software implements and with the 'omitnan' option on each predictor.

    • if you specify the mahalanobis distance ('distance','mahalanbois') without its covariance matrix, then fitcknn removes rows of x that contain at least one missing value. in other words, the software implements with the 'omitrows' option on the predictor matrix x.

  • if you specify the cost, prior, and weights name-value arguments, the output model object stores the specified values in the cost, prior, and w properties, respectively. the cost property stores the user-specified cost matrix as is. the prior and w properties store the prior probabilities and observation weights, respectively, after normalization. for details, see .

  • the software uses the cost property for prediction, but not training. therefore, cost is not read-only; you can change the property value by using dot notation after creating the trained model.

  • suppose that you set 'standardize',true.

    • if you also specify the prior or weights name-value pair argument, then fitcknn standardizes the predictors using their corresponding weighted means and weighted standard deviations. specifically, fitcknn standardizes the predictor j using

      • xj=xjμjσj.

        μj=1kwkkwkxjk.

        xjk is observation k (row) of predictor j (column).

        (σj)2=kwk(kwk)2kwk2kwk(xjkμj)2.

    • if you also set 'distance','mahalanobis' or 'distance','seuclidean', then you cannot specify scale or cov. instead, the software:

      1. computes the means and standard deviations of each predictor.

      2. standardizes the data using the results of step 1.

      3. computes the distance parameter values using their respective default.

  • if you specify scale and either of prior or weights, then the software scales observed distances by the weighted standard deviations.

  • if you specify cov and either of prior or weights, then the software applies the weighted covariance matrix to the distances. in other words,

    cov=kwk(kwk)2kwk2jkwk(xjkμj*)(xjμj*).

alternatives

although fitcknn can train a multiclass knn classifier, you can reduce a multiclass learning problem to a series of knn binary learners using fitcecoc.

extended capabilities

version history

introduced in r2014a

see also

| | | | |

topics

    网站地图