Documentación

Esta página aún no se ha traducido para esta versión. Puede ver la versión más reciente de esta página en inglés.

# fitcknn

Fit k-nearest neighbor classifier

## Sintaxis

``Mdl = fitcknn(Tbl,ResponseVarName)``
``Mdl = fitcknn(Tbl,formula)``
``Mdl = fitcknn(Tbl,Y)``
``Mdl = fitcknn(X,Y)``
``Mdl = fitcknn(___,Name,Value)``

## Descripción

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

ejemplo

````Mdl = fitcknn(X,Y)` returns a k-nearest neighbor classification model based on the predictor data `X` and response `Y`.```

ejemplo

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

## Ejemplos

contraer todo

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

```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 array {'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 `predict` to label new measurements or `crossval` to cross-validate the classifier.

```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 fisheriris X = meas; % Predictors Y = species; % Response```

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

` `

where 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 , where 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((bsxfun(@minus,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 `ClassificationPartitionedModel` classifier. The 10-fold classification error is 4%.

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 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 | 1.0158 | 0.026667 | 0.026667 | 30 | cosine | | 2 | Accept | 0.04 | 0.39927 | 0.026667 | 0.027197 | 2 | chebychev | | 3 | Accept | 0.19333 | 0.18765 | 0.026667 | 0.030324 | 1 | hamming | | 4 | Accept | 0.33333 | 0.36547 | 0.026667 | 0.033313 | 31 | spearman | | 5 | Best | 0.02 | 0.25285 | 0.02 | 0.020648 | 6 | cosine | | 6 | Accept | 0.073333 | 0.20157 | 0.02 | 0.023082 | 1 | correlation | | 7 | Accept | 0.06 | 0.15599 | 0.02 | 0.020875 | 2 | cityblock | | 8 | Accept | 0.04 | 0.1428 | 0.02 | 0.020622 | 1 | euclidean | | 9 | Accept | 0.24 | 1.0926 | 0.02 | 0.020562 | 74 | mahalanobis | | 10 | Accept | 0.04 | 0.24127 | 0.02 | 0.020649 | 1 | minkowski | | 11 | Accept | 0.053333 | 0.34142 | 0.02 | 0.020722 | 1 | seuclidean | | 12 | Accept | 0.19333 | 0.30933 | 0.02 | 0.020701 | 1 | jaccard | | 13 | Accept | 0.04 | 0.15495 | 0.02 | 0.029203 | 1 | cosine | | 14 | Accept | 0.04 | 0.48505 | 0.02 | 0.031888 | 75 | cosine | | 15 | Accept | 0.04 | 0.23479 | 0.02 | 0.020076 | 1 | cosine | | 16 | Accept | 0.093333 | 0.41927 | 0.02 | 0.020073 | 75 | euclidean | | 17 | Accept | 0.093333 | 0.43578 | 0.02 | 0.02007 | 75 | minkowski | | 18 | Accept | 0.1 | 0.25479 | 0.02 | 0.020061 | 75 | chebychev | | 19 | Accept | 0.15333 | 0.37246 | 0.02 | 0.020044 | 75 | seuclidean | | 20 | Accept | 0.1 | 0.19676 | 0.02 | 0.020044 | 75 | cityblock | |=====================================================================================================| | Iter | Eval | Objective | Objective | BestSoFar | BestSoFar | NumNeighbors | Distance | | | result | | runtime | (observed) | (estim.) | | | |=====================================================================================================| | 21 | Accept | 0.033333 | 0.25546 | 0.02 | 0.020046 | 75 | correlation | | 22 | Accept | 0.033333 | 0.24401 | 0.02 | 0.02656 | 9 | cosine | | 23 | Accept | 0.033333 | 0.13001 | 0.02 | 0.02854 | 9 | cosine | | 24 | Accept | 0.02 | 0.27867 | 0.02 | 0.028607 | 1 | chebychev | | 25 | Accept | 0.02 | 0.1302 | 0.02 | 0.022264 | 1 | chebychev | | 26 | Accept | 0.02 | 0.14608 | 0.02 | 0.021439 | 1 | chebychev | | 27 | Accept | 0.02 | 0.33121 | 0.02 | 0.020999 | 1 | chebychev | | 28 | Accept | 0.66667 | 0.15383 | 0.02 | 0.020008 | 75 | hamming | | 29 | Accept | 0.04 | 0.17944 | 0.02 | 0.020008 | 12 | correlation | | 30 | Best | 0.013333 | 0.23457 | 0.013333 | 0.013351 | 6 | euclidean | __________________________________________________________ Optimization completed. MaxObjectiveEvaluations of 30 reached. Total function evaluations: 30 Total elapsed time: 102.5273 seconds. Total objective function evaluation time: 9.3433 Best observed feasible point: NumNeighbors Distance ____________ _________ 6 euclidean Observed objective function value = 0.013333 Estimated objective function value = 0.013351 Function evaluation time = 0.23457 Best estimated feasible point (according to models): NumNeighbors Distance ____________ _________ 6 euclidean Estimated objective function value = 0.013351 Estimated function evaluation time = 0.26113 ```
```Mdl = ClassificationKNN ResponseName: 'Y' CategoricalPredictors: [] ClassNames: {'setosa' 'versicolor' 'virginica'} ScoreTransform: 'none' NumObservations: 150 HyperparameterOptimizationResults: [1x1 BayesianOptimization] Distance: 'euclidean' NumNeighbors: 6 Properties, Methods ```

