《機器學習實戰》終於到手了,開始學習了。由於本人python學的比較挫,所以學習筆記里會有許多python的內容。
1、 python及其各種插件的安裝
由於我使用了win8.1 64位系統(正版的哦),所以像numpy 和 matploblib這種常用的插件不太好裝,解決方案就是Anaconda-2.0.1-Windows-x86_64.exe 一次性搞定。
2、kNN代碼
1 #-*-coding:utf-8-*- 2 from numpy import * 3 import operator 4 5 def createDataSet(): 6 group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]]) 7 labels = ['A','A','B','B'] 8 return group,labels 9 10 def classify0(inX,dataSet,labels,k): 11 dataSetSize = dataSet.shape[0] 12 diffMat = tile(inX,(dataSetSize,1))-dataSet 13 sqDiffMat = diffMat ** 2 14 sqDistances = sqDiffMat.sum(axis = 1) 15 distances = sqDistances ** 0.5 16 sortedDistIndicies = distances.argsort() #indices 17 classCount = {} 18 for i in range(k): 19 voteIlabel = labels[sortedDistIndicies[i]] 20 classCount[voteIlabel] = classCount.get(voteIlabel,0)+1 21 #找出最大的那個 22 sortedClassCount = sorted(classCount.iteritems(), 23 key = operator.itemgetter(1),reverse = True) 24 return sortedClassCount[0][0]
這里的疑惑主要出現在:
(1)array與list有什么區別
array 是numpy里面定義的。為了方便計算,比如
1 array([1,2])+array([3,4]) 2 [1,2]+[3,4]
執行以下就可以知道他們的差別了
(2)shape[0]返回的是哪一維度的大小(不要嘲笑我小白,我真的不知道)
找到文檔看了一下就開朗了。ndarray.shape “the dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension. For a matrix with n rows and m columns, shape will be (n,m). The length of the shape tuple is therefore the rank, or number of dimensions, ndim.”
(3)tile函數
tile函數是經常使用的函數,用於擴充array。舉例:
1 >>> b = np.array([[1, 2], [3, 4]]) 2 >>> np.tile(b, 2) 3 array([[1, 2, 1, 2], 4 [3, 4, 3, 4]]) 5 >>> np.tile(b, (2, 1)) 6 array([[1, 2], 7 [3, 4], 8 [1, 2], 9 [3, 4]])
這下就懂了吧。為什么要用這個函數呢?因為后面兩個array要做差,這樣做就可以不用使用循環了,典型的空間換時間。那么為什么要做差呢?好吧,因為這是knn算法。
(4)array的sum函數
寫到這里,我決定要好好讀讀numpy文檔了。
numpy.sum(a, axis=None, dtype=None, out=None, keepdims=False)
一個sum函數還是挺麻煩的呢
>>> np.sum([[0, 1], [0, 5]], axis=0) array([0, 6]) >>> np.sum([[0, 1], [0, 5]], axis=1) array([1, 5])
這樣大家都清楚了
(5) 最后一行,return了什么?
表面看起來像是二維數組的第一個元素,但是sortedClassCount是二維數組嗎?
寫了一個小的驗證程序,發現sortedClassCount是一個list,元素是tuple。
L = {1:12,3:4} sortedL = sorted(L.iteritems(),key=operator.itemgetter(1)) print sortedL #結果 [(3, 4), (1, 12)]