最鄰近規則分類(K-Nearest Neighbor)KNN算法
阿新 • • 發佈:2018-08-23
bubuko rev created 換行 差值 code 是否 clas 分隔
自寫代碼:
1 # Author Chenglong Qian 2 3 from numpy import * #科學計算模塊 4 import operator #運算符模塊 5 6 def createDaraSet(): 7 group=array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])#創建4行2列的數組 8 labels=[‘A‘,"A",‘B‘,‘B‘]#標簽列表 9 return group,labels 10 11 group,labels=createDaraSet()12 13 ‘‘‘k—近鄰算法‘‘‘ 14 def classify0(inX,dataSet,labels,k): #inX:需要分類的向量,dataSet:訓練樣本,labels:標簽,k:臨近數目 15 ‘‘‘求距離‘‘‘ 16 dataSetSize=dataSet.shape[0] #樣本數據行數,即樣本的數量 17 diffMat=tile(inX,(dataSetSize,1))-dataSet #(來自numpy)tile:重復數組;將inX重復dataSetSize行,1列次;獲得每組數據的差值(Xi-X,Yi-Y) 18 sqDiffMat=diffMat**2 #求平方 19 sqDistances=sqDiffMat.sum(axis=1) #sum(axis=1)矩陣每一行相加,sum(axis=0)每一列相加 20 distances=sqDistances**0.5 #開根號 21 sortedDistIndicies=distances.argsort() #argsort()函數是將x中的元素從小到大排列,提取其對應的index(索引),然後輸出到y。 22 classCount={} 23 ‘‘‘排序‘‘‘ 24 for i in range(k):25 voteIlabel=labels[sortedDistIndicies[i]] #sortedDistIndicies[i]第i+1小元素的索引 26 classCount[voteIlabel]=classCount.get(voteIlabel,0)+1 #classCount.get(voteIlabel,0)返回字典classCount中voteIlabel元素對應的值,若無,則將其設為0 27 #這裏表示記錄某一標簽的數量 28 sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)#sorted(需要排序的list,key=自定義排序方式,是否反轉排序結果) 29 #items 將字典以列表形式返回 (python3.5中無 :iteritems將字典以叠代器形式返回) 30 #itemgetter函數用於獲取對象的第幾維的數據 operator.itemgetter(1)使用第二個元素進行排序 31 return sortedClassCount[0][0] 32 33 34 ‘‘‘把文本記錄轉換成矩陣Numpy的解析程序‘‘‘ 35 def file2matrix(filename): 36 fr=open(filename) 37 arrayOLines=fr.readlines() #readlines():返回由文件中剩余的文本(行)組成的列表 38 numberOfLines=len(arrayOLines) #返回對象的長度 39 returnMat=zeros((numberOfLines,3)) 40 classLabelVector=[] 41 index=0 42 for line in arrayOLines: 43 line=line.strip() #strip() 方法用於移除字符串頭尾指定的字符(默認為空格或換行符)或字符序列。 44 listFromLine=line.split(‘\t‘) #split() 通過指定分隔符對字符串進行切片 45 returnMat[index,:]=listFromLine[0:3] 46 classLabelVector.append(int(listFromLine[-1])) 47 index+=1 48 return returnMat,classLabelVector
庫代碼
1 from sklearn import neighbors 2 from sklearn import datasets 3 4 knn = neighbors.KNeighborsClassifier() 5 6 iris = datasets.load_iris() 7 8 print iris 9 10 knn.fit(iris.data, iris.target) 11 12 predictedLabel = knn.predict([[0.1, 0.2, 0.3, 0.4]]) 13 print "hello" 14 #print ("predictedLabel is :" + predictedLabel) 15 print predictedLabel
最鄰近規則分類(K-Nearest Neighbor)KNN算法