Home  >  Article  >  Backend Development  >  python k-近邻算法实例分享

python k-近邻算法实例分享

WBOY
WBOYOriginal
2016-06-06 11:31:111287browse

简单说明

这个算法主要工作是测量不同特征值之间的距离,有个这个距离,就可以进行分类了。

简称kNN。

已知:训练集,以及每个训练集的标签。

接下来:和训练集中的数据对比,计算最相似的k个距离。选择相似数据中最多的那个分类。作为新数据的分类。

python实例

代码如下:


# -*- coding: cp936 -*-

#win系统中应用cp936编码,linux中最好还是utf-8比较好。
from numpy import *#引入科学计算包
import operator #经典python函数库。运算符模块。

#创建数据集
def createDataSet():
    group=array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
    labels=['A','A','B','B']
    return group,labels

#算法核心
#inX:用于分类的输入向量。即将对其进行分类。
#dataSet:训练样本集
#labels:标签向量
def classfy0(inX,dataSet,labels,k):
    #距离计算
    dataSetSize =dataSet.shape[0]#得到数组的行数。即知道有几个训练数据
    diffMat     =tile(inX,(dataSetSize,1))-dataSet#tile:numpy中的函数。tile将原来的一个数组,扩充成了4个一样的数组。diffMat得到了目标与训练数值之间的差值。
    sqDiffMat   =diffMat**2#各个元素分别平方
    sqDistances =sqDiffMat.sum(axis=1)#对应列相乘,即得到了每一个距离的平方
    distances   =sqDistances**0.5#开方,得到距离。
    sortedDistIndicies=distances.argsort()#升序排列
    #选择距离最小的k个点。
    classCount={}
    for i in range(k):
        voteIlabel=labels[sortedDistIndicies[i]]
        classCount[voteIlabel]=classCount.get(voteIlabel,0)+1
    #排序
    sortedClassCount=sorted(classCount.iteritems(),key=operator.itemgetter(1),reverse=True)
    return sortedClassCount[0][0]

意外收获

把自己写的模块加入到python默认就有的搜索路径:在python/lib/-packages目录下建立一个 xxx.pth的文件,写入自己写的模块所在的路径即可

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn