深度学习-推荐系统-CV-NLP机器学习与数据挖掘

机械学习- 算法- k-近邻算法 knn算法 -classif

2017-12-11  本文已影响0人  sun_wenming

我来自Android开发人员,刚刚接触的机械学习,整理了k-近邻算法的classify0函数的具体意义,以及一步一步的步骤讲解,望对大家有用。由于初写,如有纰漏或者错误,欢迎指出。

如,您觉得文章有用,可以分享给小伙伴们一起进步成长。需 附加原文地址
链接 http://www.jianshu.com/p/551fb62a2b94 收藏点赞,是对作者最大的支持,核动力的发动机

先上运行图

如果把 # 零 初始化的数据代入次函数,结果应该是'A'
数据来自于,自己编写的,用于学习测试用,准确度与文章的理解程度,望大家提出我会积极改进。

运算结果

近邻算法的 计算公式精髓,下方会 一步一步 讲解哦!

import numpy as np
#用于分类的输入向量是inX,输入的训练样本集为dataSet,
#标签向量为 labels ,最后的参数 k 表示用于选择最近邻居的数目,其中标签向量的元素数目和矩
#阵 dataSet 的行数相同。
def classify0(inX,dataSet,labels,k):
    # 获取 数组 形状的 第一个 参数 a=[[1,2],[1,2],[1,2]]  a.shape = [3,2] a.shape[0] = 3
# 一、
    dataSetSize = dataSet.shape[0]
    # tile 代表了inX,复制为dataSetSize行,1列的数组
# 二、
    diffMat = np.tile(inX,(dataSetSize,1))-dataSet
    # 平方
    sqDiffMat = diffMat**2
    # axis 等于 1 是将 矩阵的每一行 相加
    sqDistances = sqDiffMat.sum(axis=1)
    # 开方
    distances = sqDistances**0.5
# 三、
    # 从小到大 排列
    sortedDistances = distances.argsort()
    classCount = {}
# 四、求出来 最低距离 的 labels结果,存放在classCount 中
    for i in range(k):
        voteIlabel =labels[sortedDistances[i]]
        classCount[voteIlabel] = classCount.get(voteIlabel,0)+1
    sortedClassCount = sorted(classCount.items(),key=operator.itemgetter(1),reverse=True)
    return sortedClassCount[0][0]
# 零   初始化 clasify0  中所需的数据
inX = [2,3]
# 限度 2,2为中介,距离小于 为不喜欢A,大于为喜欢B
dataSet = np.array([[1,2],
          [3,5],
          [1.5,2.5],
          [2.5,3.5]])
labels = ['A','B','A','B']
k=3
# 一、 求出 dataSet 训练数据的 行向量
dataSetSize = dataSet.shape[0] = 4
1.1
二、 复制 输入inX 行向量  与dataSet 的 行大小一致 ,由上方1.1图可知,向量两点的最短距离为 1.0= (inX 行向量 - dataSet 的行向量)
diffMat  = np.tile(inX,(dataSetSize,1))  - dataSet= 
[[2,3],   - [1,2],     =  [1,1]
[2,3],  - [3,5],       =  [-1,-2]
[2,3],  - [1.5,2.5],   =   [0.5,0.5]
[2,3]] - [2.5,3.5]]    =  [-0.5,-0.5]
# 1.1 = 将 差集 平方 虽有  下一步 行向量相加
sqDiffMat = diffMat**2 
# 1.2 = 行向量相加
sqDistances  = sqDiffMat.sum(axis=1) (行向量相加)
[(1^2 + 1^2),
...]
# 1.3 = 所得和集  再 开方(**0.5 相当于开方), 即  求出来了最短距离是多少、 即上方1.1 图的 d
distances  = sqDistances**0.5 = 
[((2)**0.5)   ≈  1.41421
((5)**0.5)    ≈  2.23606
((0.5)**0.5)  ≈  0.707106
((0.5)**0.5)  ≈  0.707106 
...]
# 三、
# argsort : 将distacnces中的元素从小到大排列,提取其对应的index(索引),然后输出到sortedDistances 
# 即 sortedDistances[0] = distacnces[2] = 0.707106
sortedDistances = distacnces.argsort() = 
[2,3,0,1] 
# 四
# 假设 k=3 i = 0 第一层循环 的结果为
voteIlabel =labels[sortedDistances[i]] = 'A'
classCount[voteIlabel] = classCount.get(voteIlabel,0)+1 = 1 (classCount索引为'A')
# 将遍历存储的 classCount = [('A', 1)]  排序,按照
sortedClassCount = sorted(classCount.items(),key=operator.itemgetter(1),reverse=True)
#   返回第一个 最相近的 值,作为结果, 即最相近的近邻算法
return sortedClassCount[0][0]

PS:上方算法内容来自于 机器学习实站 一书,对于一些难理解或者一些知识点的记录,并附加上自己的见解,注释解释等。如,更想快速的学习,可以直接阅读本书

上一篇下一篇

猜你喜欢

热点阅读