# ALGORITHM:K-NN (nearest neighbor classification algorithm)
# AUTHOR:KERMIT.L
# time:2016-8-7
#==============================================================================
From numpy Import *
Import operator
Import Matplotlib.pyplot as Plt
Def creatdataset ():
Group = Array ([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]])
Labels = [' A ', ' a ', ' B ', ' B ']
Return Group,labels
Group,labels = Creatdataset ()
Plt.figure (1)
Plt.plot (group[:,0],group[:,1], ' or ')
Plt.xlim (-0.5, 1.5)
Plt.ylim (-0.5, 1.5)
Plt.grid ()
For I in Xrange (Group.shape[0]):
Plt.text (Group[i][0]-0.06,group[i][1],labels[i])
Plt.show ()
def classify0 (InX, DataSet, labels, k):
Datasetsize = dataset.shape[0]
Diffmat = Tile (InX, (datasetsize,1))-DataSet;
Sqdiffmat = Diffmat * * 2
Sqdistance = sqdiffmat.sum (axis = 1)
Distance = sqdistance * * 0.5
Sortdistanceindex = Distance.argsort ()
ClassCount ={}
For I in Xrange (k):
Votelabel = Labels[sortdistanceindex[i]]
Classcount[votelabel] = Classcount.get (votelabel,0) + 1
Sortedclasscount = sorted (Classcount.iteritems (), key = Operator.itemgetter,
Reverse = True)
return sortedclasscount[0][0]
# Print Sortdistanceindex
# Sqdiffmat = diffmat.sum (AXS = 1)
# Print Sqdiffmat
# distance = Sqdiffmat * * 0.5
InX =[0.8,0.6]
Print Classify0 (InX, Group, labels, 2)
K-NN (nearest neighbor classification algorithm python