云服务器网站解析,简单学生的网页代码,济南手机网站制作,网站开发基于百度地图k-近邻算法#xff08;KNN#xff09;
一。工作原理
存在一个样本数据集合#xff0c;即训练样本集#xff0c;并且样本集中每个数据都存在标签#xff08;样本集中每一数据与所属分类的对应关系#xff09;#xff0c;
输入没有标签的新数据后#xff0c;将新数据的…k-近邻算法KNN
一。工作原理
存在一个样本数据集合即训练样本集并且样本集中每个数据都存在标签样本集中每一数据与所属分类的对应关系
输入没有标签的新数据后将新数据的每个特征与样本集中数据对应的特征进行比较然后算法提取样本集中特征最相似数据的分类标签
一般只选择样本数据集中前k个最相似结果通常k是不大于20的整数将k个最相似数据中出现次数最多的分类作为新数据的分类。
二。一般流程
1.收集数据
2.准备数据计算所需要的数值
3.分析数据
4.训练数据
5.测试数据
6.使用算法首先输入样本数据和结构化的输出结果然后运行k-近邻算法判定输入数据分别属于哪个分类最后应用
对计算出的分类执行后续的处理。 三。代码 from numpy import *
import operatordef createDataSet() :group array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])labels [A,A,B,B]return group, labelsdef classify0(inX, dataSet, labels, k) :dataSetSize dataSet.shape[0]#calculate the distance between the inx and other traning datadiffMat tile(inX, (dataSetSize,1)) - dataSet #titl for arraysqDiffMat diffMat**2sqDistances sqDiffMat.sum(axis1) #calculate the sumprint sqDistances,sqDistancesdistances sqDistances**0.5print distances,distancessortedDistIndicies distances.argsort()print sorted,sortedDistIndicies#find the k nearest neighboursclassCount {}for i in range(k) :voteIlabel labels[sortedDistIndicies[i]]classCount[voteIlabel] classCount.get(voteIlabel,0) 1sortedClassCount sorted(classCount.iteritems(), key operator.itemget
ter(1), reverse True)pre namecode classhtmlspan stylewhite-space:pre /spanprint sortedClassCountreturn sortedClassCountif __name____main__ :group, labels createDataSet()classify0([0,0],group, labels, 3) 四。执行 在终端执行 python KNN.py