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 ...
随机推荐
- 工具 - brackets
常用插件 blueprint beta file tree view indent guidelines
- 为什么maven没有.m2文件
该问题可能描述不清,建议你重新提问 为什么maven没有.m2文件 彼岸之恋°DD | 浏览 4793 次 问题未开放回答 2016-09-23 17:29 最佳答案 对于初学者在安装配置好maven ...
- vue 输入框数字、中文验证
vue项目是基于element框架做的,在做form表单时,要做些验证,element框架也提供了自定义验证 下面是一些常见的验证 只允许输入数字: 可以直接用框架的rule去验证,但必须在model ...
- IDEA 服务器热部署详解(On Update action/On frame deactivation)
https://blog.csdn.net/w15321271041/article/details/80597962 场景:一般服务器(比如tomcat,jboss等)启动以后,我们还需要进一步修改 ...
- 3.8.1 HTML与CSS简单页面效果实例
HTML与CSS简单页面效果实例 <!DOCTYPE html> <html> <head> <meta charset="utf-8" ...
- 多选按钮CheckBox
main.xml: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmln ...
- 引用类型--Function类型(函数声明与函数表达式、arguments.callee、caller、apply、call、bind)
在ECMAScript中函数实际上是对象.每个函数都是Function类型的实例,而且都与其他引用类型一样具有属性和方法.由于函数是对象,因此函数名实际上也是一个指向函数对象的指针,不会与某个函数绑定 ...
- 【高软作业2】:Java IDE调研分析
一 序言 随着软件项目开发需求的增多,拥有一款优秀的.顺手的IDE(Integrated Development Environment)对程序员来说显得格外重要.本文就Java程序开发,选择了3款I ...
- 隐患写法flag.equals("true")带来的空指针异常
分类:2008-06-04 12:47 467人阅读 评论(0) 收藏 举报 linuxjava测试 昨天,有同事A对同事B写的程序进行测试时,出现错误,看控制台信息,发现抛出了空指针异常. 调查结果 ...
- CodeForces - 869A The Artful Expedient
题意:有两个序列X和Y,各含n个数,这2n个数互不相同,若满足xi^yj的结果在序列X内或序列Y内的(xi,yj)对数为偶数,则输出"Karen",否则输出"Koyomi ...