【机器学习实战系列】读书笔记之KNN算法(一)

首先介绍knn算法用到的numpy的几个知识点:

1.shape函数是numpy.core.fromnumeric中的函数,它的功能是查看矩阵或者数组的维数。

举例说明:

建立一个4×2的矩阵c, c.shape[0] 为第一维的长度,c.shape[1] 为第二维的长度。

  1. >>> c = array([[1,1],[1,2],[1,3],[1,4]])  
  2. >>> c.shape  
  3. (4, 2)  
  4. >>> c.shape[0]  
  5. 4  
  6. >>> c.shape[1]  
  7. 2  

2.python中numpy模块tile方法说明

函数形式: tile(A,rep) 
功能:重复A的各个维度 
参数类型: 
- A: Array类的都可以 
- rep:A沿着各个维度重复的次数

举例:

tile([1,2],2)
  • 1

输出[1,2,1,2]

tile([1,2],(2,2))
  • 1

重复顺序为: [1,2] => [[1,2] , [1,2]] => [[1,2,1,2] , [1,2,1,2]]

tile([1,2],(2,2,3))
  • 1

重复顺序为: [1,2] => [[1,2] , [1,2]] => [[[1,2],[1,2]] , [[1,2],[1,2]]] => [[[1,2,1,2,1,2],[1,2,1,2,1,2]] , [[1,2,1,2,1,2],[1,2,1,2,1,2]]]


3.sum(axis = 1)

现在对于数据的处理更多的还是numpy。没有axis参数表示全部相加,axis=0表示按列相加,axis=1表示按照行的方向相加

[python]  view plain  copy
  1. >>> import numpy as np  
  2. >>> a=np.sum([[0,1,2],[2,1,3]])  
  3. >>> a  
  4. 9  
  5. >>> a.shape  
  6. ()  
  7. >>> a=np.sum([[0,1,2],[2,1,3]],axis=0)  
  8. >>> a  
  9. array([225])  
  10. >>> a.shape  
  11. (3,)  
  12. >>> a=np.sum([[0,1,2],[2,1,3]],axis=1)  
  13. >>> a  
  14. array([36])  
  15. >>> a.shape  
  16. (2,)  


4.argsort()

argsort() 函数将数组的值从小到大排序后,并按照其相对应的索引值输出

举例说明:

一维数组

[plain]  view plain  copy
  1. >>> a = array([3,1,2])  
  2. >>> argsort(a)  
  3. array([1, 2, 0])  

二维数组

[plain]  view plain  copy
  1. >>> b = array([[1,2],[2,3]])  
  2. >>> argsort(b,axis=1) #按行排序  
  3. array([[0, 1],  
  4.        [0, 1]])  
  5. >>> argsort(b,axis=0) #按列排序  
  6. array([[0, 0],  
  7.        [1, 1]])  
  8. >>>   

5.get方法

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

get()方法语法:

dict.get(key, default=None)
  • key -- 字典中要查找的键。
  • default -- 如果指定键的值不存在时,返回该默认值值,如果值不在字典中返回默认值None。
6. iteritems()

python字典中还存在items()方法。两者有些许区别。

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

[python]  view plain  copy
  1. >>> d = {'1':'one''2':'two''3':'three'}  
  2. >>> x = d.items()  
  3. >>> x  
  4. [('1''one'), ('3''three'), ('2''two')]  
  5. >>> type(x)  
  6. <type 'list'>  
  7. >>> y = d.iteritems()  
  8. >>> y  
  9. <dictionary-itemiterator object at 0x025008A0>  
  10. >>> type(y)  
  11. <type 'dictionary-itemiterator'>  


7.实施knn算法
from numpy import *
import operator

def createDataSet():
    group = array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]])
    lables = ['A', 'A', 'B', 'B']
    return group, lables

def classify0(inX, dataSet, lables, k):
    dataSetSize = dataSet.shape[0]
    diffMat = tile(inX, (dataSetSize,1)) - dataSet
    sqDiffMat = diffMat**2
    sqDistance = sqDiffMat.sum(axis=1)
    distances = sqDistance**0.5
    sortedDistance = distances.argsort()
    # 对距离进行排序,argsort()函数默认按升序排列,但只返回下标,不对原数组排序
    classCount = {}
    for i in range(k):
        # 统计最近的 k 个点的类别出现的次数
        votelable = lables[sortedDistance[i]]
        classCount[votelable] = classCount.get(votelable, 0) + 1
    sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse = True)
    # 对类别出现的次数进行排序,sorted()函数默认升序
    return sortedClassCount[0][0]
    # 返回类别出现次数最多的分类名称

if __name__ == "__main__":
    group, lables = createDataSet()
    print('group is:')
    print(group)
    print('labels is:')
    print(lables)
    t = classify0([0, 0], group, lables, 3)
    print('t is:')
    print(t)
输出结果为:

group is:
[[ 1.   1.1]
 [ 1.   1. ]
 [ 0.   0. ]
 [ 0.   0.1]]
labels is:
['A', 'A', 'B', 'B']
t is:
B



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值