Skip to main content
. 2021 Jul 19;12(7):838. doi: 10.3390/mi12070838
Algorithm 1. Pseudo-code for the k-NN Algorithm.
Input:
X: training data
Y: class labels of X
x: unknown sample
S: instance set
k: number of nearest neighbor
Output: predicted class label
1: //train phase
2: for i = 1 to length(X) do
3:   Store training instance X[i], class label Y[i] into instance set S[i]
4: end for
5:
6: //inference phase
7: for i = 1 to length(X) do
8:   Calculate distance between the unknown sample and the stored training instance d(X[i], x)
9:   Store calculated distance values into D
10: end for
11:
12: Find k minimum distance values
13: Vote which class is the most among k minimum distance values
14:
15: Return the class that has been voted by the majority