news 2026/10/23 1:01:15

【python】python机器学习实战1:实现k-近邻算法

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
【python】python机器学习实战1:实现k-近邻算法

首先分享一下链接:http://pan.baidu.com/s/1jIsS8HC 密码:rfew,
里面有kNN当中使用的数据集。这个系列的教程可能更注重机器学习的算法,没有使用深度框架,主要是从低层的一些函数进行编程。一方面可以加深对机器学习的理解,另外一方面增加python的编程能力,能够更好的学会处理自己的数据。

#coding:utf-8#首先先导入相关的数据库,这里使用的主要是Numpy和matplotlib,里面函数的定义LZ都已经给出了,具体想要如何调用函数就看小伙伴们的需要了fromnumpyimport*importoperatorimportmatplotlibimportmatplotlib.pyplotaspltimportos#首先基本的学会创建一个数据集defcreateDataSet():group=array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])labels=['A','A','B','B']returngroup,labels#主要的就是这个分类器啦!kNN分类器,有四个参数,输入,训练数据,标签,k类,这主要就是计算对应的欧氏距离defclassify0(inX,dataSet,labels,k):dataSetSize=dataSet.shape[0]diffMat=tile(inX,(dataSetSize,1))-dataSet sqDiffMat=diffMat**2sqDistances=sqDiffMat.sum(axis=1)distances=sqDistances**0.5sortedDistIndicies=distances.argsort()classCount={}foriinrange(k):voteIlabel=labels[sortedDistIndicies[i]]classCount[voteIlabel]=classCount.get(voteIlabel,0)+1sortedClassCount=sorted(classCount.iteritems(),key=operator.itemgetter(1),reverse=True)returnsortedClassCount[0][0]#在这个代码中使用的数据集是要转化成矩阵的形式,所以这个函数就是构造对应的矩阵deffile2matrix(filename):fr=open(filename)arrayOLines=fr.readlines()numberOfLines=len(arrayOLines)returnMat=zeros((numberOfLines,3))classLabelVector=[]index=0forlineinarrayOLines:line=line.strip()listFromLine=line.split('\t')returnMat[index,:]=listFromLine[0:3]classLabelVector.append(int(listFromLine[-1]))index+=1returnreturnMat,classLabelVector#这个函数主要就是画图的啦,如果使用可以看到训练集的数据分布哦defcreate_fig():fig=plt.figure()ax=fig.add_subplot(111)ax.scatter(datingDataMat[:,1],datingDataMat[:,2],15.0*array(datingLabels),15.0*array(datingLabels))plt.show()#对数据进行预处理,为什么要进行归一化,因为如果一个数据集是体重和身高,如果不对数据进行归一化,体重的均值在60kg,身高在1.75m,那么明显可以看出体重的权重会更大些,所以在特征权重均等的情况下,应该对原始数据进行归一化defautoNorm(dataSet):minVals=dataSet.min(0)maxVals=dataSet.max(0)ranges=maxVals-minVals normDataSet=zeros(shape(dataSet))m=dataSet.shape[0]normDataSet=dataSet-tile(minVals,(m,1))normDataSet=normDataSet/tile(ranges,(m,1))returnnormDataSet,ranges,minVals#测试一下咯defdatingClassTest():hoRatio=0.50datingDataMat,datingLabels=file2matrix('datingTestSet2.txt')normMat,ranges,minVals=autoNorm(datingDataMat)m=normMat.shape[0]numTestVecs=int(m*hoRatio)errorCount=0.0foriinrange(numTestVecs):classfierResult=classify0(normMat[i,:],normMat[numTestVecs:m,:],\ datingLabels[numTestVecs:m],3)print"the classfier came back with: %d, the real answer is: %d"\%(classfierResult,datingLabels[i])if(classfierResult!=datingLabels[i]):errorCount+=1.0print"the total error rate is %f"%(errorCount/float(numTestVecs))#这个函数主要就是针对输入来判断到底是哪一个类别的defclassifyPerson():resultList=['not at all','in small doses','in large doses']percentTats=float(raw_input("percentage of time spent playing video games?"))ffMiles=float(raw_input("frequent flier miles earned per year?"))iceCream=float(raw_input("liters of ice cream consumed per year?"))datingDataMat,datingLabels=file2matrix('datingTestSet2.txt')normMat,ranges,minVals=autoNorm(datingDataMat)inArr=array([ffMiles,percentTats,iceCream])classfierResult=classify0((inArr-minVals)/ranges,normMat,datingLabels,3)print"you will probably like this person: ",resultList[classfierResult-1]#要把图片转化成向量,怎么转化呢?defimg2vector(filename):returnVect=zeros((1,1024))fr=open(filename)foriinrange(32):lineStr=fr.readline()forjinrange(32):returnVect[0,32*i+j]=int(lineStr[j])returnreturnVect#定义手写数字测试的函数defhandwritingClassTest():hwLabels=[]trainingFileList=os.listdir('./digits/trainingDigits')#load the training setm=len(trainingFileList)trainingMat=zeros((m,1024))foriinrange(m):fileNameStr=trainingFileList[i]fileStr=fileNameStr.split('.')[0]#take off .txtclassNumStr=int(fileStr.split('_')[0])hwLabels.append(classNumStr)trainingMat[i,:]=img2vector('./digits/trainingDigits/%s'%fileNameStr)testFileList=os.listdir('./digits/testDigits')#iterate through the test seterrorCount=0.0mTest=len(testFileList)foriinrange(mTest):fileNameStr=testFileList[i]fileStr=fileNameStr.split('.')[0]#take off .txtclassNumStr=int(fileStr.split('_')[0])vectorUnderTest=img2vector('./digits/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"%errorCountprint"\nthe total error rate is: %f"%(errorCount/float(mTest))# group, labels = createDataSet()# print classify0([0, 0], group, labels, 3)# datingDataMat, datingLabels = file2matrix('datingTestSet2.txt')# normMat, ranges, minVals = autoNorm(datingDataMat)# # print datingDataMat[:, 1], datingLabels# print normMat, ranges, minVals# create_fig()# classifyPerson()# testVector = img2vector('./digits/testDigits/0_13.txt')# print testVectorhandwritingClassTest()# fr = open('./digits/testDigits/0_13.txt')

