1. 程式人生 > >機器學習實戰2--K近鄰

機器學習實戰2--K近鄰

本部落格基於機器學習實戰這本書,主要是對機器學習的演算法原理及python實現進行詳細解釋,若是有些沒有闡述清楚的,看到的請指出。
第二章的K近鄰演算法是一個簡單的機器學習演算法。
K近鄰演算法:
原理:收集一個樣本資料集合,並且樣本集中每個資料都存在標籤。輸入沒有標籤的新資料後,將新資料的每個特徵與樣本集中資料對應的特徵進行比較,然後演算法提取樣本集中特徵最相似資料(最近鄰)的分類標籤。選擇樣本資料集中前K個最相似的資料,這就是K近鄰演算法中K的出處,通常k是不大於20的整數。選擇k個最相似資料中出現次數最多的分類,作為新資料的分類。
演算法實現:新建一個kNN.py檔案
1. 匯入資料

#-*- coding: utf-8 -*-  #表示使用這個編碼
from numpy import * #匯入科學計算包NumPy,沒安裝趕緊百度安裝
import operator  #運算子模組,k近鄰演算法執行排序操作時將使用這個模組提供的函式
import pdb   #在Python互動環境中啟用除錯
from os import listdir # os 模組包含了許多對目錄操作的函式 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

儲存後import kNN
group,labels = kNN.createDataSet(),然後就可以得到group,labels

  1. 具體的kNN演算法:
    思想:計算已知類別資料集中的點和當前點之間的距離;
    按照距離遞增次序排序;
    選取與當前點距離最小的k個點;
    確定前k個點所在類別的出現頻率;
    返回前k個點出現頻率最高的類別作為當前點的預測分類。
 def classify0
(inX,dataSet,labels,k):
#inX是測試向量,dataSet是樣本向量,labels是樣本標籤向量,k用於選擇最近鄰居的數目 dataSetSize = dataSet.shape[0] #得到陣列的行數。即知道有幾個訓練資料,0是行,1是列 diffMat = tile(inX,(dataSetSize,1)) - dataSet #tile將原來的一個數組,擴充成了dataSetSize個一樣的陣列。diffMat得到了目標與訓練數值之間的差值。 sqDiffMat = diffMat**2 #各個元素分別平方 sqDistances = sqDiffMat.sum(axis=1) #就是一行中的元素相加 distances = sqDistances**0.5#開平方,以上是求出測試向量到樣本向量每一行向量的距離 sortedDistIndicies = distances.argsort()#對距離進行排序,從小到大 classCount={}#構造一個字典,針對前k個近鄰的標籤進行分類計數。 for i in range(k): voteIlabel = labels[sortedDistIndicies[i]] classCount[voteIlabel] = classCount.get(voteIlabel,0)+1#得到距離最小的前k個點的分類標籤 sortedClassCount = sorted(classCount.iteritems(),key = operator.itemgetter(1),reverse = True)#對classCount字典分解為元素列表,使用itemgetter方法按照第二個元素的次序對元組進行排序,返回頻率最高的元素標籤,計數前k個標籤的分類,返回頻率最高的那個標籤 return sortedClassCount[0][0]

這樣就可以使用該程式進行資料預測了。
kNN.classify0([0,0],group,labels,3)輸出結果為B。

  1. 測試kNN演算法
    這個測試是作者提供的文字檔案,先解析文字,畫二維擴散圖,kNN不用進行訓練,直接呼叫文字資料計算k近鄰就可以。
    將文字記錄轉換為NumPy的解析程式
def file2matrix(filename):#將文字記錄轉換成numpy的解析程式
    fr = open(filename) #這是python開啟檔案的方式
    arrayOLines = fr.readlines()#自動將檔案內容分析成一個行的列表
    numberOfLines = len(arrayOLines)#得到檔案的行數
    returnMat = zeros((numberOfLines,3))
    classLabelVector = []
        enumLabelVector = []
    index = 0
    for line in arrayOLines:
            line = line.strip()#截掉所有的回車符
            listFromLine = line.split('\t')#使用tab字元\t將上一步得到的整行資料分割成元素列表
            returnMat[index,:] = listFromLine[0:3]#選取前三個元素儲存到特徵矩陣中
            classLabelVector.append(listFromLine[-1])#用-1表示最後一列元素,把標籤放入這個向量中
            if cmp(listFromLine[-1],'didntLike')==0:
                enumLabelVector.append(1)
            elif cmp(listFromLine[-1],'smallDoses')==0:
                enumLabelVector.append(2)
            elif cmp(listFromLine[-1],'largeDoses')==0:
                enumLabelVector.append(3)
                index += 1
        return returnMat,enumLabelVector #返回資料矩陣和標籤向量