contraer todo

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.

Tipos de datos: `table`

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, logical or numeric vector, or 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.

It is a good practice to specify the order of the classes by using the `ClassNames` name-value pair argument.

Tipos de datos: `char` | `string`

Explanatory model of the response and a subset of the predictor variables, specified as a character vector or string scalar in the form of `'Y~X1+X2+X3'`. In this form, `Y` represents the response variable, and `X1`, `X2`, and `X3` represent the predictor variables. The variables must be variable names in `Tbl` (`Tbl.Properties.VariableNames`).

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

Tipos de datos: `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), `<missing>`, and `<undefined>` values in `Y` to be missing values. Consequently, the software does not train using observations with a missing response.

Tipos de datos: `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.

Tipos de datos: `double` | `single`

### Argumentos de par nombre-valor

Specify optional comma-separated 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`.

Ejemplo: `'NumNeighbors',3,'NSMethod','exhaustive','Distance','minkowski'` specifies a classifier for three-nearest neighbors using the nearest neighbor search method and the Minkowski metric.

### Nota

You cannot use any cross-validation name-value pair argument along with the `'OptimizeHyperparameters'` name-value pair argument. You can modify the cross-validation for `'OptimizeHyperparameters'` only by using the `'HyperparameterOptimizationOptions'` name-value pair argument.

#### Model Parameters

contraer todo

Tie-breaking algorithm used by the `predict` 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.

Ejemplo: `'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'`.

Ejemplo: `'BucketSize',40`

Tipos de datos: `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.

When you set `CategoricalPredictors` to `'all'`, the default `Distance` is `'hamming'`.

Ejemplo: `'CategoricalPredictors','all'`

Names of classes to use for training, specified as the comma-separated pair consisting of `'ClassNames'` and 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 `Y`.

If `ClassNames` is a character array, then each element must correspond to one row of the array.

Use `ClassNames` to:

• Order 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 `Y`.

Ejemplo: `'ClassNames',{'b','g'}`

Tipos de datos: `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`.

Tipos de datos: `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'`.

Tipos de datos: `single` | `double`

Tie inclusion flag, specified as the comma-separated pair consisting of `'IncludeTies'` and a logical value indicating whether `predict` includes all the neighbors whose distance values are equal to the `K`th smallest distance. If `IncludeTies` is `true`, `predict` includes all these neighbors. Otherwise, `predict` uses exactly `K` neighbors.

