参考机器学习实战第二章,自己实现了一遍

from numpy import *
import operator
import pandas as pd
from os import listdir#inX是测试数据,dataSet是训练数据集,labels是标签,返回的是概率最大的标签
def classify0(inX, dataSet, labels, k):dataSetSize = dataSet.shape[0]diffMat = tile(inX, (dataSetSize,1)) - dataSetsqDiffMat = diffMat**2sqDistances = sqDiffMat.sum(axis=1)distances = sqDistances**0.5sortedDistIndicies = distances.argsort()classCount = {}for i in range(k):voteIlabel = labels[sortedDistIndicies[i]]classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1sorted(classCount.items(), key=lambda e: e[1], reverse=True)return sorted(classCount.items(), key=lambda e: e[1], reverse=True)[0][0]#自己生成的数据,仅作测试用
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#从txt文件中提取训练集和标签
def file2matrix(filename):fr = open(filename)numberOfLines = len(fr.readlines())         #get the number of lines in the filereturnMat = zeros((numberOfLines,3))        #prepare matrix to returnclassLabel = []                       #prepare labels returnfr = open(filename)index = 0for line in fr.readlines():line = line.strip()listFromLine = line.split('\t')returnMat[index,:] = listFromLine[0:3]classLabel.append(listFromLine[-1])index += 1classLabelVector = pd.Categorical(classLabel)return returnMat,(classLabelVector.labels+1)#对训练集中的每个维度数据进行归一化
def autoNorm(dataSet):minVals=dataSet.min(0)maxVals=dataSet.max(0)ranges=maxVals-minValsnormDataSet=zeros(shape(dataSet))m=dataSet.shape[0]normDataSet=dataSet-tile(minVals,(m,1))normDataSet=normDataSet/tile(ranges,(m,1))return normDataSet,ranges,minVals#测试txt文件中的准确率
def datingClassTest():hoRatio = 0.50      #hold out 10%datingDataMat,datingLabels = file2matrix('C:/Users/new/Desktop/datingTestSet.txt')       #load data setfrom filenormMat, ranges, minVals = autoNorm(datingDataMat)m = normMat.shape[0]numTestVecs = int(m*hoRatio)errorCount = 0.0for i in range(numTestVecs):classifierResult = classify0(normMat[i,:],normMat[numTestVecs:m,:],datingLabels[numTestVecs:m],3)print("the classifier came back with: %d, the real answer is: %d" % (classifierResult, datingLabels[i]))if (classifierResult != datingLabels[i]): errorCount += 1.0print("the total error rate is: %f" % (errorCount/float(numTestVecs)))print(errorCount)#把手写字符转换成一维向量
def img2vector(filename):returnVect=zeros((1,1024))fr=open(filename)for i in range(32):lineStr=fr.readline()for j in range(32):returnVect[0,32*i+j]=int(lineStr[j])return returnVect#手写字符测试
def handwritingClassTest():hwLabels = []trainingFileList = listdir('C:/Users/new/Desktop/trainingDigits')           #load the training setm = len(trainingFileList)trainingMat = zeros((m,1024))for i in range(m):fileNameStr = trainingFileList[i]fileStr = fileNameStr.split('.')[0]     #take off .txtclassNumStr = int(fileStr.split('_')[0])hwLabels.append(classNumStr)trainingMat[i,:] = img2vector('C:/Users/new/Desktop/trainingDigits/%s' % fileNameStr)testFileList = listdir('C:/Users/new/Desktop/testDigits')        #iterate through the test seterrorCount = 0.0mTest = len(testFileList)for i in range(mTest):fileNameStr = testFileList[i]fileStr = fileNameStr.split('.')[0]     #take off .txtclassNumStr = int(fileStr.split('_')[0])vectorUnderTest = img2vector('C:/Users/new/Desktop/testDigits/%s' % fileNameStr)classifierResult = classify0(vectorUnderTest, trainingMat, hwLabels, 3)print("the classifier came back with: %d, the real answer is: %d" % (classifierResult, classNumStr))if (classifierResult != classNumStr): errorCount += 1.0print("\nthe total number of errors is: %d" % errorCount)print("\nthe total error rate is: %f" % (errorCount/float(mTest)))handwritingClassTest()# returnMat,classLabel=file2matrix('C:/Users/new/Desktop/datingTestSet.txt')
# print(autoNorm(returnMat)[0])
# group,labels=createDataSet()
# print(group,labels)
# s=classify0([0,0],group,labels,2)
# print(s)
the total number of errors is: 11the total error rate is: 0.011628

代码可以直接使用,实验数据可以从这里下载~~~

