Chapter 2 - Classifying with k-Nearest Neighbors

Classifying with distance measurements

k-Nearest Neighbors

  • Pros: High accuracy, insensitive to outliers, no assumptions about data
  • Cons: Computationally expensive, requires a lot of memory
  • Works with: Numeric values, nominal values

The first machine-learning algorithm is k-Nearest Neighbors (kNN). When given a new piece of data, we compare the new piece of data with our training set. We look at the k most similar pieces of data and take a majority vote from the k pieces of data, and the majority is the new class we assign to the data we were asked to classify.

Prepare: importing data with Python

  • Create a Python module: kNN.py

    from numpy import *
    import operator
    
    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
    

Putting the kNN classification algorithm into action

  • Function classify0()

    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):
            voteIlabel = labels[sortedDistIndicies[i]]
            classCount[voteIlable] = classCount.get(voteIlable, 0) + 1
        sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True)
        return sortedClassCount[0][0]
    

How to test a classifier

Calculate error rate using test set.

Example: improving matches from a dating site with kNN

Prepare: parsing data from a text file

  • Function file2matrix()

    def file2matrix(filename):
        fr = open(filename)
        numberOfLines = len(fr.readlines())
        returnMat = zeros((numberOfLines, 3))
        classLabelVector = []
        fr = open(filename)
        index = 0
        labels = {'didntLike': 1, 'smallDoses': 2, 'largeDoses': 3}
        for line in fr.readlines():
            line = line.strip()
            listFromLine = line.split('\t')
            returnMat[index, :] = listFromLine[0:3]
            # value is converted to integer in the book, it doesn't work on my system
            classLabelVector.append(labels[listFromLine[-1]])
            index += 1
        return returnMat, classLabelVector
    

Analyze: creating scatter plot with Matplotlib

  • Plot the data in Python console

    >>> import matplotlib
    >>> import matplotlib.pyplot as plt
    >>> fig = plt.figure()
    >>> ax = fig.add_subplot(111)
    >>> ax.scatter(datingDataMat[:, 1], datingDataMat[:, 2])
    >>> plt.show()
    
  • Customize the markers

    ax.scatter(datingDataMat[:, 1], datingDataMat[:, 2], 15.0*array(datingLabels), 15.0*array(datingLabels))
    
Visualizing Data

Prepare: normalizing numeric values

When dealing with values that lie in different ranges, it's common to normalize them. Common ranges to normalize them to are 0 to 1 or -1 to 1.

  • Function autoNorm()

    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 division
        return normDataSet, ranges, minVals
    

    In Numpy, / operator stands for element-wise division. You need to use linalg.solve(matA, matB) for matrix division.

Test: testing the classifier as a whole program

To test the accuracy of the algorithm, we take 90% of the existing data to train the classifier. Then we take the remaining 10% to test the classifier and see how accurate it is. The 10% should be randomly selected. Our data isn't stored in a specific sequence, so you can take the first 10%.

  • Function datingClassTest()

    def datingClassTest():
        hoRatio = 0.10
        datingDataMat, datingLabels = file2matrix('datingTestSet.txt')
        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}'.format(classifierResult, datingLabels[i]))
            if classifierResult != datingLabels[i]:
                errorCount += 1.0
        print("The total error rate is: {:f}".format(errorCount / float(numTestVecs)))
    
  • Sample output

    >>> kNN.datingClassTest()
    The classifier came back with: 3, the real answer is: 3
    The classifier came back with: 2, the real answer is: 2
    The classifier came back with: 1, the real answer is: 1
    The classifier came back with: 1, the real answer is: 1
    The classifier came back with: 1, the real answer is: 1
    ...
    The classifier came back with: 2, the real answer is: 2
    The classifier came back with: 3, the real answer is: 3
    The classifier came back with: 2, the real answer is: 2
    The classifier came back with: 1, the real answer is: 1
    The classifier came back with: 3, the real answer is: 3
    The total error rate is: 0.050000
    

Use: putting together a useful system

