官方用書:機器學習實戰(Machine Learning in Action)
好了,下面繼續。
第2章主要講述了k臨近(k-NearestNeighbor)算法,所以關於算法本身的思想就不在贅述,不瞭解的同學請參考下面的百度百科鏈接:http://baike.baidu.com/link?url=k1Md78fE3ETrLyDYwL8-3 度孃的解釋已經很全面了,本編重點在書中例題的實現,和解釋。
2.1.1 準備:使用Python導入數據
首先創建一個名爲knn.py的文件,可以存放在電腦的任意位置,接下來打開knn.py 編寫我們的代碼。
from numpy import*
import operator
def createDataSet():
group=array([[1.0,1.0],[1.0,1.1],[0,0],[0,0.1]])
label=['A','A','B','B']
return group,label
如果有同學不瞭解numpy或者operator模塊的話,建議先百度一下,後面會有用(本博有關於operator的官方教程翻譯)。
接下來我們測試一下這個代碼:
打開終端,進入knn.py的文件目錄 再進入python
如果可以和圖片中的一樣順利運行的話,恭喜,knn.py已經完成。
2.1.2 實施knn算法
接下來我們在knn.py裏繼續編寫 ,我們要寫的是最主要的算法:knn算法
def classify0(inX,dataSet,labels,k):
dataSetsize=dataSet.shape[0]
diffMat=tile(inX,(dataSetsize,1))-dataSet
sqDiffMat=diffMat**2
sqDistance=sqDiffMat.sum(axis=1)
distance=sqDistance**0.5
sortedDistanceIndicies=distance.argsort()
classCount={}
for i in range(k):
voteIlabel=labels[sortedDistanceIndicies[i]]
classCount[voteIlabel]=classCount.get(voteIlabel,0)+1
sortedClassCount=sorted(classCount.iteritems(),key=operator.itemgetter(1),reverse=True)
return sortedClassCount[0][0]
這裏就用到了operator 和 numpy 庫裏的函數了,不瞭解的趕快去補補。
接下來我們測試一下:
from knn import*
group,label=createDataSet()
print classify0([0.5,0.5],group,label,3)
運行下來的結果應該是B吧,如果是B,那麼恭喜你,完成編寫!
通過上面,我們就實現了一個最簡單,最基礎的knn算法。
2.2.1 準備數據:從文件中解析數據
在knn.py中添加下面的代碼,使其可以從文件中讀入數據:
def filematrix(filename):
fin=open(filename)
arryofLines=fin.readlines()
numberofLines=len(arryofLines)
returnMat=zeros((numberofLines,3))
classLabelvector=[]
index=0
for line in arryofLines:
line=line.strip()
listFromLine=line.split('\t')
returnMat[index,:]=listFromLine[0:3]
classLabelvector.append(int(listFromLine[-1]))
index+=1
return returnMat.classLabelvector
可見使用python進行文件操作還是很方便的。