Ejemplo: `'IncludeTies',true`

Tipos de datos: `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, and the distance metric is a `'kdtree'` type; otherwise, `'exhaustive'`.

Ejemplo: `'NSMethod','exhaustive'`

Predictor variable names, specified as the comma-separated pair consisting of `'PredictorNames'` and a string array of unique names or cell array of unique character vectors. The functionality of `'PredictorNames'` depends on the way you supply the training data.

• If you supply `X` and `Y`, then you can use `'PredictorNames'` to give the predictor variables in `X` names.

• 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 in 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.

• It is a good practice to specify the predictors for training using either `'PredictorNames'` or `formula` only.

Ejemplo: `'PredictorNames',{'SepalLength','SepalWidth','PetalLength','PetalWidth'}`

Tipos de datos: `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.

Ejemplo: `'Prior','uniform'`

Tipos de datos: `char` | `string` | `single` | `double` | `struct`

Response variable name, specified as the comma-separated pair consisting of `'ResponseName'` and a character vector or string scalar.

Ejemplo: `'ResponseName','response'`

Tipos de datos: `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'`.

Tipos de datos: `single` | `double`

Score transformation, specified as the comma-separated pair consisting of `'ScoreTransform'` and 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 score transform. The function handle must accept a matrix (the original scores) and return a matrix of the same size (the transformed scores).

Ejemplo: `'ScoreTransform','logit'`

Tipos de datos: `char` | `string` | `function_handle`

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

Tipos de datos: `double` | `single` | `char` | `string`

#### Cross Validation

contraer todo

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 later by passing `Mdl` to `crossval`.

Ejemplo: `'CrossVal','on'`

Cross-validation partition, specified as the comma-separated pair consisting of `'CVPartition'` and a `cvpartition` partition object as 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 use one of these four name-value pair arguments only: `'CVPartition'`, `'Holdout'`, `'KFold'`, or `'Leaveout'`.

Ejemplo: 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 the comma-separated pair consisting of `'Holdout'` and 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 use one of these four name-value pair arguments only: `CVPartition`, `Holdout`, `KFold`, or `Leaveout`.

Ejemplo: `'Holdout',0.1`

Tipos de datos: `double` | `single`

Number of folds to use in a cross-validated model, specified as the comma-separated pair consisting of `'KFold'` and 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 the cells of a `k`-by-1 cell vector in the `Trained` property of the cross-validated model.

To create a cross-validated model, you can use one of these four name-value pair arguments only: `CVPartition`, `Holdout`, `KFold`, or `Leaveout`.

Ejemplo: `'KFold',5`

Tipos de datos: `single` | `double`

Leave-one-out cross-validation flag, specified as the comma-separated 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, specified in the `NumObservations` property of the model), the software completes these steps:

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

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

To create a cross-validated model, you can use one of these four name-value pair arguments only: `CVPartition`, `Holdout`, `KFold`, or `Leaveout`.

Ejemplo: `'Leaveout','on'`

#### Hyperparameter Optimization

contraer todo

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
`exhaustive`Any distance metric of `ExhaustiveSearcher`
`kdtree``'cityblock'`, `'chebychev'`, `'euclidean'`, or `'minkowski'`

This table includes valid distance metrics of `ExhaustiveSearcher`.

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 `nancov(X)`. 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 = nanstd(X)`. 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'`.

For definitions, see Distance Metrics.

Ejemplo: `'Distance','minkowski'`

Tipos de datos: `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
`@fcn``fcn` 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)`.

Ejemplo: `'DistanceWeight','inverse'`

Tipos de datos: `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'`.

Ejemplo: `'Exponent',3`

Tipos de datos: `single` | `double`

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.

Ejemplo: `'NumNeighbors',3`

Tipos de datos: `single` | `double`

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.

Ejemplo: `'Standardize',true`

Tipos de datos: `logical`

#### Hyperparameter Optimization

