2_5最近鄰算法kNN(k_nearest_neighbor)——classifyPerson_2_5

聲明:《機器學習實戰》代碼詳細註釋和重構,以及相關的函數、模塊和算法的解釋;本文爲博主原創文章,未經博主允許不得轉載。

  1. 約會網站預測函數(程序清單2-5)
    *#代碼:Peter Gong_shuai
    *#中文註釋:Gong_shuai
    *#代碼重構:Gong_shuai
    *#函數註解:Gong_shuai
    *#相關的函數、模塊和算法的解釋:Gong_shuai
    *#環境:Python2.7、Sublime Text3、mac

  2. 代碼

#coding=utf-8
#約會網站預測函數(程序清單2-5)

#源代碼:Peter  Gong_shuai
#中文註釋:Gong_shuai
#代碼重構:Gong_shuai
#函數註解:Gong_shuai
#環境:python2.7

from numpy import *
import operator
from os import listdir #函數listdir可以列出給定目錄的文件名


#處理輸入格式問題,輸入爲文件名字符串,輸出爲訓練樣本矩陣和類標籤向量
def file2matrix(filename):
    fr = open(filename)
    numberOfLines = len(fr.readlines())         #得到文本行數
    returnMat = zeros((numberOfLines,3))        #創建以零填充的矩陣,爲了簡化,另外的一個維度設爲3
    classLabelVector = []                       #返回標籤     
    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

#歸一化特徵值    
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))#注意事項:特徵值矩陣有1000*3個值。而minVals和range的值都爲1*3.爲了解決這個問題使用numpy中tile函數將變量內容複製成輸入矩陣同樣大小的矩陣  
    normDataSet = normDataSet/tile(ranges, (m,1))   #element wise divide矩陣除法
    return normDataSet, ranges, minVals

#k近鄰算法
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
    #選擇距離最小的k個點
    sortedDistIndicies = distances.argsort()     
    classCount={}          
    for i in range(k):
        voteIlabel = labels[sortedDistIndicies[i]]
        classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1
    #排序
    sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True)
    return sortedClassCount[0][0]

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("freguent flier miles earned per year?"))
    iceCream = float (raw_input("liters of ice cream consumed per year?"))
    datingDataMat,datingLabels = file2matrix('datingTestSet2.txt')
    normMat, ranges, minVals = autoNorm(datingDataMat)
    inArr = array([fffMiles, percentTats, iceCream])
    classifierResult = classifyO((inArr-\
                       minVals)/ranges,normMat,datingLabels,3)
    print "You will probably like this person: ", resultList[classifierResult - 1]

classifyPerson()

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