Description Usage Arguments Details Value Note Author(s) References See Also
Demonstrate the process of k-Nearest Neighbour classification on the 2D plane.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
train |
matrix or data frame of training set cases containing only 2 columns |
test |
matrix or data frame of test set cases. A vector will be
interpreted as a row vector for a single case. It should also contain only
2 columns. This data set will be ignored if |
cl |
factor of true classifications of training set |
k |
number of neighbours considered. |
interact |
logical. If |
tt.col |
a vector of length 2 specifying the colors for the training data and test data. |
cl.pch |
a vector specifying symbols for each class |
dist.lty, dist.col |
the line type and color to annotate the distances |
knn.col |
the color to annotate the k-nearest neighbour points using a polygon |
... |
additional arguments to create the empty frame for the animation
(passed to |
For each row of the test set, the k nearest (in Euclidean distance) training set vectors are found, and the classification is decided by majority vote, with ties broken at random. For a single test sample point, the basic steps are:
locate the test point
compute the distances between the test point and all points in the training set
find k shortest distances and the corresponding training set points
vote for the result (find the maximum in the table for the true classifications)
As there are four steps in an iteration, the total number of animation frames
should be 4 * min(nrow(test), ani.options('nmax'))
at last.
A vector of class labels for the test set.
There is a special restriction (only two columns) on the training and
test data set just for sake of the convenience for making a scatterplot.
This is only a rough demonstration; for practical applications, please
refer to existing kNN functions such as knn
in
class, etc.
If either one of train
and test
is missing, there'll be
random matrices prepared for them. (It's the same for cl
.)
Yihui Xie
Examples at https://yihui.org/animation/example/knn-ani/
Venables, W. N. and Ripley, B. D. (2002) Modern Applied Statistics with S. Fourth edition. Springer.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.