Machine Learning in Action_CH2_1_kNN

from numpy import *
import operator

def createDataBase():
    group = array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]]) # numpy向量
    labels = ['A', 'A', 'B', 'B'] # 列表
    return group, labels

def 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值