機器學習實戰系列2——KNN(近鄰)算法

定義

採用不同特徵值之間的距離方法進行分類
優點:精度高、對異常值不敏感、無數據輸入假定
缺點:計算複雜度高、空間複雜度高
適用:數值型與標稱型數據

算法概述

給定一個訓練集(其中的實例類別已定),對新的輸入實例(無標籤),比較新實例特徵與樣本集中的特徵,在訓練數據集中找到與該實例中最鄰近的K個實例,這K個實例的多數屬於那個類,就把該輸入實例分爲這個類(K<=20)
輸入:實例的特徵向量
輸出:實例的類別
三要素:K值的選擇,距離度量、分類決策規則——對特徵空間的劃分
1.K值的選擇——交叉驗證法。較小、較大分別影響,近似誤差、估計誤差
2.距離度量
3.分類決策規則——多數表決

僞代碼

對未知類別屬性的數據集中的每個點依次執行以下操作

  1. 計算已知類別數據集中的點與當前點之間的距離(特徵值之間的距離)
  2. 按照距離遞增次序排序
  3. 選取與當前點距離最小的前K個點
  4. 確定前K個點所在類別出現的頻率
  5. 返回前K個點出現頻率最高的類別作爲當前點的預測分類

python代碼示例(將每組數據劃到某個類中)

場景1:電影分類

通過統計電影中打鬥次數與接吻次數來區分動作與愛情片

場景2:改進約會網站

3個特徵

場景3:改進手寫數字識別系統——在圖像上應用KNN

32*32黑白圖像轉換成1024的向量

'''
Created on Sep 20, 2018
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

'''
from numpy import *
import operator  #運算符模塊
from os import listdir
import matplotlib
import matplotlib.pyplot as plt


# 創建數據集與標籤
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

#kNN分類器
def classify0(inX, dataSet, labels, k):#inX待分類數據集
    dataSetSize = dataSet.shape[0] #4行,每行是個樣本
    #使用歐式距離計算距離
    diffMat = tile(inX, (dataSetSize,1)) - dataSet #tile()函數是將待分類數據集重複幾行幾次,與樣本集矩陣一樣大小,方便相減
    sqDiffMat = diffMat**2 #取平方
    sqDistances = sqDiffMat.sum(axis=1) #按列求和
    distances = sqDistances**0.5
    sortedDistIndicies = distances.argsort() #argsort()將distances 中的元素從小到大排列,並返回其對應的索引
    classCount={}          #字典,前k個標籤及次數
    for i in range(k):
        voteIlabel = labels[sortedDistIndicies[i]] #返回距離最近的K的標籤
        classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1 #如果當前標籤不存在,則創建並設置值爲0;存在就加1;// Python 字典(Dictionary) get() 函數返回指定鍵的值,如果值不在字典中返回默認值
    sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
    #items() 函數以列表返回可遍歷的(鍵, 值) 元組數組
    #operator模塊提供的itemgetter函數用於獲取對象的哪些維的數據
    #reverse=True降序排列,默認爲升序排列
    #sortedClassCount是個列表,元素爲元組(標籤,次數)
    return sortedClassCount[0][0] #返回頻率最高的元素的標籤,第一個元組的第一個元素

#處理數據的輸入格式問題
#讀取文件,返回訓練樣本矩陣和類別標籤向量
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




#不同特徵值取值範圍幅度大,數值歸一化,將取值範圍歸一化到0到1或者-1到1之間
#newvalue=(oldvalue-min)/(max-min)    
    
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.10      #hold out 10%
    datingDataMat,datingLabels = file2matrix('datingTestSet2.txt')       #load data setfrom file
    normdatingDataMat, ranges, minVals = autoNorm(datingDataMat)
    m = normdatingDataMat.shape[0]
    numTestVecs = int(m*hoRatio)
    errorCount = 0.0 #錯誤計數器變量
    for i in range(numTestVecs):
        classifierResult = classify0(normdatingDataMat[i,:],normdatingDataMat[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 classifyPerson():
    resultList=['not at all','in small doses','in large doses']
    
    ffMiles=float(input("frequent flier miles earned per year?"))
    percentTats=float(input("percentage of time spent  playing video games?"))
    iceCream=float(input("liters of ice cream consumed per year?"))
    datingDataMat,datingLabels=file2matrix("datingTestSet2.txt")
    normMat,ranges,minVals=autoNorm(datingDataMat)
    inArr=array([ffMiles,percentTats,iceCream])
    classifierResult=classify0((inArr-minVals)/ranges,normMat,datingLabels,3)
    print("you will probabaly like this person: ",resultList[classifierResult-1])
    
    
 
#手寫數字識別
#將圖像格式化處理爲一個向量32*32變成1*1024的向量

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(r'I:\study\nlp\機器學習實戰源碼\MLiA_SourceCode\machinelearninginaction\Ch02\digits\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('I:/study/nlp/機器學習實戰源碼/MLiA_SourceCode/machinelearninginaction/Ch02/digits/trainingDigits/%s' % fileNameStr)
    testFileList = listdir(r'I:\study\nlp\機器學習實戰源碼\MLiA_SourceCode\machinelearninginaction\Ch02\digits\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('I:/study/nlp/機器學習實戰源碼/MLiA_SourceCode/machinelearninginaction/Ch02/digits/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)))


if __name__ == '__main__':
    group, labels=createDataSet() 
    sortedClassCount=classify0([0,0], group, labels, 4)
    
    datingDataMat,datingLabels=file2matrix(r'I:\study\nlp\機器學習實戰源碼\MLiA_SourceCode\machinelearninginaction\Ch02\datingTestSet2.txt')
   
    #分析約會數據:使用matplotlib創建散點圖
    fig=plt.figure()
    ax=fig.add_subplot(111)
    #不同興趣愛好的人類別也不一樣
    ax.scatter(datingDataMat[:,0],datingDataMat[:,1],15.0*array(datingLabels),15.0*array(datingLabels)) #使用約會數據的第1列與第2列數據
    plt.show()
    
    normdatingDataSet, ranges, minVals=autoNorm(datingDataMat)
    
    datingClassTest() #約會網站性能
    
    classifyPerson()  #約會網站測試
    
    
    testVector=img2vector(r'I:\study\nlp\機器學習實戰源碼\MLiA_SourceCode\machinelearninginaction\Ch02\digits\trainingDigits\2_0.txt')
    #圖片轉換爲向量
   
    handwritingClassTest() #手寫數字測試

#總結
1.先將訓練集變成矩陣形式,一行代表一個樣本(創建0矩陣,再往裏填充)
標籤變成列表的形式
2.KNN針對大數據集,存儲空間大,需計算新樣例與所有樣本的距離,耗時;另外,無法給出任何數據的基礎結構信息(含有什麼特徵)——概率測量方法可以解決這個問題(決策樹)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章