1. 程式人生 > >Machine Learning in Action-chapter2-k近鄰算法

Machine Learning in Action-chapter2-k近鄰算法

turn fma 全部 pytho label -c log eps 數組

一.numpy()函數

1.shape[]讀取矩陣的長度

例:

import numpy as np
x = np.array([[1,2],[2,3],[3,4]])
print x.shape         //輸出行列數 (3,2)
print x.shape[0]    //輸出行數 3
print x.shape[1]    //輸出列數 2

2.tile()函數

形式為tile(A,reps)

reps的數字從後往前分別對應A的第N個維度的重復次數。如tile(A,2)表示A的第一個維度重復2遍,tile(A,(2,3))表示A的第一個維度重復3遍,然後第二個維度重復2遍,tile(A,(2,2,3))表示A的第一個維度重復3遍,第二個維度重復2遍,第三個維度重復2遍。

例:

A=[1,2]
print ‘-----------tile(A,2)--------------‘
print tile(A,2)
print ‘-----------tile(A,(2,2))----------‘
print tile(A,(2,2))
print ‘-----------tile(2,2,3)------------‘
print tile(A,(2,2,3))

  輸出結果為:

技術分享

3.sum()函數

沒有axis參數表示全部相加,axis=0表示按列相加,axis=1表示按照行的方向相加

例:

import numpy as np
x = np.array([[1,2,3],[4,5,6]])
k = x.sum()
k0 = x.sum(axis=0)
k1 = x.sum(axis=1)
print k
print k0
print k1

  輸出結果為:

技術分享

4.argsort()函數

返回的是數組值從小到大的索引值

例:>>> x = np.array([3, 1, 2])
>>> np.argsort(x)
array([1, 2, 0])

-------------------------------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
    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)
#sortedClassCount = sorted(classCount.iteritems(), key=lambda classCount:classCount[1], reverse=True) return sortedClassCount[0][0]

  

inX:輸入向量

dataSet:訓練樣本

labels:標簽向量

Machine Learning in Action-chapter2-k近鄰算法