[Python] Implements KNN algorithm

Source: Internet
Author: User

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

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.