K-nn Algorithm

Source: Internet
Author: User

It was a bit hot today, and it was just a power outage again. When I had nothing to worry about, I realized the K-Nearest Neighbor Algorithm. The idea of the K-Nearest Neighbor Algorithm is to compare the features of new data to those of all samples one by one, and find the labels of K most similar data (the distance is the shortest, then, find the most tags in the K tags, that is, the tags of the new data. For details, see the K-Nearest Neighbor Algorithm.

The Code is as follows:

#-*-Coding: UTF-8-*-"created on Sun Jul 07 15:40:25 2013 @ Author: lming_08" Import numpy as nptrain_set_count = 16000 def create_dataset (file_name ): FD = open (file_name) lines = FD. readlines () # inst_count = Len (lines) # number of instances # vec_dimension = Len (lines [0]) # vector dimension class_label = [] # category label feature_vec_set = NP. zeros (train_set_count, 16), dtype = np.int) # feature vector SET Index = 0 for line in lines: If index> = Train_set_count: break line = line. strip () Data = line. split (",") class_label.append (data [0]) feature_vec_set [index,:] = [np.int (data [I]) for I in range (1, len (data)] index + = 1 # feature_vec_set is ndarray, and class_label is list return feature_vec_set, class_label def KNN (classification, feature_vec_set, class_label, k ): train_set_count = Len (class_label) dist_array = NP. zeros (train_set_count, 1), dtyp E = np.int) inx_repeat = NP. tile (sums, (train_set_count, 1) diff_array = inx_repeat-limit sqdiff_array = diff_array ** 2 dist_array = sqdiff_array.sum (axis = 1) # sum of each row sorted_index = sums () votelabel = [0] * 26 #26 letters correspond to 0 respectively... 25 For I in range (k): CH = class_label [sorted_index [I] # corresponding label votelabel [ord (CH)-65] = votelabel [ord (CH) -65] + 1 votelabel_min_index = votelabel. Index (max (votelabel) return CHR (votelabel_min_index + 65) If _ name _ = "_ main _": feature_vec_set, class_label = create_dataset (". /letter_recognition/letter_recognition.txt ") FD = open (". /letter_recognition/remain_4000rows.txt ") fd_result = open (". /letter_recognition/test_result.txt "," A ") lines = FD. readlines () test_count = 0 error_count = 0 for line in lines: test_count + = 1 line = line. stri P () Data = line. split (",") records = NP. array ([np.int (data [I]) for I in range (1, Len (data)]) CH = KNN (signature, feature_vec_set, class_label, 20) if line [0]! = CH: # print (U "Classification label is % C, and its actual label is % C" % (line [0], CH )) fd_result.write ("the label for classification is % C, and its actual label is % C \ n" % (line [0], CH )) error_count + = 1 print (U "test sample count: % d, error rate: % F" % (test_count, error_count/float (test_count) FD. close () fd_result.close ()

The training sample set used in the Code is from the machine learning data resources of the University of California Irwin, used to identify the letters of the dataset, see the http://archive.ics.uci.edu/ml/datasets/Letter+Recognition

The training sample set is the first 16000 rows of data in letletter_recognition.txt, And the last 4000 rows of data are used for testing.

Run the following code:

F: \ python_workspace> the number of samples tested by Python KNN. py is 4000, and the error rate is 0.073750.

You can see that the error rate is 7.375. then, you can download the test_result.txt file, as shown in the following section:

The classification label is g, and the actual label is C
The classification label is A, and the actual label is Y
The classification label is K, and the actual label is L
The classification label is P, and the actual label is H.
The classification label is h, and the actual label is B.
The classification label is K, and the actual label is g
The classification label is g, and the actual label is R.
The classification label is X, and the actual label is E.
The classification label is h, and the actual label is D.
The classification label is J, and the actual label is I
The classification label is E, and the actual label is g
The classification label is h, and the actual label is Y.
The classification label is d, and the actual label is B.
The classification label is N, and the actual label is D.
The classification label is h, and the actual label is Q.
The classification label is g, and the actual label is X
The classification label is h, and the actual label is K
The classification label is Q, and the actual label is o

...

The actual running process is slow because each test vector must be relatively close to each training sample vector, and the algorithm complexity is high.

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.