KNN algorithm parsing and java code and python code implementation

Source: Internet
Author: User

KNN (k Nearest Neighbors) is also called k's Nearest method. In general, kNN is a relatively easy-to-understand algorithm. Assume that each class contains multiple sample data, in addition, each data has a unique class tag indicating which category the samples belong to. kNN is used to calculate the distance from each sample data to the data to be classified, if k samples closest to the data to be classified are used, the majority of samples in which k samples belong to this category. The basic idea of this algorithm is: after a new text is given, consider K pieces of text closest (most similar) to the new text in the training text set, determine the category of the new text based on the category of the K text. The specific algorithm is as follows: step one: calculate the distance from each test tuples to each sample tuples, select k step two for the most recent (or most similar) tuples: Calculate the category of the tuples from k candidate tuples. Which category is more, determine whether the test tuples are implemented in this java version: package cluster; public class KNNNode {private int index; // The private double distance of the tuples; // The distance from the test tuples to private String c; // category public KNNNode (int index, double distance, String c) {// super (); this. index = index; t His. distance = distance; this. c = c;} public int getIndex () {return index;} public void setIndex (int index) {this. index = index;} public double getDistance () {return distance;} public void setDistance (double distance) {this. distance = distance;} public String getC () {return c;} public void setC (String c) {this. c = c ;}} package cluster; import java. util. list; import java. util. arrayList; import java. util. com Parator; import java. util. map; import java. util. hashMap; // use of hashMap import java. util. priorityQueue;/*** KNN is calculated in only two steps. For each test tuples, calculate the nearest k training tuples. * Based on the K training tuples obtained in the previous step, select the test tuples * @ author chenjinandy **/public class KNN {/*** for sorting PriorityQueue, in ascending or descending order, this example is an internal class of the descending order * Comaprator. It is similar to the meaning of the cmp function in c ++ and tells the comparison method, is sorted in descending order */private Comparator <KNNNode> comparator = new Comparator <KNNNode> () {public int compare (KNNNode o1, KNNNode o2) {if (o1.getDistance () >= o2.getDistance () {return 1 ;}else {return 0 ;}}}; /*** random number generation function, which generates random integers with different K values. The range is 0-max. * a k-sized linked list is generated. The content of the linked list is Integer, the value is a random non-repeated value */public List <Integer> getRandKNum (int k, int max) {www.2cto. comList <Integer> rand = new ArrayList <Integer> (k); for (int I = 0; I <k; I ++) {int temp = (int) (Math. random () * max); if (! Rand. contains (temp) rand. add (temp); elsei --;} return rand;}/*** calculates the distance between two tuples. All tuples are data lists, use square Euclidean distance to express the distance * @ param d1 * @ param d2 * @ return */public double calDistance (List <Double> d1, List <Double> d2) // d1 is the sample of the test ancestor {double distance = 0.0; for (int I = 0; I <d1.size (); I ++) {distance + = (d1.get (I) -d2.get (I) * (d1.get (I)-d2.get (I); // returns distance from the square Euclidean distance};}/*** dates is the training tuples, testdate is the test tuples, and K is the k parameter in KNN, that is, the number of * @ param dates * @ p closest to each selected Aram testdate * @ param k * @ return */public String knn (List <Double> dates, List <Double> testdate, int k) {/** the following process is the process of initializing a priority queue. First, construct a data set whose values are not greater than the size of the Training tuples. random Number of size () */PriorityQueue <KNNNode> pq = new PriorityQueue <KNNNode> (k, comparator); List <Integer> randNum = getRandKNum (k, dates. size (); // you can replace 0-K-1 only for the initial preparation of an pq. // randNum contains k random values for (int I = 0; I <k; I ++) {int index = randNum. get (I); List <Double> curr Data = dates. get (index); String c = currData. get (currData. size ()-1 ). toString (); KNNNode node = new KNNNode (index, calDistance (testdate, currData), c); pq. add (node); // This is only the ancestor of the initialization pq. In fact, it is all right. After comparison, add}/** priorityQueue usage. during initialization, determine the size and comparison type, comparator, which is gradually reduced in this example. Therefore, the maximum distance between the chain header and the parent * is used to calculate the distance between the current test tuples and each training tuples. If the distance is smaller than the maximum distance in the priority queue, replace it with */for (int I = 0; I <dates. size (); I ++) {List <Double> t = dates. get (I); // gradually compare the distance between the training ancestor and testdata with the maximum distance in pq. If the distance is smaller If it is larger, double distance = calDistance (testdate, t) is not considered. // The distance between the training ancestor and the test ancestor is KNNNode node = pq. peek (); // query the elements in the returned queue header. At this time, if (distance <node. getDistance () {pq. remove (); pq. add (new KNNNode (I, distance, t. get (t. size ()-1 ). toString (); // when the distance between the training ancestor record and the test ancestor is smaller than the maximum distance in the queue, It is selected} return getMostClass (pq );} /** the PriorityQueue operation is performed by the value of */private String getMostClass (PriorityQueue <KNNNode> pq) {Map <String, Integer> count = new HashMap <String, Integer> (); // use hashMap to calculate the for (int I = 0; I <pq. size (); I ++) // construct a hashMap for the class attribute of all tuples in the priority queue {KNNNode node = pq. remove (); String c = node. getC (); if (count. containsKey (c) {count. put (c, count. get (c) + 1); // the key value of HashMap cannot be repeated} else {count. put (c, 1); // Add a new key-value} int maxIndex =-1; int maxCount = 0; // The HashMap operation does not have get (I) for the serial number, but only the operation for the key value, so get keys first // keySet () obtain the key value sequence of hashmap Object [] classes = count. KeySet (). toArray (); for (int I = 0; I <classes. length; I ++) {if (count. get (classes [I])> maxCount) {maxIndex = I; maxCount = count. get (classes [I]);} return classes [maxIndex]. toString () ;}} package cluster; import java. io. bufferedReader; import java. io. file; import java. io. fileReader; import java. util. arrayList; import java. util. list; public class TestKNN {public void read (List <Double> datas, String path) {try {Buf FeredReader br = new BufferedReader (new FileReader (new File (path); String data = br. readLine (); List <Double> l = null; while (data! = Null) {String t [] = data. split (""); l = new ArrayList <Double> (); for (int I = 0; I <t. length; I ++) {l. add (Double. parseDouble (t [I]);} datas. add (l); data = br. readLine () ;}} catch (Exception e) {e. printStackTrace () ;}} public void printtestdate (List <Double> testdate) {for (int I = 0; I <testdate. size (); I ++) System. out. print (testdate. get (I) + "");} public static void main (String args []) {TestKNN tknn = new TestKNN (); String path1 = "TestSet/KNN/dates.txt "; string path2 = "TestSet/KNN/testdate.txt"; List <Double> dates = new ArrayList <List <Double> (); list <Double> testdate = new ArrayList <List <Double> (); try {tknn. read (dates, path1); tknn. read (testdate, path2); KNN knn = new KNN (); for (int I = 0; I <dates. size (); I ++) {List <Double> tdata = dates. get (I); System. out. print ("training tuples:"); tknn. printtestdate (tdata); System. out. println (""); // System. out. println (knn. knn (dates, tdata, 3);} for (int I = 0; I <testdate. size (); I ++) {List <Double> tdata = testdate. get (I); System. out. print ("test tuples:"); tknn. printtestdate (tdata); System. out. println ("category:"); System. out. println (Math. round (Float. parseFloat (knn. knn (dates, tdata, 3);} catch (Exception e) {e. printStackTrace () ;}} python version #-*-coding: gb2312-*-import math import string # Calculate the euclidean distance between v1 and v2 def euclidean (v1, v2 ): d = 0.0 for I in range (len (v1): d + = (v1 [I]-v2 [I]) ** 2 return math. sqrt (d) # calculate the distance between vec1 and all data, and sort def getdistances (data, vec1): # data = getVlist (data) # vec1 = getVlist (vec1) distancelist = [] for I in range (len (data): vec2 = data [I] distancelist. append (euclidean (vec1, vec2), data [I] [8]) distancelist. sort () return distancelist # training tuples indicate vlist1 = ["1.0 1.1 1.2 2.1 0.3 2.3 1.4 0.5 1.7 1", "1.2 1.4 2.0 0.2 2.5 1.2 0.8 1 ", "1.2 1.8 1.6 2.5 0.1 2.2 1.8 0.2 1", "1.9 2.1 6.2 1.1 0.9 3.3 2.4 5.5 0", "1.0 0.8 1.6 2.1 0.2 2.3 1.6 0.5 1 ", "1.6 2.1 5.2 1.1 0.8 3.6 2.4 4.5 0"] # test the tuples that indicate vlist2 = ["1.0 1.1 1.2 2.1 0.3 2.3 1.4 0.5 ", "1.7 1.2 1.4 2.0 0.2 2.5 1.2 0.8 1.2", "1.8 1.6 2.5 0.1 2.2 1.8 0.2 1.9", "2.1 6.2 1.1 0.9 3.3 2.4 5.5 ", "1.0 0.8 1.6 2.1 0.2 2.3 1.6 0.5 1.6", "2.1 5.2 1.1 0.8 3.6 2.4 4.5"] # Train tuples and test the data processing methods of tuples, convert the character query to floatdef getfloat (varr): varrlist = [] for varrelem in varr: # print float (varrelem) varrlist. append (float (varrelem) return varrlist def getVlist (vlist): v_list = [] for v in vlist: varr = v. split ("") v_list.append (getfloat (varr) return v_list vlist1 = getVlist (vlist1) # Process training tuples into float arrays vlist2 = getVlist (vlist2) # obtain the category def getClasses (distance, k): classes ={} for I in range (k): dis = distance [I] if classes. _ contains _ (dis [1]): dnum = classes. get (dis [1]) + 1 del classes [dis [1] classes. setdefault (dis [1], int (dnum) else: classes. setdefault (dis [1], 1) dicnum = 0 classnum =-1 # the following code finds the largest number of classes for dic in classes: # print dic www.2cto.com if classes. get (dic)> = dicnum: dicnum = classes. get (dic) classnum = dic return int (classnum) def knn (vlist1, vlist2): for v2 in vlist2: distancelist = getdistances (vlist1, v2) print "test tuples" print v2 print 'category 'print getClasses (distancelist, 3) knn (vlist1, vlist2)

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.