Machine Learning in Action_CH2_1_kNN

来源:互联网 发布:java poi maven 编辑:程序博客网 时间:2024/05/22 16:04
from numpy import *import operatordef createDataBase():    group = array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]]) # numpy向量    labels = ['A', 'A', 'B', 'B'] # 列表    return group, labelsdef classify0(inX, dataSet, labels, k):    dataSetSize = dataSet.shape[0] # 获得向量第一维长度    diffMat = tile(inX, (dataSetSize, 1)) - dataSet # 纵向扩大dataSetSize倍    sqDiffMat = diffMat ** 2    sqDistances = sqDiffMat.sum(axis = 1) # 按行求和    distances = sqDistances ** 0.5    sortedDistIndicies = distances.argsort() # 从小到大排序,返回的是索引值的列表    classCount = {} # python字典    for i in range(k):        voteIlabel = labels[sortedDistIndicies[i]]        classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1 # 数频度,每次加1    # 对字典进行排序    # Python 2 才能使用classCount.iteritems()    sortedClassCount = sorted(classCount.items(), key = operator.itemgetter(1), reverse = True)    return sortedClassCount[0][0]if __name__ == '__main__':    # arr = array([[1, 2, 3, 4], [5, 6, 7, 8]])    # print(arr.shape)    # matrix = mat(arr)    # print(matrix.shape)    # print(array([[1, 2],[3, 4]]))    # print(array([(1, 2), (3, 4)]))    # a = array([1, 2])    # print(a.dtype)    # a = [1, 2, 3, 4]    # print(tile(a, 2))    group, labels = createDataBase()    print(classify0([0, 0], group, labels, 3)) # 输出B

1 0