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
breakties
— tie-breaking algorithm
'smallest'
(default) | 'nearest'
| 'random'
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
— distance metric
'cityblock'
| 'chebychev'
| 'correlation'
| 'cosine'
| 'euclidean'
| 'hamming'
| function handle | ...
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
).
nsmethod | distance metric names |
---|---|
exhaustive | any distance metric of |
kdtree | 'cityblock' , 'chebychev' , 'euclidean' ,
or 'minkowski' |
this table includes valid distance metrics of .
distance metric names | description |
---|---|
'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). |
@ |
distance function handle. function d2 = distfun(zi,zj) % calculation of distance ...
|
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
distanceweight
— distance weighting function
'equal'
| 'inverse'
| 'squaredinverse'
| function handle
distance weighting function, specified as one of the values in this table.
value | description |
---|---|
'equal' | no weighting |
'inverse' | weight is 1/distance |
'squaredinverse' | weight is 1/distance2 |
@ | fcn 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
distparameter
— parameter for distance metric
positive definite covariance matrix | positive scalar | vector of positive scale values
parameter for the distance metric, specified as one of the values described in this table.
distance metric | parameter |
---|---|
'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
includeties
— tie inclusion flag
false
(default) | true
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
nsmethod
— nearest neighbor search method
'kdtree'
| 'exhaustive'
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 pointxnew
, the software computes the distance values from all points inx
toxnew
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'
.
numneighbors
— number of nearest neighbors
positive integer value
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
categoricalpredictors
— categorical predictor indices
[]
| vector of positive integers
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
classnames
— names of classes in training data y
categorical array | character array | logical vector | numeric vector | cell array of character vectors
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
— cost of misclassification
square matrix
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
expandedpredictornames
— expanded predictor names
cell array of character vectors
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
modelparameters
— parameters used in training classificationknn
object
this property is read-only.
parameters used in training the classificationknn
model, specified as an object.
mu
— predictor means
numeric vector
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
numobservations
— number of observations
positive integer scalar
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
predictornames
— predictor variable names
cell array of character vectors
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
— prior probabilities for each class
numeric vector
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
responsename
— response variable name
character vector
this property is read-only.
response variable name, specified as a character vector.
data types: char
rowsused
— rows used in fitting
[]
| logical vector
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
scoretransform
— score transformation
'none'
(default) | 'doublelogit'
| 'invlogit'
| 'ismax'
| 'logit'
| function handle | ...
score transformation, specified as either a character vector or a function handle.
this table summarizes the available character vectors.
value | description |
---|---|
"doublelogit" | 1/(1 e–2x) |
"invlogit" | log(x / (1 – x)) |
"ismax" | sets the score for the class with the largest score to 1, and sets the scores for all other classes to 0 |
"logit" | 1/(1 e–x) |
"none" or "identity" | x (no transformation) |
"sign" | –1 for x < 0 0 for x = 0 1 for x > 0 |
"symmetric" | 2x – 1 |
"symmetricismax" | sets the score for the class with the largest score to 1, and sets the scores for all other classes to –1 |
"symmetriclogit" | 2/(1 e–x) – 1 |
for a matlab® function or a function you define, use its function handle for 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
sigma
— predictor standard deviations
numeric vector
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
w
— observation weights
vector of nonnegative values
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
x
— unstandardized predictor data
numeric matrix
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
y
— class labels
categorical array | character array | logical vector | numeric vector | cell array of character vectors
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
hyperparameteroptimizationresults
— cross-validation optimization of hyperparameters
bayesianoptimization
object | table
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 classbayesianoptimization
'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 | |
lime | local interpretable model-agnostic explanations (lime) |
loss of k-nearest neighbor classifier | |
margin of k-nearest neighbor classifier | |
partialdependence | compute partial dependence |
plotpartialdependence | create 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 | |
shapley | shapley values |
compare accuracies of two classification models by repeated cross-validation |
examples
train k-nearest neighbor classifier
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 aclassificationknn
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
c/c code generation
generate c and c code using matlab® coder™.
usage notes and limitations:
the function supports code generation.
when you train a k-nearest neighbor classification model by using
fitcknn
, the following restrictions apply.the value of the
'distance'
name-value pair argument cannot be a custom distance function.the value of the
'distanceweight'
name-value pair argument can be a custom distance weight function, but it cannot be an anonymous function.the value of the
'scoretransform'
name-value pair argument cannot be an anonymous function.
for more information, see introduction to code generation.
gpu arrays
accelerate code by running on a graphics processing unit (gpu) using parallel computing toolbox™.
usage notes and limitations:
the following object functions fully support gpu arrays:
the following object functions offer limited support for gpu arrays:
the object functions execute on a gpu if either of the following apply:
the model was fitted with gpu arrays.
the predictor data that you pass to the object function is a gpu array.
for more information, see run matlab functions on a gpu (parallel computing toolbox).
version history
introduced in r2012a
打开示例
您曾对此示例进行过修改。是否要打开带有您的编辑的示例?
matlab 命令
您点击的链接对应于以下 matlab 命令:
请在 matlab 命令行窗口中直接输入以执行命令。web 浏览器不支持 matlab 命令。
select a web site
choose a web site to get translated content where available and see local events and offers. based on your location, we recommend that you select: .
you can also select a web site from the following list:
how to get best site performance
select the china site (in chinese or english) for best site performance. other mathworks country sites are not optimized for visits from your location.
americas
- (español)
- (english)
- (english)
europe
- (english)
- (english)
- (deutsch)
- (español)
- (english)
- (français)
- (english)
- (italiano)
- (english)
- (english)
- (english)
- (deutsch)
- (english)
- (english)
- switzerland
- (english)
asia pacific
- (english)
- (english)
- (english)
- 中国
- (日本語)
- (한국어)