機器學習筆記:K-最近鄰算法

K-最近鄰算法(k-Nearest Neighbors)

KNN基本思想

計算輸入值的座標與當前所有點的座標距離(利用歐幾里得距離),將這些距離保存在一個遞增的列表裏,獲取k個最小的距離的值,在這些值中找到最主要的分類,即出現次數最多的類別,這個類別就是要預測的輸入值的類別。

General approach to kNN

  1. Collect: Any method.
  2. Prepare: Numeric values are needed for a distance calculation. A structured dataformat is best.
  3. Analyze: Any method.
  4. Train: Does not apply to the kNN algorithm.
  5. Test: Calculate the error rate.
  6. Use: This application needs to get some input data and output structured num-eric values. Next, the application runs the kNN algorithm on this input data and determines which class the input data should belong to. The application then takes some action on the calculated class.

練習舉例

產生如下圖座標所示的數據
這裏寫圖片描述

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

numpy 是python的一個第三方庫,開源,可以快速處理數據,尤其是對大型矩陣計算性能優異。
簡單實現kNN算法:

import operator
def classify0(inX, dataSet, labels, k):
    #區一維數組長度
    dataSetSize = dataSet.shape[0] 

    #計算距離
    # tile()的用法參考:http://blog.csdn.net/april_newnew/article/details/44176059
    diffMat = np.tile(inX, (dataSetSize,1))-dataSet   
    #用歐幾里得距離(歐氏距離)計算距離
    sqDiffMat = diffMat**2                            
    sqDistances = sqDiffMat.sum(axis=1)           
    distances = sqDistances**0.5      
    # argsort()返回數組從小到大排列後的索引            
    sortedDistIndicies = distances.argsort() 
    classCount={} 
    for i in range(k):
        voteIlabel = labels[sortedDistIndicies[i]]                  
        classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1   

    # iteritems()迭代函數,獲取鍵值對
    # itemgetter() 用於獲取對象的哪些維的數據,參數爲一些序號
    sortedClassCount = sorted(classCount.items(),      
                   key=operator.itemgetter(1), reverse=True) 
    return sortedClassCount[0][0]

調用測試:

print(classify0([0.6,0.8], createDataSet()[0],createDataSet()[1], 3))

輸入值爲[0.6,0.8],取k=3,結果爲A
輸入值爲[0.3,0.5],取k=3,結果爲B

歐幾里得距離(歐氏距離)計算距離

對於二維座標,假設有兩個點(xA0,xB0),(xA1,xB1) ,它們之間的距離爲

d=(xA1xA0)2+(xB1xB0)2

例如計算(0,0),(1,2)的距離,套公式爲
d=(10)2+(20)2

如果是多維座標,就針對對應的維相減再平方求和,例如計算(1,0,0,1)和(7,6,8,4)之間的距離,套公式如下:

d=(71)2+(60)2+(80)2+(41)2

補充

當存在其中某一樣本類數據計算得到的距離有較大差異的時候,需要進行數據規範化,縮放之後使數值在某一範圍內達到統一,這個範圍一般是0~1,或者-1~1,縮放的公式如下:

newValue=oldValueminmaxmin

最小值min,最大值max

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