KNN算法的总结

来源:互联网 发布:阿里云访问页面很慢 编辑:程序博客网 时间:2024/05/23 19:39

kNN是一种非常有效且简单的分类算法,我用了三个小时把其理论和实践都作了一遍,在这里总结一下。

一: kNN算法的一般流程

       (1)收集数据:使用任何方法,你多能想到的,这是第一步

        (2)准备数据:距离计算所需要的数值,最好是结构化的数据格式

         (3)分析数据:使用任何方法

         (4)训练算法:kNN就不用了

          (5)测试算法:计算错误率

           (6)使用算法:就是用你自己的数据来测试

二:kNN算法的实践

      1:首先建立一个kNN.py的脚本文件,里面主要有两个函数组成,一个是用来生成小数据库,另一个是用来分类的

               

  1. # kNN: k Nearest Neighbors  
  2.   
  3. # Input:      newInput: vector to compare to existing dataset (1xN)  
  4. #             dataSet:  size m data set of known vectors (NxM)  
  5. #             labels:   data set labels (1xM vector)  
  6. #             k:        number of neighbors to use for comparison   
  7.               
  8. # Output:     the most popular class label  
  9. #########################################  
  10.   
  11. from numpy import *  
  12. import operator  
  13.   
  14. # create a dataset which contains 4 samples with 2 classes  
  15. def createDataSet():  
  16.     # create a matrix: each row as a sample  
  17.     group = array([[1.0, 0.9], [1.0, 1.0], [0.1, 0.2], [0.0, 0.1]])  
  18.     labels = ['A', 'A', 'B', 'B'] # four samples and two classes  
  19.     return group, labels  
  20.   
  21. # classify using kNN  
  22. def kNNClassify(newInput, dataSet, labels, k):  
  23.     numSamples = dataSet.shape[0] # shape[0] stands for the num of row  
  24.   
  25.     ## step 1: calculate Euclidean distance  
  26.     # tile(A, reps): Construct an array by repeating A reps times  
  27.     # the following copy numSamples rows for dataSet  
  28.     diff = tile(newInput, (numSamples, 1)) - dataSet # Subtract element-wise  
  29.     squaredDiff = diff ** # squared for the subtract  
  30.     squaredDist = sum(squaredDiff, axis = 1) # sum is performed by row  
  31.     distance = squaredDist ** 0.5  
  32.   
  33.     ## step 2: sort the distance  
  34.     # argsort() returns the indices that would sort an array in a ascending order  
  35.     sortedDistIndices = argsort(distance)  
  36.   
  37.     classCount = {} # define a dictionary (can be append element)  
  38.     for i in xrange(k):  
  39.         ## step 3: choose the min k distance  
  40.         voteLabel = labels[sortedDistIndices[i]]  
  41.   
  42.         ## step 4: count the times labels occur  
  43.         # when the key voteLabel is not in dictionary classCount, get()  
  44.         # will return 0  
  45.         classCount[voteLabel] = classCount.get(voteLabel, 0) + 1  
  46.   
  47.     ## step 5: the max voted class will return  
  48.     maxCount = 0  
  49.     for key, value in classCount.items():  
  50.         if value > maxCount:  
  51.             maxCount = value  
  52.             maxIndex = key  
  53.   
  54.     return maxIndex   

2.我们接下来需要进行测试

  1. import kNN  
  2. from numpy import *   
  3.   
  4. dataSet, labels = kNN.createDataSet()  
  5.   
  6. testX = array([1.2, 1.0])  
  7. k = 3  
  8. outputLabel = kNN.kNNClassify(testX, dataSet, labels, 3)  
  9. print "Your input is:", testX, "and classified to class: ", outputLabel  
  10.   
  11. testX = array([0.1, 0.3])  
  12. outputLabel = kNN.kNNClassify(testX, dataSet, labels, 3)  
  13. print "Your input is:", testX, "and classified to class: ", outputLabel
会输出
  1. Your input is: [ 1.2  1.0] and classified to class:  A  
  2. Your input is: [ 0.1  0.3] and classified to class:  B 
这是kNN最基本的理论方法和简单实践,接下来我也将学习一下kNN的进阶知识


原创粉丝点击