One, the code for writing knn.py files in Pycharm 5.0.4 (IDE writing Python program)
--------------------------
1. knn.py operator Module
--------------------------
1 fromNumPyImport*2 Importoperator3 4#运算符模块 Create datasets and labels5 defCreateDataSet ():6Group = Array ([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]])7Labels = ['A','A','B','B']8 returnGroup, labels
1), open command line
First enter the knn.py folder, in the knn.py process, the effect as shown
--------------------------
2. knn.py k-Nearest neighbor algorithm
--------------------------
1 fromNumPyImport*2 Importoperator3 4#运算符模块5 defCreateDataSet ():6Group = Array ([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]])7Labels = ['A','A','B','B']8 returnGroup, Labels9 Ten#k-Nearest Neighbor algorithm This module needs to use the group/labels of the operator module One defclassify0 (InX, DataSet, labels, k): ADatasetsize =Dataset.shape[0] -Diffmat = Tile (InX, (datasetsize, 1))-DataSet -Sqdiffmat = Diffmat * * 2 theSqdistances = Sqdiffmat.sum (Axis=1) -distances = sqdistances * * 0.5 -Sorteddistindicies =Distances.argsort () -ClassCount = {} + forIinchRange (k): -Voteilabel =Labels[sorteddistindicies[i]] +Classcount[voteilabel] = classcount.get (Voteilabel, 0) + 1 A atSortedclasscount =Sorted (Classcount.iteritems (), -Key=operator.itemgetter (1), -Reverse=True) - returnSORTEDCLASSCOUNT[0][0]
2) on the basis of 1), the contents of 2) can be modified by the parameters
[Python] Implements KNN algorithm