僅供參考,歡迎指正。
第一:
k近鄰算法的核心:訓練樣本集,並且樣本集中每個數據都存在標籤,即我們知道樣本集中每一數據與所屬分類的對應關係。輸人沒有標籤的新數據後,將新數據的每個特徵與樣本集中數據對應的 特徵進行比較,然後算法提取樣本集中特徵最相似數據(最近鄰)的分類標籤。
第二:
示例:使用K近鄰算法改進約會網站的配對效果
第一個 classify0 函數(該算法的核心)起到分類的作用;首先看有幾行,然後用tile函數(個人感覺這裏很關鍵,第一個是模型,然後時行數,重複次數),然後就是算他們之間的距離,從小到大排序後提取他們的原來的所用到sortedDistIndicies中。接下來的一個循環時選出前k項,然後這k項有重複的。在進行計數後,再生成新的字典。再排序。reverse默認升序operator.itemgetter函數獲取的不是值,而是定義了一個函數,通過該函數作用到對象上才能獲取值。取得第一維度的值。
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):
votellabel=labels[sortedDistIndicies[i]]
classCount[votellabel]=classCount.get(votellabel,0)
sortedClassCount = sorted(classCount.items(),key = operator.itemgetter(1),reverse = True)
return sortedClassCount[0][0]
第二個重要的函數 file2matrix 。它是將文件中的文本,轉換爲矩陣。
def file2matrix(filename):
fr=open(filename)
arrayOLines=fr.readlines()
numberOfLines=len(arrayOLines)
returnMat=zeros((numberOfLines,3))
classLabelVector=[]
index=0
for line in arrayOLines:
line = line.strip('\n')
listFromLine = line.split('\t')
returnMat[index,:]=listFromLine[0:3]
classLabelVector.append((int)(listFromLine[-1]))
index +=1
return returnMat,classLabelVector
第三個重要的就是 autoNorm 函數。它避免了三個特徵值影響差距較大,因爲,其中一項的數值較大,所以要歸一化。
def autoNorm(dataSet):
minVals=dataSet.min(0)
maxVals=dataSet.max(0)
ranges=minVals-maxVals
normDataSet=zeros(shape(dataSet))
m=dataSet.shape[0]
normDataSet=dataSet-tile(minVals,(m,1))
normDataSet=normDataSet/tile(ranges,(m,1))
return normDataSet,ranges,minVals
其他函數是建立在三個函數上,在此不說了。還有一個書寫數字識別時文本格式,個人認爲不太符合常規,且已用神經網絡實現,在此就不說了。