一步一步实现KNN分类算法相关推荐

  1. 从原始文档到KNN分类算法实现(一)

    版权声明:本文为博主原创文章,未经博主允许不得转载. 建立原始文档 ~/corpus/C1下建三个文件:0,1,2.内容分别为: 0 眼睛 明亮 健康 身体 发达 1 高大 身材 胳膊 勇猛 四肢 2 ...

  2. python KNN分类算法 使用鸢尾花数据集实战

    KNN分类算法,又叫K近邻算法,它概念极其简单,但效果又很优秀. 如觉得有帮助请点赞关注收藏啦~~~ KNN算法的核心是,如果一个样本在特征空间中的K个最相似,即特征空间中最邻近的样本中的大多数属于某 ...

  3. python分类算法_用Python实现KNN分类算法

    本文实例为大家分享了Python KNN分类算法的具体代码,供大家参考,具体内容如下 KNN分类算法应该算得上是机器学习中最简单的分类算法了,所谓KNN即为K-NearestNeighbor(K个最邻 ...

  4. KNN 分类算法原理代码解析

    作者 | Charmve 来源 | 迈微AI研习社 k-最近邻算法是基于实例的学习方法中最基本的,先介绍基x`于实例学习的相关概念. 基于实例的学习 已知一系列的训练样例,很多学习方法为目标函数建立起 ...

  5. 用Python开始机器学习(4:KNN分类算法)

    转自: http://blog.csdn.net/lsldd/article/details/41357931 1.KNN分类算法 KNN分类算法(K-Nearest-Neighbors Classi ...

  6. k近邻算法(KNN)-分类算法

    k近邻算法(KNN)-分类算法 1 概念 定义:如果一个样本在特征空间中的k个最相似(即特征空间中最邻近)的样本中的大多数属于某一个类别,则该样本也属于这个类别. k-近邻算法采用测量不同特征值之间的 ...

  7. 利用python语言实现分类算法_使用python实现kNN分类算法

    k-近邻算法是基本的机器学习算法,算法的原理非常简单: 输入样本数据后,计算输入样本和参考样本之间的距离,找出离输入样本距离最近的k个样本,找出这k个样本中出现频率最高的类标签作为输入样本的类标签,很 ...

  8. 《机器学习实战》学习总结(一)KNN分类算法原理

    kNN分类算法属于有监督类学习算法. 该分类算法不需要训练算法,直接对待分类点进行决策分类. 算法实现过程如下: 1.计算测试点与已知类别数据集中点的距离: 2.对距离进行排序(递增). 3.选取与测 ...

  9. Python实现knn分类算法(Iris 数据集)

    1.KNN分类算法 KNN分类算法(K-Nearest-Neighbors Classification),又叫K近邻算法,是一个概念极其简单,而分类效果又很优秀的分类算法. 他的核心思想就是,要确定 ...

  10. knn分类算法实现手写体数字识别python

    之前写过knn分类算法代码,想把knn用于设别手写体数字,看下正确率. 大概思路:获取图片(可以自己写,我之前有写过黑白图片转文本的代码,也可以网上找,反正数据量大会更好)->转成文本-> ...

最新文章

  1. python编程语言是什么-Python是一种什么样的编程语言?解释?编译?汇编?机械?...
  2. #pragma once与#ifndef的区别?
  3. 前端Javascript与Nodejs的异同
  4. 第二轮冲刺-Runner站立会议08
  5. linux两台服务器传输,Linux两台服务器之间高速数据传输命令:scp应用详解
  6. (10)FPGA面试技能提升篇10(MATLAB)
  7. 当Ext.js中xtype: 'checkboxfield'时,没勾选则向后台发送的数据没有字段的解决方法...
  8. google控制台使用
  9. 快速下载720云高清全景图片
  10. Java调用WebService接口的四种方式
  11. Ubuntu安装客户端RabbitVCS(svn管理)
  12. mybatis mapper xml的学习详解
  13. 等保2.0三级通用要求
  14. python实现最大公约数最小公倍数求法
  15. 东北人讲java_东北人,请你讲东北话(内附东北话速成)
  16. BookXNote使用
  17. win7和ubuntu关闭防火墙方法
  18. python29期完结2021年共367G
  19. java io流详解_一文带你看懂JAVA IO流,史上最全面的IO教学啦
  20. 拼图游戏-恶搞整蛊表白软件

热门文章

  1. 浅谈java 之 Map
  2. No resource found that matches the given name 'android:Theme.Material.Light.DarkActionBar'
  3. AS3 CookBook学习整理(二)
  4. windows上java调用gdal.jar报错
  5. 排序算法之四 归并排序(C++版本)
  6. MapReduce学习要点
  7. 位置度标注方法图解_追踪主力-散户操盘实战图解:操盘手法分析
  8. mybatis连接池
  9. 计算机网格和云计算区别,什么是云计算,什么是网格计算,他们之间有什么区别...
  10. mysql 复杂类型_MySQL 复杂数据类型之JSON数据