fit k-pg电子麻将胡了
fit k-nearest neighbor classifier
syntax
description
returns a k-nearest neighbor classification model based on
the input variables (also known as predictors, features, or attributes) in the
table mdl = fitcknn(tbl,responsevarname)tbl and output (response)
tbl.responsevarname.
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.mdl = fitcknn(___,name,value)
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.
train a k-nearest neighbor classifier using the minkowski metric
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 k-nearest neighbor classifier using custom distance metric
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
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 matrixz.compare
xto each row ofz.return a vector
dof length , where is the number of rows ofz. each element ofdis the distance between the observation corresponding toxand the observations corresponding to each row ofz.
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.
optimize fitted knn classifier
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 |


__________________________________________________________
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
tbl — sample data
table
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
tblcontains the response variable, and you want to use all remaining variables intblas predictors, then specify the response variable by usingresponsevarname.if
tblcontains the response variable, and you want to use only a subset of the remaining variables intblas predictors, then specify a formula by usingformula.if
tbldoes not contain the response variable, then specify a response variable by usingy. the length of the response variable and the number of rows intblmust be equal.
responsevarname — response variable name
name of variable in tbl
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
formula — explanatory model of response variable and subset of predictor variables
character vector | string scalar
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
y — class labels
categorical array | character array | string array | logical vector | numeric vector | cell array of character vectors
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
x — predictor data
numeric matrix
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.
breakties — tie-breaking algorithm
'smallest' (default) | 'nearest' | 'random'
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'
bucketsize — maximum data points in node
50 (default) | positive integer value
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
categoricalpredictors — categorical predictor flag
[] | 'all'
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),fitcknnassumes that a variable is categorical if it is a logical vector, categorical vector, character array, string array, or cell array of character vectors. iftblincludes both continuous and categorical values, then you must specify the value of'categoricalpredictors'so thatfitcknncan determine how to treat all predictors, as either continuous or categorical variables.if the predictor data is a matrix (
x),fitcknnassumes that all predictors are continuous. to identify all predictors inxas categorical, specify'categoricalpredictors'as'all'.
when you set categoricalpredictors to 'all',
the default distance is 'hamming'.
example: 'categoricalpredictors','all'
classnames — names of classes to use for training
categorical array | character array | string array | logical vector | numeric vector | cell array of character vectors
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
classnamesto specify the order of the dimensions ofcostor the column order of classification scores returned bypredict.select a subset of classes for training. for example, suppose that the set of all distinct class names in
yis["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 — cost of misclassification
square matrix | structure
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 classjif its true class isi(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 ofcost, additionally specify theclassnamesname-value pair argument.structure
shaving two fields:s.classnamescontaining the group names as a variable of the same type asy, ands.classificationcostscontaining 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
cov — covariance matrix
cov(x,'omitrows') (default) | positive definite matrix of scalar values
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 — 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' (default) | 'inverse' | 'squaredinverse' | 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.
| 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 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
exponent — minkowski distance exponent
2 (default) | positive scalar value
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
includeties — tie inclusion flag
false (default) | true
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
nsmethod — nearest neighbor search method
'kdtree' | 'exhaustive'
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 pointxnew, the software computes the distance values from all points inxtoxnewto 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'
numneighbors — number of nearest neighbors to find
1 (default) | positive integer value
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
predictornames — predictor variable names
string array of unique names | cell array of unique character vectors
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
xandy, then you can usepredictornamesto assign names to the predictor variables inx.the order of the names in
predictornamesmust correspond to the column order ofx. that is,predictornames{1}is the name ofx(:,1),predictornames{2}is the name ofx(:,2), and so on. also,size(x,2)andnumel(predictornames)must be equal.by default,
predictornamesis{'x1','x2',...}.
if you supply
tbl, then you can usepredictornamesto choose which predictor variables to use in training. that is,fitcknnuses only the predictor variables inpredictornamesand the response variable during training.predictornamesmust be a subset oftbl.properties.variablenamesand cannot include the name of the response variable.by default,
predictornamescontains the names of all predictor variables.a good practice is to specify the predictors for training using either
predictornamesorformula, but not both.
example: "predictornames",["sepallength","sepalwidth","petallength","petalwidth"]
data types: string | cell
prior — prior probabilities
'empirical' (default) | 'uniform' | vector of scalar values | structure
prior probabilities for each class, specified as the comma-separated
pair consisting of 'prior' and a value in this
table.
| value | description |
|---|---|
'empirical' | the class prior probabilities are the class relative frequencies
in y. |
'uniform' | all class prior probabilities are equal to 1/k, where k is the number of classes. |
| numeric vector | each element is a class prior probability. order the elements
according to 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
|
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
responsename — response variable name
"y" (default) | character vector | string scalar
response variable name, specified as a character vector or string scalar.
if you supply
y, then you can useresponsenameto specify a name for the response variable.if you supply
responsevarnameorformula, then you cannot useresponsename.
example: "responsename","response"
data types: char | string
scale — distance scale
std(x,'omitnan') (default) | vector of nonnegative scalar values
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
scoretransform — score transformation
"none" (default) | "doublelogit" | "invlogit" | "ismax" | "logit" | function handle | ...
score transformation, specified as a character vector, string scalar, or function handle.
this table summarizes the available character vectors and string scalars.
| value | description |
|---|---|
"doublelogit" | 1/(1 e–2x) |
"invlogit" | log(x / (1 – x)) |
"ismax" | sets the score for the class with the largest score to 1, and sets the scores for all other classes to 0 |
"logit" | 1/(1 e–x) |
"none" or "identity" | x (no transformation) |
"sign" | –1 for x < 0 0 for x = 0 1 for x > 0 |
"symmetric" | 2x – 1 |
"symmetricismax" | sets the score for the class with the largest score to 1, and sets the scores for all other classes to –1 |
"symmetriclogit" | 2/(1 e–x) – 1 |
for a matlab function or a function you define, use its function handle for the score transform. the function handle must accept a matrix (the original scores) and return a matrix of the same size (the transformed scores).
example: "scoretransform","logit"
data types: char | string | function_handle
standardize — flag to standardize predictors
false (default) | true
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
weights — observation weights
numeric vector of positive values | name of variable in tbl
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(,
where n,1)n is the number of observations in x or tbl.
data types: double | single | char | string
crossval — cross-validation flag
'off' (default) | 'on'
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'
cvpartition — cross-validation partition
[] (default) | cvpartition partition object
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.
holdout — fraction of data for holdout validation
scalar value in the range (0,1)
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:
randomly select and reserve
p*100% of the data as validation data, and train the model using the rest of the data.store the compact, trained model in the
trainedproperty 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
kfold — number of folds
10 (default) | positive integer value greater than 1
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:
randomly partition the data into
ksets.for each set, reserve the set as validation data, and train the model using the other
k– 1 sets.store the
kcompact, trained models in ak-by-1 cell vector in thetrainedproperty 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
leaveout — leave-one-out cross-validation flag
'off' (default) | 'on'
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:
reserve the one observation as validation data, and train the model using the other n – 1 observations.
store the n compact, trained models in an n-by-1 cell vector in the
trainedproperty 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'
optimizehyperparameters — parameters to optimize
'none' (default) | 'auto' | 'all' | string array or cell array of eligible parameter names | vector of optimizablevariable objects
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
optimizablevariableobjects, 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:
distance—fitcknnsearches among'cityblock','chebychev','correlation','cosine','euclidean','hamming','jaccard','mahalanobis','minkowski','seuclidean', and'spearman'.distanceweight—fitcknnsearches among'equal','inverse', and'squaredinverse'.exponent—fitcknnsearches among positive real values, by default in the range[0.5,3].numneighbors—fitcknnsearches among positive integer values, by default log-scaled in the range[1, max(2,round(numobservations/2))].standardize—fitcknnsearches 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'
hyperparameteroptimizationoptions — options for optimization
structure
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 name | values | default |
|---|---|---|
optimizer |
| 'bayesopt' |
acquisitionfunctionname |
acquisition functions whose names include
| 'expected-improvement-per-second-plus' |
maxobjectiveevaluations | maximum 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 | 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 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 |
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 at the command line:
for details, see the | 1 |
useparallel | logical value indicating whether to run bayesian optimization in parallel, which requires parallel computing toolbox™. due to the nonreproducibility of parallel timing, parallel bayesian optimization does not necessarily yield reproducible results. for details, see . | false |
repartition | logical value indicating whether to repartition the cross-validation at every
iteration. if this field is the setting
| false |
| use no more than one of the following three options. | ||
cvpartition | a cvpartition object, as created by cvpartition | 'kfold',5 if you do not specify a cross-validation
field |
holdout | a scalar in the range (0,1) representing the holdout fraction | |
kfold | an integer greater than 1 | |
example: 'hyperparameteroptimizationoptions',struct('maxobjectiveevaluations',60)
data types: struct
output arguments
mdl — trained k-nearest neighbor classification model
classificationknn model object | classificationpartitionedmodel cross-validated model
object
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:
find the
numneighborspoints in the training setxthat are nearest toxnew.find the
numneighborsresponse valuesyto those nearest points.assign the classification label
ynewthat has the largest posterior probability among the values iny.
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
nansors indicate missing observations. the following describes the behavior offitcknnwhen the data set or weights contain missing observations.if any value of
yor any weight is missing, thenfitcknnremoves those values fromy, the weights, and the corresponding rows ofxfrom the data. the software renormalizes the weights to sum to1.if you specify to standardize predictors (
'standardize',1) or the standardized euclidean distance ('distance','seuclidean') without a scale, thenfitcknnremoves 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, thenfitcknnremoves rows ofxthat contain at least one missing value. in other words, the software implements with the'omitrows'option on the predictor matrixx.
if you specify the
cost,prior, andweightsname-value arguments, the output model object stores the specified values in thecost,prior, andwproperties, respectively. thecostproperty stores the user-specified cost matrix as is. thepriorandwproperties store the prior probabilities and observation weights, respectively, after normalization. for details, see .the software uses the
costproperty for prediction, but not training. therefore,costis 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
priororweightsname-value pair argument, thenfitcknnstandardizes the predictors using their corresponding weighted means and weighted standard deviations. specifically,fitcknnstandardizes the predictor j using-
xjk is observation k (row) of predictor j (column).
-
if you also set
'distance','mahalanobis'or'distance','seuclidean', then you cannot specifyscaleorcov. instead, the software:computes the means and standard deviations of each predictor.
standardizes the data using the results of step 1.
computes the distance parameter values using their respective default.
if you specify
scaleand either ofpriororweights, then the software scales observed distances by the weighted standard deviations.if you specify
covand either ofpriororweights, then the software applies the weighted covariance matrix to the distances. in other words,
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
automatic parallel support
accelerate code by automatically running computation in parallel using parallel computing toolbox™.
to perform parallel hyperparameter optimization, use the
'hyperparameteroptimizationoptions', struct('useparallel',true)
name-value argument in the call to the fitcknn function.
for more information on parallel hyperparameter optimization, see .
for general information about parallel computing, see (parallel computing toolbox).
gpu arrays
accelerate code by running on a graphics processing unit (gpu) using parallel computing toolbox™.
usage notes and limitations:
by default,
fitcknnuses the exhaustive nearest neighbor search algorithm forgpuarrayinput arguments.you cannot specify the name-value argument
'nsmethod'as'kdtree'.you cannot specify the name-value argument
'distance'as a function handle.you cannot specify the name-value argument
'includeties'astrue.fitcknnfits the model on a gpu if either of the following apply:the input argument
xis agpuarrayobject.the input argument
tblcontainsgpuarraypredictor variables.
for more information, see run matlab functions on a gpu (parallel computing toolbox).
version history
introduced in r2014a
打开示例
您曾对此示例进行过修改。是否要打开带有您的编辑的示例?
matlab 命令
您点击的链接对应于以下 matlab 命令:
请在 matlab 命令行窗口中直接输入以执行命令。web 浏览器不支持 matlab 命令。
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.