侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Python实现的knn算法示例

Python  /  管理员 发布于 7年前   191

本文实例讲述了Python实现的knn算法。分享给大家供大家参考,具体如下:

代码参考机器学习实战那本书:

机器学习实战 (Peter Harrington著) 中文版

机器学习实战 (Peter Harrington著) 英文原版[附源代码]

有兴趣你们可以去了解下

具体代码:

# -*- coding:utf-8 -*-#! python2'''''@author:zhoumeixucreatedate:2015年8月27日'''#np.zeros((4,2))#np.zeros(8).reshape(4,2)#x=np.array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]]) np.zeros_like(x)# 最值和排序:最值有np.max(),np.min() 他们都有axis和out(输出)参数,# 而通过np.argmax(), np.argmin()可以得到取得最大或最小值时的 下标。# 排序通过np.sort(), 而np.argsort()得到的是排序后的数据原来位置的下标# 简单实现knn算法的基本思路import numpy as npimport operator #运算符操作包from _ctypes import Arrayfrom statsmodels.sandbox.regression.kernridgeregress_class import plt_closealldef createDataSet(): group=np.array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]]) labels=['A','A','B','B'] return group ,labelsgroup,labels=createDataSet()def classify0(inx,dataSet,labels,k): dataSetSize=dataSet.shape[0] diffMat=np.tile(inx,(dataSetSize,1))-dataSet sqDiffMat=diffMat**2 sqDistances=sqDiffMat.sum(axis=1) distances=sqDistances**0.5   #计算距离 python中会自动广播的形式 sortedDistIndicies=distances.argsort() #排序,得到原来数据的在原来所在的下标 classCount={} for i in range(k):  voteIlabel=labels[sortedDistIndicies[i]] # 计算距离最近的值所在label标签  classCount[voteIlabel]=classCount.get(voteIlabel,0)+1 # 计算距离最近的值所在label标签,对前k哥最近数据进行累加 sortedClassCount=sorted(classCount.iteritems(),key=operator.itemgetter(1),reverse=True) #排序得到距离k个最近的数所在的标签 return sortedClassCount[0][0]if __name__=='__main__': print(classify0([0,0],group,labels,4))# 利用knn算法改进约会网站的配对效果def file2matrix(filename): fr=open(filename) arrayOLines=fr.readlines() numberOfLines=len(arrayOLines) returnMat=np.zeros((numberOfLines,3)) classLabelVector=[] index=0 for line in arrayOLines:  line=line.strip()  listFromLine=line.split('\t')  returnMat[index,:]=listFromLine[0:3]  classLabelVector.append(int(listFromLine[-1]))  index+=1 return returnMat ,classLabelVector #生成训练数据的array和目标arraypath=u'D:\\Users\\zhoumeixu204\\Desktop\\python语言机器学习\\机器学习实战代码 python\\机器学习实战代码\\machinelearninginaction\\Ch02\\'datingDataMat,datingLabels=file2matrix(path+'datingTestSet2.txt')import matplotlibimport matplotlib.pyplot as pltfig=plt.figure()ax=fig.add_subplot(111)ax.scatter(datingDataMat[:,1],datingDataMat[:,2])plt.show()ax.scatter(datingDataMat[:,1],datingDataMat[:,2],15.0*np.array(datingLabels),15*np.array(datingDataMat[:,2]))plt.show()  #生成训练数据的array和目标arraydef autoNorm(dataset): minVals=dataset.min(0) maxVals=dataset.max(0) ranges=maxVals-minVals normeDataSet=np.zeros(np.shape(dataset)) m=dataset.shape[0] normDataSet=dataset-np.tile(minVals,(m,1)) normDataSet=normDataSet/np.tile(ranges,(m,1)) return normDataSet ,ranges,minValsnormMat,ranges,minVals=autoNorm(datingDataMat)def datingClassTest(): hoRatio=0.1 datingDataMat,datingLabels=file2matrix(path+'datingTestSet2.txt') normMat,ranges,minVals=autoNorm(datingDataMat) m=normMat.shape[0] numTestVecs=int(m*hoRatio) errorCount=0.0 for 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.0 print "the total error rare is :%f"%(errorCount/float(numTestVecs)) #利用knn算法测试错误率if __name__=='__main__': datingClassTest()#利用构建好的模型进行预测def classifyPerson(): resultList=['not at all','in same doses','in large d oses'] percentTats=float(raw_input("percentage if time spent playin cideo games:")) ffMiles=float(raw_input("frequnet fliter miles earned per year:")) iceCream=float(raw_input("liters of ice cream consumed per year:")) datingDataMat,datingLabels=file2matrix(path+'datingTestSet2.txt') normMat,ranges,minVals=autoNorm(datingDataMat) inArr=np.array([ffMiles,percentTats,iceCream]) classifierResult=classify0((inArr-minVals)/ranges,normMat,datingLabels,3) print("you will probably like the person:",resultList[classifierResult-1])if __name__!='__main__': classifyPerson()#利用knn算法进行手写识别系统验证path=u'D:\\Users\\zhoumeixu204\\Desktop\\python语言机器学习\\机器学习实战代码 python\\机器学习实战代码\\machinelearninginaction\\Ch02\\'def img2vector(filename): returnVect=np.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 returnVecttestVector=img2vector(path+'testDigits\\0_13.txt')print(testVector[0,0:31])import osdef handwritingClassTest(): hwLabels=[] trainingFileList=os.listdir(path+'trainingDigits') m=len(trainingFileList) trainingMat=np.zeros((m,1024)) for i in range(m):  fileNameStr=trainingFileList[i]  fileStr=fileNameStr.split('.')[0]  classNumStr=int(fileStr.split('_')[0])  hwLabels.append(classNumStr)  trainingMat[i,:]=img2vector(path+'trainingDigits\\'+fileNameStr) testFileList=os.listdir(path+'testDigits') errorCount=0.0 mTest=len(testFileList) for j in range(mTest):  fileNameStr=testFileList[j]  fileStr=fileNameStr.split('.')[0]  classNumStr=int(fileNameStr.split('_')[0])  classNumStr=int(fileStr.split('_')[0])  vectorUnderTest=img2vector(path+'testDigits\\'+fileNameStr)  classifierResult=classify0(vectorUnderTest,trainingMat,hwLabels,3)  print("the classifier canme back with:%d,the real answer is :%d"%(classifierResult,classNumStr))  if classifierResult!=classNumStr:   errorCount+=1.0 print("\nthe total number of errors is :%d"%errorCount) print("\n the total error rate is :%f"%(errorCount/float(mTest)))if __name__=='__main__': handwritingClassTest()

运行结果如下图:

 

注:这里使用到了statsmodels模块,可以点击此处本站下载statsmodels安装模块,再进入statsmodels模块所在目录位置,使用:

pip install statsmodels-0.9.0-cp27-none-win32.whl

进行statsmodels模块的安装

同理,出现ImportError: No module named pandas错误提示时,点击此处本站下载pandas模块,再使用

pip install pandas-0.23.1-cp27-none-win32.whl

进行pandas模块的安装

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。


  • 上一条:
    Python3.6日志Logging模块简单用法示例
    下一条:
    python字符串常用方法
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(95个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客