K-NN (nearest neighbor classification algorithm python

Source: Internet
Author: User

# 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.