1. 程式人生 > >kNN k近鄰演算法的python實現

kNN k近鄰演算法的python實現

Machine Learning in Action 這本書中演算法的實現 

#!/usr/bin/python
# -*- coding: utf-8 -*-
from numpy import*
import operator
import matplotlib
import matplotlib.pyplot as plt
from os import listdir
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
group,labels=createDataSet()
# print group,labels
def classify0(inX,dataSet,labels,k):#kNN演算法
    dataSetSize=dataSet.shape[0]
    diffMat=tile(inX,(dataSetSize,1))-dataSet
    # print diffMat
    sqDiffMat=diffMat**2
    sqDistances=sqDiffMat.sum(axis=1)
    # print sqDistances
    distances=sqDistances**0.5
    sortedDistIndicies=distances.argsort()
    #print distances,sortedDistIndicies
    classCount={}
    for i in range(k):
        voteIlabel=labels[sortedDistIndicies[i]]
        classCount[voteIlabel]=classCount.get(voteIlabel,0)+1
        # print classCount
    sortedClassCount=sorted(classCount.iteritems(),
                            key=operator.itemgetter(1),reverse=True)
    # print sortedClassCount
    return sortedClassCount[0][0]
def file2matrix(filename):   #從檔案讀資料
    fr=open(filename)
    arrayOLines=fr.readlines()#讀出每一行
    #print(arrayOLines)
    numberOfLines=len(arrayOLines)#行數
    returnMat=zeros((numberOfLines,3))#0矩陣Numpy
    classLabelVector=[]
    index=0
    for line in arrayOLines:
        line=line.strip() #去掉回車
        #print line
        listFromLine=line.split('\t')   #把整行資料分割為元素列表
        #print listFromLine
        returnMat[index,:]=listFromLine[0:3]
        classLabelVector.append(int(listFromLine[-1]))  #-1為最後一列
        index+=1
    return returnMat,classLabelVector
def autuNorm(dataSet): #資料正則化:new=(old-min)/(max-min)
    minVals=dataSet.min(0)
    maxVals=dataSet.max(0)
    #print maxVals
    ranges=maxVals-minVals
    normDataSet=zeros(shape(dataSet))
    m=dataSet.shape[0]
    normDataSet=dataSet-tile(minVals,(m,1))
    normDataSet=normDataSet/tile(ranges,(m,1))
    return normDataSet,ranges,minVals
def datingClassTest():   #測試訓練集精度
    hoRatio=0.10
    datingDataMat,datingLables=file2matrix('datingTestSet2.txt')
    normMat,ranges,minVals=autuNorm(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 "result: %d ,real: %d"\
              %(classifierResult,datingLabels[i])
        if(classifierResult!=datingLabels[i]):errorCount+=1.0
    print"error rates %f" %(errorCount/float(numTestVecs))
def img2vector(filename):  #將32*32的影象資料轉換為一行的向量
    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')
    m = len(trainingFileList)
    trainingMat = zeros((m,1024))
    for i in range(m):
        fileNameStr = trainingFileList[i]
        fileStr = fileNameStr.split('.')[0]
        classNumStr = int(fileStr.split('_')[0])
        hwLabels.append(classNumStr)
        trainingMat[i,:] = img2vector('trainingDigits/%s' % fileNameStr)
    testFileList = listdir('testDigits')
    errorCount = 0.0
    mTest = len(testFileList)
    for i in range(mTest):
        fileNameStr = testFileList[i]
        fileStr = fileNameStr.split('.')[0]
        classNumStr = int(fileStr.split('_')[0])
        vectorUnderTest = img2vector('testDigits/%s' % fileNameStr)
        classifierResult = classify0(vectorUnderTest, trainingMat, hwLabels, 3)
        print "the classifier came back with: %d, the real answer is: %d" % (classifierResult, classNumStr)
        if (classifierResult != classNumStr): errorCount += 1.0
    print "\nthe total number of errors is: %d" % errorCount
    print "\nthe total error rate is: %f" % (errorCount/float(mTest))
#print classify0([0,0],group,labels,3)
datingDataMat,datingLabels=file2matrix('datingTestSet2.txt')
# 畫出影象分析資料特徵
# fig=plt.figure()
# ax=fig.add_subplot(111)
# ax.scatter(datingDataMat[:,1],datingDataMat[:,2],15.0*array(datingLabels),
#            15.0*array(datingLabels))
# plt.show()

#datingClassTest()
handwritingClassTest()