可以使用reload(kNN)
datingDataMat,datingLabels = kNN.file2matrix(‘datingTestSet.txt’)得到資料矩陣和標籤向量。

  1. 使用Matplotlib製作原始資料的散點圖
fig = plt.figure()
ax = fig.add_subplot(131)
ax.scatter(datingDataMat[:,1],datingDataMat[:,2])
ax = fig.add_subplot(132)
ax.scatter(datingDataMat[:,1],datingDataMat[:,2],15.0*array(vector),15.0*array(vector))
ax = fig.add_subplot(133)
ax.scatter(datingDataMat[:,0],datingDataMat[:,1],15.0*array(vector),15.0*array(vector))
plt.show()

這裡寫圖片描述

  1. 在計算KNN距離時,若某一列的數值遠大於其他列, 那這一列對計算距離時的影響最大。將資料歸一化,每一列的資料取值範圍處理為0-1之間,這樣每一列的資料對結果影響都一樣。
    歸一化特徵值:
def autoNorm(dataSet):
    minVals = dataSet.min(0)#獲得最小值,(0)是從列中獲取最小值,而不是當前行,就是每列都取一個最小值
    maxVals = dataSet.max(0)#獲得最大值
    ranges = maxVals - minVals#獲得取值範圍
    normDataSet = zeros(shape(dataSet))#初始化新矩陣
    m = dataSet.shape[0]#獲得列的長度
    normDataSet = dataSet - tile(minVals,(m,1))#特徵值是1000×3,而最小值和範圍都是1×3,用tile函式將變數內容複製成輸入矩陣一樣大小的矩陣
    normDataSet = normDataSet/tile(ranges,(m,1))#/可能是除法,在numpy中,矩陣除法要用linalg.solve(matA,matB).
    return normDataSet,ranges,minVals
  1. 將資料集分為測試資料和樣本資料
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)#前m×hoRatio個數據是測試的,後面的是樣本
        print "the calssifier 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))#最後打印出測試錯誤率
  1. 構建預測函式,輸入資訊得到預測標籤
#輸入某人的資訊,便得出對對方喜歡程度的預測值  
def classifyPerson():
    resultList = ['not at all', 'in small doses', 'in large doses'] 
    percentTats = float(raw_input("percentage of time spent playing video games?"))#輸入  
    ffMiles = float(raw_input("frequent flier miles earned per year?"))  
    iceCream = float(raw_input("liters of ice cream consumed per year?"))  
    datingDataMat, datingLabels = file2matrix('datingTestSet.txt') #讀入樣本檔案,其實不算是樣本,是一個標準檔案 
    normMat, ranges, minVals = autoNorm(datingDataMat)#歸一化
    inArr = array([ffMiles, percentTats, iceCream])#組成測試向量
#    pdb.set_trace()#可debug
    classifierResult = classify0((inArr-minVals)/ranges, normMat, datingLabels,3)#進行分類
#    return test_vec_g,normMat,datingLabels
    print 'You will probably like this person:', resultList[classifierResult - 1]#列印結果

在python下輸入kNN.classifyPerson(),輸入某人的資訊,就可以得到該人的標籤。
8.手寫識別系統的示例:
收集資料時,要將手寫的字元影象轉換成向量。

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')# 得到目錄下所有檔案的檔名
    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)#把標籤新增進list
        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)#對向量進行k近鄰測試
        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))

使用kNN.handwritingClassTest()測試該函式的輸出結果,依次測試每個檔案,輸出結果,計算錯誤率,因為分類演算法不是絕對的,只是一個概率問題,所以對每一組資料都有錯誤率。

至此,第二章基本闡述完畢,k近鄰演算法是分類資料最簡單有效的演算法,使用演算法時,我們必須有接近實際資料的訓練樣本資料。k近鄰演算法必須儲存全部資料集,如果訓練資料集很大的話,必須使用大量的儲存空間。
優點:精度高,對異常值不敏感,無資料輸入假定
缺點:nisan複雜度高,空間複雜度高。
適用資料範圍:數值型和標稱型。