kNN.py源码及注释(python3.x)
import operator
from os import listdir
def CerateDataSet():
group = np.array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
labels = ['A','A','B','B']
return group,labels
dataSetSize = dataSet.shape[0] #输入的训练样本集是dataSet,标签向量为labels
diffMat = np.tile(inX,(dataSetSize,1)) - dataSet #最后的参数k表示用于选择最近邻居的数目,其中标签向量的元素数目和矩阵dataSet的行数相同。
sqDiffMat = diffMat**2
sqDistances = sqDiffMat.sum(axis=1)
distances = sqDistances**0.5
sortedDistIndicies = distances.argsort()
classCount={}
for i in range(k):
voteIlabel = labels[sortedDistIndicies[i]]
classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1
sortedClassCount = sorted(classCount.items(),key=operator.itemgetter(1),reverse=True)
return sortedClassCount[0][0]
fr = open(filename) #1.打开文件读取文件行数
arrayOLines = fr.readlines()
numberOfLines = len(arrayOLines)
returnMat = np.zeros((numberOfLines,3)) #创建返回numpy的矩阵
classLabelVector = []
index = 0
for line in arrayOLines: #解析文件数据到列表
line = line.strip() #这一步将‘\\n'(空行)转换为'',截取掉所有的回车字符
listFromLine = line.split('\t') #然后使用tab字符\t将上一步得到的整行数据分割成一个元素列表
returnMat[index,:] = listFromLine[0:3]
classLabelVector.append(int(listFromLine[-1]))
index += 1
return returnMat,classLabelVector
def autoNorm(dataSet): #这个步骤是因为海伦希望三个因素对约会系数计算相等,将数字特征转化为0到1区间
minVals = dataSet.min(0) #将每列的最小值放在minVals中
maxVals = dataSet.max(0) #将每列的最大值放在minVals中
ranges = maxVals - minVals #计算范围
normDataSet = np.zeros(np.shape(dataSet)) #创建矩阵
m = dataSet.shape[0]
normDataSet = dataSet -np.tile(minVals,(m,1)) #numpy中的tile()函数将变量内容复制成输入矩阵同样大小的矩阵
normDataSet = normDataSet/np.tile(ranges,(m,1)) #注意这是具体特征值相除
return normDataSet, ranges, minVals
hoRatio = 0.10 #测试数据所占据比重
datingDataMat,datingLabels = file2matrix('C:\\Users\\dzy520\\Desktop\\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 rate is:%f" %(errorCount/float(numTestVecs)))
def classifyPerson(): #约会网站预测函数,即输入网上的数值测试符合海伦对象的函数
resultList = ['not at all','in small doses','in large doses'] #三种情况,不喜欢,一般,喜欢
percentTats = float(input("percentage oftime spent playing video games?")) #输入玩游戏的占比
ffMiles = float(input("frequent flier miles earned per year?")) #输入旅行距离的占比
iceCream = float(input("liters of ice cream consumed per year?")) #输入吃冰激凌的数量
datingDataMat,datingLabels = file2matrix('C:\\Users\\dzy520\\Desktop\\datingTestSet2.txt')
normMat,ranges,minVals = autoNorm(datingDataMat)
inArr = np.array([ffMiles,percentTats,iceCream]) #将上面三个数据整合成numpy数组
classifierResult = classify0((inArr-minVals)/ranges,normMat,datingLabels,3) #计算是否符合
print("You will probably like this person:",resultList[classifierResult - 1])
#接下来的是手写识别系统
def img2vector(filename): #此函数是为了把图像格式化处理为一个向量。把一个32*32的矩阵转化为1*1024的向量
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]) #将0或者1赋上去
return returnVect
hwLabels = [] #标签空列表
trainingFileList = listdir(r'C:\Users\dzy520\Desktop\machinelearninginaction\Ch02\trainingDigits')
m = len(trainingFileList)
trainingMat = np.zeros((m,1024)) #创建m行1024列训练矩阵,每行数据存储一个图像
for i in range(m):
fileNameStr = trainingFileList[i] #获取标签,也就是获取这个数字是几
fileStr = fileNameStr.split('.')[0] #对文件名进行分割。就是2_45.txt,从 . 那个地方开始分割文件名,就得到2_45和txt两部分,[0]是取前面部分
classNumStr = int(fileStr.split('_')[0]) #再对上步骤处理好的前面部分再从 _ 这里分割,取前面数字
hwLabels.append(classNumStr)
trainingMat[i,:] = img2vector(r'C:\Users\dzy520\Desktop\machinelearninginaction\Ch02\trainingDigits/%s' %fileNameStr) #将fileNameStr所对应的数据写到trainingMat这个矩阵的第i行
testFileList = listdir(r'C:\Users\dzy520\Desktop\machinelearninginaction\Ch02\testDigits')
errorCount = 0.0 #初始化错误率为0
mTest = len(testFileList)
for i in range(mTest):
fileNameStr = testFileList[i]
fileStr = fileNameStr.split('.')[0] #对测试数据进行分割
classNumStr = int(fileStr.split('_')[0])
vectorUnderTest = img2vector(r'C:\Users\dzy520\Desktop\machinelearninginaction\Ch02\testDigits/%s' %fileNameStr)
classifierResult = classify0(vectorUnderTest, trainingMat,hwLabels,3) #由于数据已经是0到1之间所以不需要用上面的autoNorm函数,这个步骤是为了,计算找到最相近的3个即最 开始函数的原理返回发生最多的标签
print("the classifier came 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("\nthe total error rate is: %f"%(errorCount/float(mTest)))
kNN.py源码及注释(python3.x)的更多相关文章
- 3.9 run_main.py源码(兼容python2和3)
3.9 run_main.py源码(兼容python2和3) 以下代码在python2和python3上都跑通过,python3只需注释掉上面红色框框区域代码就行(最后一步发送邮箱代码,我注释掉了). ...
- robotlegs2.0框架实例源码带注释
robotlegs2.0框架实例源码带注释 Robotlegs2的Starling扩展 有个老外写了robotleges2的starling扩展,地址是 https://github.com/brea ...
- Centos7下源码编译安装python3.6
测试环境: 操作步骤: 1. 下载Python源码包(python3.6.0) 官网下载地址:https://www.python.org/downloads/ 搜狐下载地址:http://mirro ...
- eclipse/intellij idea 查看java源码和注释
工作三年了,一直不知道怎么用IDE查看第三方jar包的源码和注释,惭愧啊!看源码还好些,itellij idea自带反编译器,eclipse装个插件即可,看注释就麻烦了,总不能去找api文档吧!现在终 ...
- 完美原创:centos7.1 从源码升级安装Python3.5.2
(原创)完美原创:centos7.1 从源码升级安装Python3.5.2 下载Python3.5.2源码:https://www.python.org/downloads/release/pytho ...
- centos7.1 从源码升级安装Python3.5.2
http://blog.csdn.net/tengyunjiawu_com/article/details/53535153 centos7.1 从源码升级安装Python3.5.2(我写的,请大家度 ...
- Django框架base.py源码
url.py文件 from django.conf.urls import url from django.contrib import admin from app_student import v ...
- 【Eclipse+IntelliJ反编译】Eclipse/IntelliJ IDEA反编译查看源码及注释
怎么用IDE查看第三方jar包的源码和注释,IntelliJ IDEA自带反编译器,Eclipse装个插件即可,不能看注释就麻烦了,总不能去找API文档吧,现在终于掌握了,下面给出解决方案,供大家参考 ...
- ExcelToHtmlTable转换算法:将Excel转换成Html表格并展示(项目源码+详细注释+项目截图)
功能概述 Excel2HtmlTable的主要功能就是把Excel的内容以表格的方式,展现在页面中.Excel的多个Sheet对应页面的多个Tab选项卡.转换算法的难点在于,如何处理行列合并,将Exc ...
随机推荐
- 「CSP」第一届提高组考后总结
「CSP」第一届提高组考后总结 问题分析+反思 成绩 心态 考前心态 考时心态 考后心态 方法 心灵鸡汤... 在学习了三年之后,我们信竞迎来了初中最后一次大考,也是第一次 CSPCSPCSP 考试. ...
- 吴裕雄 Bootstrap 前端框架开发——Bootstrap 按钮:制作一个小按钮
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...
- ubuntu16.04 使用tensorflow object detection训练自己的模型
一.构建自己的数据集 1.格式必须为jpg.jpeg或png. 2.在models/research/object_detection文件夹下创建images文件夹,在images文件夹下创建trai ...
- input文件类型上传,或者作为参数拼接的时候注意的问题!
1.ajax请求参数如果为文本类型,直接拼接即可.如果为file类型就需要先获取文件信息 2.获取文件信息: HTML代码: <div class="form-group"& ...
- Hadoop的伪分布式安装和部署的流程
1.准备工作 下载一些用到的命令 yum install -y vim yum install -y lrzsz yum install net-tools 目录约定 /opt #工作目录 /opt/ ...
- 如何知道某个ACTIVITY是否在前台?
本文链接:http://zengrong.net/post/1680.htm 有一个Android应用包含包含一个后台程序,该程序会定期连接服务器来实现自定义信息的推送.但是,当这个应用处于前台的时候 ...
- LATTICE 编程烧录器HW-USBN-2B使用说明
HW-USBN-2B说明文档 1. 引脚定义 编程引脚 名称 编程设备引脚类型 描述 VCC 编程电压 输入 连接VCC到目标设备,典型的ICC=10Ma.板子设计必须考虑VCC的电流供应 ...
- 「Luogu1402」酒店之王
传送门 Luogu 解题思路 网络流板子题. 建图细节见代码,也可以参考这道差不多的题 细节注意事项 咕咕咕. 参考代码 #include <algorithm> #include < ...
- IdentityServer4专题之三:OAuth、SSO和OpenID
一.oauth 典型案例:如果一个用户R拥有两项服务:一项服务是图片在线存储服务A,另一个是图片在线打印服务B.由于服务A与服务B是由两家不同的服务提供商提供的,所以用户在这两家服务提供商的网站上各自 ...
- 吴裕雄 Bootstrap 前端框架开发——Bootstrap 按钮:按钮标签
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...