第2章 K近邻算法 python中的sum函数.sum(axis=1) 浅述python中argsort()函数的用法

numpy中的tile函数:

遇到numpy.tile(A,(b,c))函数,重复复制A,按照行方向b次,列方向c次。

>>> import numpy
>>> numpy.tile([0,0],5)#在列方向上重复[0,0]5次,默认行1次
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
>>> numpy.tile([0,0],(1,1))#在列方向上重复[0,0]1次,行1次
array([[0, 0]])
>>> numpy.tile([0,0],(2,1))#在列方向上重复[0,0]1次,行2次
array([[0, 0],
       [0, 0]])
>>> numpy.tile([0,0],(3,1))
array([[0, 0],
       [0, 0],
       [0, 0]])
>>> numpy.tile([0,0],(1,3))#在列方向上重复[0,0]3次,行1次
array([[0, 0, 0, 0, 0, 0]])
>>> numpy.tile([0,0],(2,3))<span style="font-family: Arial, Helvetica, sans-serif;">#在列方向上重复[0,0]3次,行2次</span>
array([[0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0]])

python中的sum函数.sum(axis=1)

当加入axis=1以后就是将一个矩阵的每一行向量相加

a = np.array([[0, 2, 1]])

print a.sum()
print a.sum(axis=0)
print a.sum(axis=1)

结果分别是:3, [0 1 2], [3]

 

b = np.array([0, 2, 1])

print b.sum()
print b.sum(axis=0)
print b.sum(axis=1)

结果分别是:3, 3, 运行错误:'axis' entry is out of bounds

 可知:对一维数组,只有第0轴,没有第1轴

c = np.array([[0, 2, 1], [3, 5, 6], [0, 1, 1]])

print c.sum()
print c.sum(axis=0)
print c.sum(axis=1)

结果分别是:19, [3 8 8], [ 3 14  2]

浅述python中argsort()函数的用法

1.先定义一个array数据

1 import numpy as np
2 x=np.array([1,4,3,-1,6,9])

2.现在我们可以看看argsort()函数的具体功能是什么:

x.argsort()

输出定义为y=array([3,0,2,1,4,5])。

我们发现argsort()函数是将x中的元素从小到大排列提取其对应的index(索引),然后输出到y。例如:x[3]=-1最小,所以y[0]=3,x[5]=9最大,所以y[5]=5。

Python 字典(Dictionary) get()方法


描述

Python 字典(Dictionary) get() 函数返回指定键的值,如果值不在字典中返回默认值。

语法

get()方法语法:

dict.get(key, default=None)

参数

  • key -- 字典中要查找的键。
  • default -- 如果指定键的值不存在时,返回该默认值值。

返回值

返回指定键的值,如果值不在字典中返回默认值None。

items()和iteritems()区别:

字典的items方法作用:是可以将字典中的所有项,以列表方式返回。因为字典是无序的,所以用items方法返回字典的所有项,也是没有顺序的。
字典的iteritems方法作用:与items方法相比作用大致相同,只是它的返回值不是列表,而是一个迭代器。

核心代码解读:

# inX:用于分类的输入向量  
# dataSet:输入的训练样本集
# labels:标签向量
# k:用于选择最近邻的数量
def classify0(inX, dataSet, labels, k):
    # 距离计算
    dataSetSize = dataSet.shape[0] #数据的条目数  #c.shape[1] 为列的数量,c.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 rangs(k):
        # 取出对应的label
        voteIlabel = labels[sortedDistIndicies[i]]
        #计算当前取出的label的数量
        #对标签A、B分别进行统计计数
        classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1
    
    # 逆序排列label对应总数的列表 返回对应的label
    sortedClassCount = sorted(classCount.iteritems(),key=operator.itemgetter(1), reverse=True)
    #iteritems()是把字典里面的元素,返回一个迭代器
    #key=operator.itemgetter(1),按照第1个值(即第二个统计到的个树值)进行排序
    #reverse=True,True时将按降序排列
    
    
    return sortedClassCount[0][0]

猜你喜欢

转载自www.cnblogs.com/captain-dl/p/9392882.html