《机器学习实战》k-近邻算法概述-程序清单详解kNN.py(未完待续)

from numpy import *import operatordef createDateSet():    group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])    labels = ['A','A','B','B']    return group,labelsdef classify0(inX,
摘要由CSDN通过智能技术生成
from numpy import *
import operator


def createDateSet():
    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):
    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.items(),
                              key = operator.itemgetter(1),reverse = True)

    return sortedClassCount[0][0]

kNN.classify0([0,0],group,labels,3)


详解:

dataSet.shape[0]:表示训练集中向量的个数。

shape[n]:表示第n维的长度

例如:

>>>group.shape[0]

4

>>>group.shape[1]

2


tile(inX,(dataSetSize,1)):得到的是dataSetSize个的inX。

tile(A,reps):construct an array by repeating A the number of times given by reps.

具体用法可见:docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html


sqDiffMat.sum(axis=1):得到的是第二维的所有元素之和。

具体用法可见:docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html


distances.argsort():是将distances里的元素从小到大排列,得到一个对应原来的元素的顺序排列。

具体用法可见:docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html


classCount.get(voteIlabel,0):返回字典中,voteIlabel的值,如果没有,则创建,并将值设为0(即第二个参数)。


 sortedClassCount = sorted(classCount.items(),
                              key = operator.itemgetter(1),reverse = True)

将字典按照item的第一维逆向排序。


1.原书中使用的是python2.7环境,博文中代码经过修改能在python3.3中正常运行。

2.文中的维数按照第零维,第一维的顺序排列。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值