import numpy as np
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
def classify0(inX,dataSet,labels,k):                                             #inX是用于分类的输入向量
    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]
def file2matrix(filename):                                                             #将文本记录转换Numpy的解析程序
    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
def datingClassTest():                                                                  #为了测试分类器的工作效率
    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
def handwritingClassTest():
    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)的更多相关文章

  1. 3.9 run_main.py源码(兼容python2和3)

    3.9 run_main.py源码(兼容python2和3) 以下代码在python2和python3上都跑通过,python3只需注释掉上面红色框框区域代码就行(最后一步发送邮箱代码,我注释掉了). ...

  2. robotlegs2.0框架实例源码带注释

    robotlegs2.0框架实例源码带注释 Robotlegs2的Starling扩展 有个老外写了robotleges2的starling扩展,地址是 https://github.com/brea ...

  3. Centos7下源码编译安装python3.6

    测试环境: 操作步骤: 1. 下载Python源码包(python3.6.0) 官网下载地址:https://www.python.org/downloads/ 搜狐下载地址:http://mirro ...

  4. eclipse/intellij idea 查看java源码和注释

    工作三年了,一直不知道怎么用IDE查看第三方jar包的源码和注释,惭愧啊!看源码还好些,itellij idea自带反编译器,eclipse装个插件即可,看注释就麻烦了,总不能去找api文档吧!现在终 ...

  5. 完美原创:centos7.1 从源码升级安装Python3.5.2

    (原创)完美原创:centos7.1 从源码升级安装Python3.5.2 下载Python3.5.2源码:https://www.python.org/downloads/release/pytho ...

  6. centos7.1 从源码升级安装Python3.5.2

    http://blog.csdn.net/tengyunjiawu_com/article/details/53535153 centos7.1 从源码升级安装Python3.5.2(我写的,请大家度 ...

  7. Django框架base.py源码

    url.py文件 from django.conf.urls import url from django.contrib import admin from app_student import v ...

  8. 【Eclipse+IntelliJ反编译】Eclipse/IntelliJ IDEA反编译查看源码及注释

    怎么用IDE查看第三方jar包的源码和注释,IntelliJ IDEA自带反编译器,Eclipse装个插件即可,不能看注释就麻烦了,总不能去找API文档吧,现在终于掌握了,下面给出解决方案,供大家参考 ...

  9. ExcelToHtmlTable转换算法:将Excel转换成Html表格并展示(项目源码+详细注释+项目截图)

    功能概述 Excel2HtmlTable的主要功能就是把Excel的内容以表格的方式,展现在页面中.Excel的多个Sheet对应页面的多个Tab选项卡.转换算法的难点在于,如何处理行列合并,将Exc ...

随机推荐

  1. 怎样把exe程序注册成系统服务

    怎样把exe程序注册成系统服务 最近一段时间我们公司开发一款新的产品,要在服务器上运行一个服务端程序,为了方便我就希望能将这个程序注册成系统服务开机自动启动而不用每次重启系统都要手动启动程序.要实现这 ...

  2. ssh_crm项目

    1.代码 https://pan.baidu.com/s/1hudAhA8  密码:c7xu 2.总结 https://pan.baidu.com/s/1o9ArFf0 密码:hteu 3.资料 ht ...

  3. 编写跨平台Java程序注意事项

    使用Java语言编写应用程序最大的优点在于“一次编译,处处运行”,然而这并不是说所有的Java程序都具有跨平台的特性,事实上,相当一部分的Java程序是不能在别的操作系统上正确运行的,那么如何才能编写 ...

  4. jmeter实现文件下载

    通过浏览器下载文件时,会提示选择保存路径,但是利用测试工具jmeter请求时,在页面看到请求次数是增加了,而本地没有具体下载下来的文件. 需要在具体的文件下载请求下面,添加后置处理器-bean she ...

  5. 【剑指Offer面试编程题】题目1214:丑数--九度OJ

    把只包含因子2.3和5的数称作丑数(Ugly Number).例如6.8都是丑数,但14不是,因为它包含因子7. 习惯上我们把1当做是第一个丑数.求按从小到大的顺序的第N个丑数. 输入: 输入包括一个 ...

  6. 中国6G为什么要从现在上路?

    现在,通信5G的概念早已深入人心,正在从蓝图上的规划走向现实,平心而论,中国在2G/3G/4G时代都没有太突出的表现,或受制于人.或沦为跟随者,如今中国想翻身,于是从一开始就卯足了劲儿抢跑5G,不仅把 ...

  7. BOM--window对象

    BOM 的核心对象是window,它表示浏览器的一个实例.在浏览器中,window 对象有双重角色,它既是通过JavaScript 访问浏览器窗口的一个接口,又是ECMAScript 规定的Globa ...

  8. Windows篇:文件对比软件->"DiffMerge"

    文件对比软件->"DiffMerge" DiffMerge是什么? 如果没有DiffMerge! 想想一下,有两篇10000字的文章,找不同,眼睛都要看花吧.有了DiffMe ...

  9. 098、Java中String类之charAt()方法

    01.代码如下: package TIANPAN; /** * 此处为文档注释 * * @author 田攀 微信382477247 */ public class TestDemo { public ...

  10. Redis的增删改查 c# key value类型和hash map 类型

    using Newtonsoft.Json; using StackExchange.Redis; using System; using System.Collections.Generic; us ...