哈哈,还不错哦,我们还学会了怎么批量读取文件O(∩_∩)O

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/10/23 1:01:04

【python】python快速入门(列表推导式)

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

作者头像 李华
网站建设 2026/10/23 1:01:02

【python】python module使用之----operator

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

作者头像 李华
网站建设 2026/10/22 23:59:28

FreeRTOS任务通知实战详解:内核原理、API与避坑指南

裸机编程切到RTOS之后,任务之间的通信和同步永远是躲不开的坎。前面聊过队列、信号量、互斥锁、事件组,这次把FreeRTOS任务通知(Task Notification)单独拎出来讲透。原因很简单:任务通知是FreeRTOS里最容易用错、也最容…

作者头像 李华
网站建设 2026/10/22 23:56:45

从极简命名到工程落地:拆解小模块设计哲学与实操要点

1. 从“rea”这个标题说起:一个极简词背后的项目拆解思路 “rea”这三个字母,第一次看到的时候,我脑子里蹦出来的第一反应是——这大概率是个缩写,而且是一个被压缩到极致的缩写。在技术圈里混久了你会发现,越是短的项…

作者头像 李华
网站建设 2026/10/22 23:56:38

jinfo命令详解:JVM运行中参数查看与动态修改实战

提到 JVM 排查工具,大家随口就是 jstat、jstack、jmap,jinfo 反而常常被忽略。它属于 JDK 自带的诊断命令,核心能力正好是标题里这九个字:实时查看和修改 JVM 配置参数,也就是你可以不重启、不停机,对一个正…

作者头像 李华
网站建设 2026/10/22 23:55:34

从零到2万Star:AI编程开源教程的定位、设计与增长复盘

这个教程做到 2 万 Star,说实话比我预期来得早。最近更意外的是,它竟然出现在豆包的推荐里,不少读者是顺着 AI 助手的回答摸到项目页的。我先交代一下这是个什么东西:它不是一套讲理论的书,也不是单纯的代码仓库&#…

作者头像 李华