Now that we've tested the classifier on our data, it's time to use it to actually classify people for Hellen. Hellen will find someone on the dating site and enter his information. The program predicts how much she'll like this person.

  • Function classifyPerson()

    def classifyPerson():
        resultList = ['not at all', 'in small doses', 'in large doses']
        percentTats = float(input('percentage of time spent playing video games?'))
        ffMiles = float(input('frequent flier miles earned per year?'))
        iceCream = float(input('liters of ice cream consumed per year?'))
        datingDataMat, datingLabels = file2matrix('datingTestSet.txt')
        normMat, ranges, minVals = autoNorm(datingDataMat)
        inArr = array([ffMiles, percentTats, iceCream])
        classifierResult = classify0((inArr-minVals)/ranges, normMat, datingLabels, 3)
        print("You will probably like this person: ", resultList[classifierResult - 1])
    

Example: a handwriting recognition system

Prepare: converting images into test vectors

We'll take the 32x32 matrix that is each binary image and make it a 1x1024 vector. After this, we can apply it to the existing classifier.

  • Function img2vector()

    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
    

Test: kNN on handwriting digits

  • Function handwritingClassTest()

    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}'.format(fileNameStr))
        testFileList = listdir('testDigits')
        errorCount = 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}'.format(fileNameStr))
            classifierResult = classify0(vectorUnderTest, trainingMat, hwLabels, 3)
            print("The classifier came back with: {:d}, the real answer is: {:d}".format(classifierResult, classNumStr))
            if classifierResult != classNumStr:
                errorCount += 1
        print("\nThe total number of errors is: {:d}".format(errorCount))
        print("\nThe total error rate is: {:f}".format(errorCount/float(mTest)))
    
  • Sample output

    >>> kNN.handwritingClassTest()
    The classifier came back with: 4, the real answer is: 4
    The classifier came back with: 4, the real answer is: 4
    The classifier came back with: 3, the real answer is: 3
    The classifier came back with: 9, the real answer is: 9
    The classifier came back with: 0, the real answer is: 0
    ..
    The classifier came back with: 1, the real answer is: 1
    The classifier came back with: 5, the real answer is: 5
    The classifier came back with: 4, the real answer is: 4
    The classifier came back with: 3, the real answer is: 3
    The classifier came back with: 3, the real answer is: 3
    
    The total number of errors is: 11
    
    The total error rate is: 0.011628
    

So many calculations make this algorithm pretty slow. This is a modification to kNN, called kD-trees, that allow us to reduce the number of calculations.

Summary

The k-Nearest Neighbors algorithm is a simple and effective way to classify data. kNN is an example of instance-based learning, where you need to have instances of data close at hand to perform the machine learning algorithm. In addition, you need to calculate the distance measurement for every piece of data in the database, and this can be cumbersome.

And additional drawback is that kNN doesn't give you any idea of the underlying structure of the data; you have no idea what an "average" or "examplar" instance from each class looks like. In the next chapter, we'll address this issue by exploring ways in which probability measurements can help you do classification.

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,791評論 6 545
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,795評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 178,943評論 0 384
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 64,057評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,773評論 6 414
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 56,106評論 1 330
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,082評論 3 450
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,282評論 0 291
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,793評論 1 338
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,507評論 3 361
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,741評論 1 375
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,220評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,929評論 3 351
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,325評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,661評論 1 296
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,482評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,702評論 2 380

推薦閱讀更多精彩內容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,417評論 0 10
  • 說不清楚是為什么突然就想把生活寫出來 可能就覺得生活走的太快了 人的記憶不夠容納 所以要找一個地方 把這些記憶存放...
    六月詔歌閱讀 233評論 0 0
  • 最早有印象的一條狗狗還是我幾歲的時候鄉上下來幾個打狗的活活的把我們的大狗給打死了,來哄我的小狗還說叔叔以后給捉一只...
    卍祝天下好人都平安卍閱讀 210評論 0 1
  • 《超級個體-伽藍214》405/500,12.22打卡,大晴天x2 【三件事】 1. [ ] 第一要務:展會概念功...
    伽藍214閱讀 235評論 0 0
  • 目標:到2018年5月7日,收入增加5萬元;意識狀態由己及人。 1.在智庫捐款2元。 感恩格西老師智慧的教導開啟我...
    晶晶_37cd閱讀 114評論 0 1