码迷,mamicode.com
首页 > 编程语言 > 详细

K-近邻算法程序清单

时间:2019-11-21 14:23:37      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:查看   迭代   getter   dcl   item   计算   列表   bsp   diff   

.shape  :  查看矩阵或数组的维数

 

.shape[0]  :  查看行长度

.shape[1]  :  查看列长度

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

tile(A, (B, C))  :  重复数组A,行上B次,列上C次

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

B=A.argsort()  :  将数组A中的元素从小到大排列,提取其对应的索引index,然后输出到B

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

a = [1, 2, 3]

b=operator.itemgetter(1)

b(a) >>>  2 

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

students = [(‘john‘,‘A‘,‘15‘),(‘jane‘,‘B‘,‘12‘),(‘dave‘,‘B‘,‘10‘)]

sorted(students,key=operator.itemgetter(2),reverse=True)

resverse  :  false升序、True降序

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

dict.get(key, default=None)

key  :  字典中要查找的键

default  :  如指定键的值不存在时,返回该默认值

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

.items()  :  将一个字典以列表的形式返回,因为字典是无序的,所以返回的列表也是无序的

.iteritems()  :  返回一个迭代器

a = {‘a‘:1,‘b‘:3}
a.items()
返回a = [(‘a‘,1),(‘b‘,3)]

 

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

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 = {}

#选择距离最小的k个点
    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]

K-近邻算法程序清单

标签:查看   迭代   getter   dcl   item   计算   列表   bsp   diff   

原文地址:https://www.cnblogs.com/leon-quant/p/11905002.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!