1. 程式人生 > >k近鄰分類演算法的python實踐

k近鄰分類演算法的python實踐

最近學習機器學習演算法,用python實現。

這裡記錄k近鄰演算法的python原始碼實現和一些理解。

文章參考了zouxy09的博文,程式碼參考machine learning in action.

k近鄰分類演算法原理:

1、根據k近鄰,計算K個離待分類物品最近的物品,這K個最近的物品已經分類。

2、統計K個近鄰的分類結果,按照降序排列。

3、分類結果值最大的,即是待分類物品類別。

程式碼如下(根據手寫數字0-9,判斷未知手寫數字的分類):

#!/usr/bin/env python
# coding=utf-8

'''
Created on Sep 16, 2010
kNN: k Nearest Neighbors

Input:      inX: vector to compare to existing dataset (1xN)
            dataSet: size m data set of known vectors (NxM)
            labels: data set labels (1xM vector)
            k: number of neighbors to use for comparison (should be an odd number)
            
Output:     the most popular class label

@author: pbharrin
'''

from numpy import *
import operator
from os import listdir

#每個dataSet陣列元素,對應一個labels陣列元素,根據K鄰域分類
#k應該是奇數,偶數不好比較。舉例:分類結果A:2;B:2.就不能正確分類了
def classify0(inX, dataSet, labels, k):
    dataSetSize = dataSet.shape[0]
    diffMat = tile(inX, (dataSetSize,1)) - dataSet  #待分類陣列與所有訓練集陣列
    sqDiffMat = diffMat**2                          
    sqDistances = sqDiffMat.sum(axis=1)
    distances = sqDistances**0.5                    #計算歐氏距離
    sortedDistIndicies = distances.argsort()        #距離排序:升序
    classCount={}          
    for i in range(k):                              #最近3個檔案,對應的分類
        voteIlabel = labels[sortedDistIndicies[i]]  #sorted後的索引,與排序前索引對應關係
        classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1
    sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
    return sortedClassCount[0][0]

def createDataSet():
    group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
    labels = ['A','A','B','B']
    return group, labels

def file2matrix(filename):
    fr = open(filename)
    numberOfLines = len(fr.readlines())         #get the number of lines in the file
    returnMat = zeros((numberOfLines,3))        #prepare matrix to return
    classLabelVector = []                       #prepare labels return   
    fr = open(filename)
    index = 0
    for line in fr.readlines():
        line = line.strip()
        listFromLine = line.split('\t')
        returnMat[index,:] = listFromLine[0:3]
        classLabelVector.append(int(listFromLine[-1]))
        index += 1
    return returnMat,classLabelVector
    
def autoNorm(dataSet):
    minVals = dataSet.min(0)
    maxVals = dataSet.max(0)
    ranges = maxVals - minVals
    normDataSet = zeros(shape(dataSet))
    m = dataSet.shape[0]
    normDataSet = dataSet - tile(minVals, (m,1))
    normDataSet = normDataSet/tile(ranges, (m,1))   #element wise divide
    return normDataSet, ranges, minVals
   
def datingClassTest():
    hoRatio = 0.50      #hold out 10%
    datingDataMat,datingLabels = file2matrix('datingTestSet2.txt')       #load data setfrom file
    normMat, ranges, minVals = autoNorm(datingDataMat)
    m = normMat.shape[0]
    numTestVecs = int(m*hoRatio)
    errorCount = 0.0
    for i in range(numTestVecs):
        classifierResult = classify0(normMat[i,:],normMat[numTestVecs:m,:],datingLabels[numTestVecs:m],3)
        print("the classifier came back with: %d, the real answer is: %d" % (classifierResult, datingLabels[i]))
        if (classifierResult != datingLabels[i]): errorCount += 1.0
    print("the total error rate is: %f" % (errorCount/float(numTestVecs)))
    print(errorCount)
    
def img2vector(filename):
    returnVect = zeros((1,1024))
    fr = open(filename)
    for i in range(32):
        lineStr = fr.readline()
        for j in range(32):
            returnVect[0,32*i+j] = int(lineStr[j])
    return returnVect

def handwritingClassTest():
    hwLabels = []
    trainingFileList = listdir('trainingDigits')           #load the training set
    m = len(trainingFileList)
    trainingMat = zeros((m,1024))
    for i in range(m):
        fileNameStr = trainingFileList[i]
        fileStr = fileNameStr.split('.')[0]     #take off .txt
        classNumStr = int(fileStr.split('_')[0])
        hwLabels.append(classNumStr)            #檔案名錶示已分類標籤
        trainingMat[i,:] = img2vector('trainingDigits/%s' % fileNameStr)
        
    testFileList = listdir('testDigits')        #iterate through the test set
    errorCount = 0.0
    mTest = len(testFileList)
    for i in range(mTest):
        fileNameStr = testFileList[i]
        fileStr = fileNameStr.split('.')[0]     #take off .txt
        classNumStr = int(fileStr.split('_')[0])    #測試檔案的已分類標籤
        vectorUnderTest = img2vector('testDigits/%s' % fileNameStr)
        classifierResult = classify0(vectorUnderTest, trainingMat, hwLabels, 3) #訓練集已對應分類,求測試集分類結果
        if (classifierResult != classNumStr): 
            print("the classifier came back with: %d, the real answer is: %d" % (classifierResult, classNumStr))
            errorCount += 1.0
    print("\n the total number of errors is: %d" % errorCount)
    print("\n the total error rate is: %f" % (1-errorCount/float(mTest)))
    
handwritingClassTest();

這裡主要用到了函式handwritingClassTest(),classify0,img2vector

handwritingClassTest:真個演算法組織管理

classify0:分類主函式,比較待分類物品與已分類函式,根據K近鄰,給出分類結果

img2vector:讀取檔案內容

注意事項:

1、K近鄰分類,需要計算待分類物品與所有已分類物品的距離才能計算結果,計算量大。

2、分類結果與K取值相關,不同K值對應不同的分類結果。

3、樣本不平衡時,分類結果容易傾向於大樣本分類集合。

參考文章:

1、http://blog.csdn.net/zouxy09/article/details/16955347

2、machine learning in action