contraer todo

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 `hyperparameters`.

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 Classification Loss. To control the cross-validation type and other aspects of the optimization, use the `HyperparameterOptimizationOptions` name-value pair.

### Nota

`'OptimizeHyperparameters'` values override any values you set using other name-value pair arguments. For example, setting `'OptimizeHyperparameters'` to `'auto'` causes the `'auto'` values to apply.

The eligible parameters for `fitcknn` are:

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

• `DistanceWeight``fitcknn` searches among `'equal'`, `'inverse'`, and `'squaredinverse'`.

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

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

• `Standardize``fitcknn` 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, 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 + cross-validation loss) for regression and the misclassification rate for classification. To control the iterative display, set the `Verbose` field of the `'HyperparameterOptimizationOptions'` name-value pair argument. To control the plots, set the `ShowPlots` field of the `'HyperparameterOptimizationOptions'` name-value pair argument.

For an example, see Optimize Fitted KNN Classifier.

Ejemplo: `'auto'`

Options for optimization, specified as the comma-separated pair consisting of `'HyperparameterOptimizationOptions'` and a structure. This argument modifies the effect of the `OptimizeHyperparameters` name-value pair argument. All fields in the structure are optional.

Field NameValuesDefault
`Optimizer`
• `'bayesopt'` — Use Bayesian optimization. Internally, this setting calls `bayesopt`.

• `'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'`

For details, see the `bayesopt ``AcquisitionFunctionName` name-value pair argument, or Acquisition Function Types.

`'expected-improvement-per-second-plus'`
`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 `tic` and `toc`. Run time can exceed `MaxTime` because `MaxTime` does not interrupt function evaluations.

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

• `0` — No iterative display

• `1` — Iterative display

• `2` — Iterative display with extra information

For details, see the `bayesopt` `Verbose` name-value pair argument.

`1`
`UseParallel`Logical value indicating whether to run Bayesian optimization in parallel, which requires Parallel Computing Toolbox™ . For details, see Parallel Bayesian Optimization.`false`
`Repartition`

Logical value indicating whether to repartition the cross-validation at every iteration. If `false`, the optimizer uses a single partition for the optimization.

`true` usually gives the most robust results because this setting 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 field names.
`CVPartition`A `cvpartition` object, as created by `cvpartition`.`'Kfold',5` if you do not specify any cross-validation field
`Holdout`A scalar in the range `(0,1)` representing the holdout fraction.
`Kfold`An integer greater than 1.

Ejemplo: `'HyperparameterOptimizationOptions',struct('MaxObjectiveEvaluations',60)`

Tipos de datos: `struct`

## Output Arguments

contraer todo

Trained k-nearest neighbor classification model, returned as a `ClassificationKNN` model object or a `ClassificationPartitionedModel` 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`.

## Más acerca de

contraer todo

### 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 Posterior Probability in the `predict` documentation.

## Sugerencias

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.

## Algoritmos

• `NaNs` or `<undefined>`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 `nanmean` and `nanstd` 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 `nancov` on the predictor matrix `X`.

• Suppose that you set `'Standardize',1`.

• If you also specify `Prior` or `Weights`, then the software takes the observation weights into account. Specifically, the weighted mean of predictor j is

`${\overline{x}}_{j}=\sum _{{B}_{j}}^{}{w}_{k}{x}_{jk}$`

and the weighted standard deviation is

`${s}_{j}=\sum _{Bj}^{}{w}_{k}\left({x}_{jk}-{\overline{x}}_{j}\right),$`

where Bj is the set of indices k for which xjk and wk are not missing.

• 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=\frac{\sum _{B}{w}_{j}}{{\left(\sum _{B}{w}_{j}\right)}^{2}-\sum _{B}{w}_{j}^{2}}\sum _{B}^{}{w}_{j}{\left({x}_{j}-\overline{x}\right)}^{\prime }\left({x}_{j}-\overline{x}\right),$`

where B is the set of indices j for which the observation xj does not have any missing values and wj is not missing.

## 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`.