Machine Learning in Action机器学习——第二章k-近邻算法代码详解(一)

一、近邻算法的定义与作用也就是意义

k-近邻算法,近邻算法近邻算法顾名思义,找到最近的点然后进行归纳,距离哪些点最近这个点就属于那个类。这和线性回归算法有异曲同工之妙,但是我感觉还是一元线性回归算法更加精准。(有兴趣的小伙伴可以参阅《西瓜书》与《南瓜书》),当然就方便来说,可能k-近邻算法更加方便并且容易理解。

一般的,k-近邻算法可以应用的范围特别广,因为他本身就是一个分类问题。在书中介绍的就是有电影分类、择偶、识别手写数字。

二、近邻算法的代码详解

1、实施分类算法

def classify0(inX, dataSet, labels, k):
    dataSetSize = dataSet.shape[0]  # 代表的是dataSet数据集中的行数
    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]]  # 遍历排序后的前 k 个标签
        classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1 # 记录这 k 个标签出现的次数
    sortedClassCount = sorted(classCount.items(),  key=operator.itemgetter(1), reverse=True)  # 按照出现次数对标签进行从大到小排序
    return sortedClassCount[0][0]  # 返回出现次数最多的那个标签

参数含义 

inX代表的是所需要分类的对象,也就是用于分类的输入向量

dataSet代表的是inX要被分类出来的依据对象,是依据dataSet这个数据组才把inX分为那些类,也就是书上的输入的训练样本集

labels也就是dataSet所对应的标签,比如说爱情片、恐怖片这种,用于将最多的标签复制给inX的标签,最后作为一个返回值。

k代表所抽取的前几个元素,进行分类之后会将标签与数据集依次排序排序之后的前k个元素中哪个标签所占数目比较多,就将inX分为这个标签。

到这里kNN的大概意思应该就解释清楚了(书中后面列举的是具体的实例),下面看具体的函数作用。

函数解析

shape:在这里用shape[0]来读取这个dataSet数据集的行数

tile:在这里用tile是将inX汇聚成dataSize行一列的数据集,因为矩阵的运算规律需要我们这么做。

sum:sum(axis=1)其中axis=1的意思是,将每一行的元素加起来,然后再进行接下来的开方。

argsort:就是分类函数了,对distance进行排序

sorted:对于classCount.items()进行排序,排序依据是operater(也就是classCount.item)的第二个元素,也就是上面循环中求出的每个标签的数字。从大到小进行排序。

难点解析

    for i in range(k):
        voteIlabel = labels[sortedDistIndicies[i]]  # 遍历排序后的前 k 个标签
        classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1 # 记录这 k 个标签出现的次数

在这个循环之中,有一个问题,labels如何和以及分类排序之后的数据集找到一一对应的关系。所以上面使用了一个argsort函数

函数的具体效果如上图,这样根据大小排列之后,dataSet的标签依旧不会改变。也就解决了上述问题。

三、总结

以上就是kNN分类算法的大体解析,实例介绍我们放在之后的讲解中。

上面都是我学习之中遇到的一些困难以及疑惑,如果小伙伴们还有其他的问题也欢迎私信我进行交流。

代码出处出自于机器学习实战这本书中,其中对于python3.X与python2.X的不同进行了一些调整,例如:

python2与3的变动
python2python3
print “”print("")
iteritems()items()

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Machine Learning in Action is unique book that blends the foundational theories of machine learning with the practical realities of building tools for everyday data analysis. You'll use the flexible Python programming language to build programs that implement algorithms for data classification, forecasting, recommendations, and higher-level features like summarization and simplification. About the Book A machine is said to learn when its performance improves with experience. Learning requires algorithms and programs that capture data and ferret out the interesting or useful patterns. Once the specialized domain of analysts and mathematicians, machine learning is becoming a skill needed by many. Machine Learning in Action is a clearly written tutorial for developers. It avoids academic language and takes you straight to the techniques you'll use in your day-to-day work. Many (Python) examples present the core algorithms of statistical data processing, data analysis, and data visualization in code you can reuse. You'll understand the concepts and how they fit in with tactical tasks like classification, forecasting, recommendations, and higher-level features like summarization and simplification. Readers need no prior experience with machine learning or statistical processing. Familiarity with Python is helpful. What's InsideA no-nonsense introduction Examples showing common ML tasks Everyday data analysis Implementing classic algorithms like Apriori and Adaboos =================================== Table of ContentsPART 1 CLASSIFICATION Machine learning basics Classifying with k-Nearest Neighbors Splitting datasets one feature at a time: decision trees Classifying with probability theory: naïve Bayes Logistic regression Support vector machines Improving classification with the AdaBoost meta algorithm PART 2 FORECASTING NUMERIC VALUES WITH REGRESSION Predicting numeric values: regression Tree-based regression PART 3 UNSUPERVISED LEARNING Grouping unlabeled items using k-means clustering Association analysis with the Apriori algorithm Efficiently finding frequent itemsets with FP-growth PART 4 ADDITIONAL TOOLS Using principal component analysis to simplify data Simplifying data with the singular value decomposition Big data and MapReduce
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值