File Exchange

image thumbnail

k-Nearest Neighbors (kNN) Algorithm

version 2.1.8 (21.8 KB) by David Ferreira
Complete package

54 Downloads

Updated 17 Feb 2019

GitHub view license on GitHub

Function
1. predict_knn
2. find_knn
3. plot_knn

Description
1. Returns the estimated labels of one or multiple test instances and the accuracy of the estimates.
2. Returns the k nearest training instances, the k nearest training labels and the respective distances.
3. Creates a graphic highlighting the nearest training instances (For plotting, instances must have only two or three features (2-D or 3-D)).

Examples using Iris Data Set
load fisheriris
X = meas;
Y = species;
Xnew = [min(X);mean(X);max(X)];
k = 5;
label = predict_knn(X,Y,Xnew,k)

label =

'setosa'
'versicolor'
'virginica'


Ynew = {'versicolor';'versicolor';'virginica'};
[label,accuracy] = predict_knn(X,Y,Xnew,k,Ynew)

label =

'setosa'
'versicolor'
'virginica'

accuracy =

0.6667

See more examples described in the script files.

Cite As

David Ferreira (2019). k-Nearest Neighbors (kNN) (https://www.mathworks.com/matlabcentral/fileexchange/67018-k-nearest-neighbors-knn), MathWorks. Retrieved January 23, 2019.

Comments and Ratings (2)

Updates

2.1.8

Find function added

2.1.7

Description correction

2.1.6

Description correction

2.1.5

Description correction

2.1.4

Description correction

2.1.3

3-D chart added and cell type label support.

2.1.2

The plotting 3-D function was added in the main algorithm.

2.1.1

More markers were added to the chart.

2.1.0

The plotting function was added in the main algorithm.

2.0.9

Function Pack

2.0.8

Title correction

2.0.7

Title correction

2.0.6

Added to github.

2.0.5

New tools have been added, bringing a more complete algorithm.

2.0.4

Simplification in k nearest instances and k nearest labels

2.0.3

Basic update

2.0.2

Update in maximum frequency

2.0.1

Simplification in frequency verification

2.0.0

Check the frequencies using 'histcounts'

1.62

Title correction

1.61

Correction of the k nearest labels.

1.60

Returns the k nearest labels.

1.54

Basic update

1.53

Updating the Euclidean distance between two points

1.52

Description correction

1.51

Description correction

1.5

Elements sorted by "sort" function and reduced processing time by approximately 1/3.

1.1.0.0

Update of the calculation of the Euclidean distance between two points

1.0.0.0

Description correction

1.0.0.0

It was added the verification of the dimensions of the matrices.

MATLAB Release Compatibility
Created with R2015a
Compatible with any release
Platform Compatibility
Windows macOS Linux