main content

k-凯发k8网页登录

k-nearest neighbor classification

description

classificationknn is a nearest neighbor classification model in which you can alter both the distance metric and the number of nearest neighbors. because a classificationknn classifier stores training data, you can use the model to compute resubstitution predictions. alternatively, use the model to classify new observations using the method.

creation

create a classificationknn model using fitcknn.

properties

knn properties

tie-breaking algorithm used by when multiple classes have the same smallest cost, specified as 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. breakties applies when includeties is false.

change breakties using dot notation: mdl.breakties = newbreakties.

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 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 of the same size containing nonnegative distance weights. for example, 'squaredinverse' is equivalent to @(d)d.^(–2).

change distanceweight using dot notation: mdl.distanceweight = newdistanceweight.

data types: char | function_handle

parameter for the distance metric, specified as one of the values described in this table.

distance metricparameter
'mahalanobis'positive definite covariance matrix c
'minkowski'minkowski distance exponent, a positive scalar
'seuclidean'vector of positive scale values with length equal to the number of columns of x

for any other distance metric, the value of distparameter must be [].

you can alter distparameter using dot notation: mdl.distparameter = newdistparameter. however, if distance is 'mahalanobis' or 'seuclidean', then you cannot alter distparameter.

data types: single | double

tie inclusion flag indicating whether includes all the neighbors whose distance values are equal to the kth smallest distance, specified as false or true. if includeties is true, predict includes all of these neighbors. otherwise, predict uses exactly k neighbors (see the breakties property).

change includeties using dot notation: mdl.includeties = newincludeties.

data types: logical

this property is read-only.

nearest neighbor search method, specified as either 'kdtree' or 'exhaustive'.

  • 'kdtree' — creates and uses a kd-tree to find nearest neighbors.

  • '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 value is 'kdtree' when x has 10 or fewer columns, x is not sparse, and the distance metric is a 'kdtree' type. otherwise, the default value is 'exhaustive'.

number of nearest neighbors in x used to classify each point during prediction, specified as a positive integer value.

change numneighbors using dot notation: mdl.numneighbors = newnumneighbors.

data types: single | double

other classification properties

this property is read-only.

categorical predictor indices, specified as a vector of positive integers. categoricalpredictors contains index values indicating that the corresponding predictors are categorical. the index values are between 1 and p, where p is the number of predictors used to train the model. if none of the predictors are categorical, then this property is empty ([]).

data types: double

this property is read-only.

names of the classes in the training data y with duplicates removed, specified as a categorical or character array, logical or numeric vector, or cell array of character vectors. classnames has the same data type as y. (the software treats string arrays as cell arrays of character vectors.)

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

cost of the misclassification of a point, specified as a square matrix. 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). the order of the rows and columns in cost corresponds to the order of the classes in classnames. the number of rows and columns in cost is the number of unique classes in the response.

by default, cost(i,j) = 1 if i ~= j, and cost(i,j) = 0 if i = j. in other words, the cost is 0 for correct classification and 1 for incorrect classification.

change a cost matrix using dot notation: mdl.cost = costmatrix.

data types: single | double

this property is read-only.

expanded predictor names, specified as a cell array of character vectors.

if the model uses encoding for categorical variables, then expandedpredictornames includes the names that describe the expanded variables. otherwise, expandedpredictornames is the same as predictornames.

data types: cell

this property is read-only.

parameters used in training the classificationknn model, specified as an object.

this property is read-only.

predictor means, specified as a numeric vector of length numel(predictornames).

if you do not standardize mdl when training the model using fitcknn, then mu is empty ([]).

data types: single | double

this property is read-only.

number of observations used in training the classificationknn model, specified as a positive integer scalar. this number can be less than the number of rows in the training data because rows containing nan values are not part of the fit.

data types: double

this property is read-only.

predictor variable names, specified as a cell array of character vectors. the variable names are in the same order in which they appear in the training data x.

data types: cell

prior probabilities for each class, specified as a numeric vector. the order of the elements in prior corresponds to the order of the classes in classnames.

add or change a prior vector using dot notation: mdl.prior = priorvector.

data types: single | double

this property is read-only.

response variable name, specified as a character vector.

data types: char

this property is read-only.

rows of the original training data used in fitting the classificationknn model, specified as a logical vector. this property is empty if all rows are used.

data types: logical

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

this table summarizes the available character vectors.

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

change scoretransform using dot notation: mdl.scoretransform = newscoretransform.

data types: char | function_handle

this property is read-only.

predictor standard deviations, specified as a numeric vector of length numel(predictornames).

if you do not standardize the predictor variables during training, then sigma is empty ([]).

data types: single | double

this property is read-only.

observation weights, specified as a vector of nonnegative values with the same number of rows as y. each entry in w specifies the relative importance of the corresponding observation in y.

data types: single | double

this property is read-only.

unstandardized predictor data, specified as a numeric matrix. each column of x represents one predictor (variable), and each row represents one observation.

data types: single | double

this property is read-only.

class labels, specified as a categorical or character array, logical or numeric vector, or cell array of character vectors. each value in y is the observed class label for the corresponding row in x.

y has the same data type as the data in y used for training the model. (the software treats string arrays as cell arrays of character vectors.)

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

hyperparameter optimization properties

this property is read-only.

cross-validation optimization of hyperparameters, specified as a bayesianoptimization object or a table of hyperparameters and associated values. this property is nonempty when the 'optimizehyperparameters' name-value pair argument is nonempty when you create the model using fitcknn. the value depends on the setting of the 'hyperparameteroptimizationoptions' name-value pair argument when you create the model:

  • 'bayesopt' (default) — object of class bayesianoptimization

  • 'gridsearch' or 'randomsearch' — table of hyperparameters used, observed objective function values (cross-validation loss), and rank of observations from lowest (best) to highest (worst)

object functions

compare accuracies of two classification models using new data
cross-validate machine learning model
edge of k-nearest neighbor classifier
gather properties of statistics and machine learning toolbox object from gpu
limelocal interpretable model-agnostic explanations (lime)
loss of k-nearest neighbor classifier
margin of k-nearest neighbor classifier
partialdependencecompute partial dependence
plotpartialdependencecreate partial dependence plot (pdp) and individual conditional expectation (ice) plots
predict labels using k-nearest neighbor classification model
resubstitution classification edge
resubstitution classification loss
resubstitution classification margin
classify training data using trained classifier
shapleyshapley values
compare accuracies of two classification models by repeated cross-validation

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.

tips

  • the compact function reduces the size of most classification models by removing the training data properties and any other properties that are not required to predict the labels of new observations. because k-nearest neighbor classification models require all of the training data to predict labels, you cannot reduce the size of a classificationknn model.

alternative functionality

finds the k-nearest neighbors of points. finds all the points within a fixed distance. you can use these functions for classification, as shown in . if you want to perform classification, then using classificationknn models can be more convenient because you can train a classifier in one step (using fitcknn) and classify in other steps (using ). alternatively, you can train a k-nearest neighbor classification model using one of the cross-validation options in the call to fitcknn. in this case, fitcknn returns a classificationpartitionedmodel cross-validated model object.

extended capabilities

version history

introduced in r2012a

see also

|

topics

    网站地图