python k-近邻算法实例分享
时间:2022-03-26 14:47:17
简单说明
这个算法主要工作是测量不同特征值之间的距离,有个这个距离,就可以进行分类了。
简称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的文件,写入自己写的模块所在的路径即可
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python使用当前时间、随机数产生一个唯一数字的方法
![](https://img.aspxhome.com/file/2023/6/67926_0s.png)
两种与SQL Server数据库交换数据的方法
ASP技巧 挂QQ的网页源代码ASP/PHP
Python将list元素转存为CSV文件的实现
![](https://img.aspxhome.com/file/2023/2/86242_0s.png)
详解Python读取和写入操作CSV文件的方法
![](https://img.aspxhome.com/file/2023/6/65526_0s.jpg)
WEB标准与XHTML 1.0 Transitional等文档类型介绍
讲解SQL Server海量数据导入的最快方法
python实现五子棋小游戏
![](https://img.aspxhome.com/file/2023/3/65913_0s.jpg)