KNN演算法及python問題
阿新 • • 發佈:2019-02-11
機器學習實戰之KNN
創造資料集
from numpy import *
import operator
def createDataSet():
group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
labels = ['A','A','B','B']
return group,labels
創造一個4*2的array,數值可理解為座標,label就是對應分類
python時間
tile
tile的作用是把一個矩陣複製出一個新的矩陣,如A是一個矩陣
tile(A,1) = A
tile(A,2,3)就是把A作為一個元素,複製成新的2 *3的矩陣,每一個元素就是一個A
shape
shape是獲取矩陣的size的函式
A = [1,2,3;4,5,6;7,8,9]
A.shape = (3,3)
A.shape[0] = A.shape[1] = A.shape[2] = 3
argsort
argsort是一個排序後獲取下標的函式
A = [5,4,3,1,2]
B = A.argsort() = [3,4,2,1,0]
itemgetter
itemgetter是operator的一個函式
b=operator.itemgetter(n-1)
b成為獲取物件第n個元素的函式
A = [1 ,2,3]
b(A) = 2
axis
axis是表示矩陣的行列的
a = [1,2,3; 4,5,6]
axis預設為0,表示列
a.sum() = 21
a.sum(axis=0) = [5,7,9] 列求和
a.sum(axis=1) = [6,15] 行求和
dict.get
python中的字典dict,獲取對應值有兩種方式
1. key2 = dict[key1] ,但是假如字典不存在key1會發生錯誤
2. key2 = dict.get(key1,default) 當不存在key1,返回預設值default
完整程式碼及註釋
py import *
import operator
def createDataSet():
group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
labels = ['A','A','B','B']
return group,labels
#上面函式是根據已有的資料,創造資料集
def classify0(inX,dataSet,labels,k):
#inX是待分類的資料,dataSet是已知的資料集,labels是已知資料集的分類,k是演算法抽取的最相鄰點的數量
dataSetSize = dataSet.shape[0]
#獲取dataSet的點的個數
diffMat = tile(inX,(dataSetSize,1)) - dataSet
#tile函式把待分類點組成一個n維向量,再和原有資料集每個點作差
#相當於,得到(x-x1),(x-x2),(x-x3)···
sqDiffMat = diffMat ** 2
#(x-x1)^2 ···
sqDistances = sqDiffMat.sum(axis=1)
#各個維度的差的平方求和
distances = sqDistances ** 0.5
#和開方最終得到歐式距離
sortedDistIndicies = distances.argsort()
#根據求得的距離進行排序,並得到對應的資料集的下標
classCount = {}
#新建字典,放置距離小的資料的標籤及其對應數量
for i in range(k):
#放置距離小的前K個點
voteIlabel = labels[sortedDistIndicies[i]]
#根據下標得到當前這個資料點的label
classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1
#字典中label對應值+1
sortedClassCount = sorted(classCount.iteritems(),key=operator.itemgetter(1),reverse=True)
#根據字典的key2進行排序
sorted classCount
return sortedClassCount[0][0]
#排序產生的是一個列表,列表的元素是一個tuple
#返回出現最多的標籤,也就是最終分類結果