最后,我们要进行手写数字分类任务,但是现在我们是用kNN算法,可能会比较慢

首先,完整地看完2.3.1和2.3.2的内容,然后找到trainingDigits和testDigits文件夹,大致浏览下



那么思路应该是:

  • 从文件夹中获取文件名,,并且文件名中包含了标记,再分别打开每个文件
  • 对打开的每个文件,对其向量化
  • 然后从上述文件获得的每个向量,数据集,标记集和选定的k,用分类器进行输出
import numpy as np

def txt2vec(filename):
# 32*32的规模,用1*1024的向量接收
vecContent = np.zeros((1, 1024))
with open(filename, 'r') as fobj:
for i in range(32):
line = fobj.readline()
for j in range(32):
vecContent[0, 32 * i + j] = int(line[j])
return vecContent # 打印输出看一下结果
filename = './trainingDigits/0_0.txt'
a = txt2vec(filename)
print(a[0, 0:64]) [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 1. 1. 1. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 1. 1. 1.
1. 1. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]

没有问题,这样我们的txt转换成vector函数就做好了

接下来,有一个难点,要把trainingDigits和testDigits文件夹的文件名分别获得,并得到标记

需要使用listdir函数,需要从os导包

import numpy as np
from os import listdir
trainingFilePath = './trainingDigits'
testFilePath = './testDigits'
# 获得trainingDigits的各文件
trainingFileList = listdir(trainingFilePath)
# 获得标记集
labelSet = []
dataSetNum = len(trainingFileList)
print(dataSetNum) 1934

之后便把之前写的代码综合起来

import numpy as np
import kNN def txt2vec(filename):
# 32*32的规模,用1*1024的向量接收
vecContent = np.zeros((1, 1024))
with open(filename, 'r') as fobj:
for i in range(32):
line = fobj.readline()
for j in range(32):
vecContent[0, 32 * i + j] = int(line[j])
return vecContent # 打印输出看一下结果
# filename = './trainingDigits/0_0.txt'
# a = txt2vec(filename)
# print(a[0, 0:64]) trainingFilePath = './trainingDigits'
testFilePath = './testDigits' from os import listdir def hwPredict():
# 获得trainingDigits的各文件
trainingFileList = listdir(trainingFilePath)
# 获得标记集
labelSet = []
dataSetNum = len(trainingFileList)
# 获得数据集
dataSet = np.zeros((dataSetNum, 1024))
# print(dataSetNum)
for i in range(dataSetNum):
# 获得每一个txt文件
eachTrainingFile = trainingFileList[i]
# 因为文件时0_0.txt类型,所以先按.分割,再按_分割
eachTrainingFile = eachTrainingFile.split('.')[0]
eachTrainingFileLabel = int(eachTrainingFile.split('_')[0])
labelSet.append(eachTrainingFileLabel)
# 通过txt2vec获得数据集
trainingFilename = 'trainingDigits/' + eachTrainingFile + '.txt'
dataSet[i, :] = txt2vec(trainingFilename)
# print(len(dataSet))
# print(dataSet.shape)
# print(type(dataSet))
# print(labelSet)
# 现在我们的数据集和label都做好了
# 开始用测试集的数据来进行判断 testFileList = listdir(testFilePath)
# print(testFileList)
errorCount = 0.0
testSetNum = len(testFileList)
# print(testSetNum)
for i in range(testSetNum):
# 老样子,先进行每个向量的划分
eachTestFile = testFileList[i]
# print(eachTestFile)
eachTestFile = eachTestFile.split('.')[0]
# print(eachTestFile)
eachTestFileLabel = int(eachTestFile.split('_')[0])
# 转换成向量
testFilename = 'trainingDigits/' + eachTestFile + '.txt'
testVector = txt2vec(testFilename)
# print(testVector)
testClassifierResult = kNN.classifier(testVector,dataSet,labelSet,3)
print("the classifier came back with:%d,the real answer is:%d"%(testClassifierResult,eachTestFileLabel))
if testClassifierResult != eachTestFileLabel:
errorCount += 1.0
print("\nthe total number of errors is:",errorCount)
print("\nthe total error rate is:",errorCount/testSetNum) hwPredict()

结果如下:

the classifier came back with:0,the real answer is:0
the classifier came back with:0,the real answer is:0
the classifier came back with:0,the real answer is:0
...
the classifier came back with:9,the real answer is:9
the classifier came back with:9,the real answer is:9 the total number of errors is: 13.0 the total error rate is: 0.013742071881606765

kNN算法至此告一段落,代码均上传至https://github.com/lpzju/-

kNN算法在分类算法中最简单最有效,但是复杂度也比较大,且使用大量存储空间。另一个缺点是无法给出任何数据的基础结构信息

kNN-识别手写数字的更多相关文章

  1. KNN识别手写数字

    一.问题描述 手写数字被存储在EXCEL表格中,行表示一个数字的标签和该数字的像素值,有多少行就有多少个样本. 一共42000个样本 二.KNN KNN最邻近规则,主要应用领域是对未知事物的识别,即判 ...

  2. KNN实现手写数字识别

    KNN实现手写数字识别 博客上显示这个没有Jupyter的好看,想看Jupyter Notebook的请戳KNN实现手写数字识别.ipynb 1 - 导入模块 import numpy as np i ...

  3. KNN 算法-实战篇-如何识别手写数字

    公号:码农充电站pro 主页:https://codeshellme.github.io 上篇文章介绍了KNN 算法的原理,今天来介绍如何使用KNN 算法识别手写数字? 1,手写数字数据集 手写数字数 ...

  4. 使用神经网络来识别手写数字【译】(三)- 用Python代码实现

    实现我们分类数字的网络 好,让我们使用随机梯度下降和 MNIST训练数据来写一个程序来学习怎样识别手写数字. 我们用Python (2.7) 来实现.只有 74 行代码!我们需要的第一个东西是 MNI ...

  5. 学习笔记TF024:TensorFlow实现Softmax Regression(回归)识别手写数字

    TensorFlow实现Softmax Regression(回归)识别手写数字.MNIST(Mixed National Institute of Standards and Technology ...

  6. TensorFlow实战之Softmax Regression识别手写数字

         关于本文说明,本人原博客地址位于http://blog.csdn.net/qq_37608890,本文来自笔者于2018年02月21日 23:10:04所撰写内容(http://blog.c ...

  7. 一文全解:利用谷歌深度学习框架Tensorflow识别手写数字图片(初学者篇)

    笔记整理者:王小草 笔记整理时间2017年2月24日 原文地址 http://blog.csdn.net/sinat_33761963/article/details/56837466?fps=1&a ...

  8. python手写神经网络实现识别手写数字

    写在开头:这个实验和matlab手写神经网络实现识别手写数字一样. 实验说明 一直想自己写一个神经网络来实现手写数字的识别,而不是套用别人的框架.恰巧前几天,有幸从同学那拿到5000张已经贴好标签的手 ...

  9. 3 TensorFlow入门之识别手写数字

    ------------------------------------ 写在开头:此文参照莫烦python教程(墙裂推荐!!!) ---------------------------------- ...

  10. 用BP人工神经网络识别手写数字

    http://wenku.baidu.com/link?url=HQ-5tZCXBQ3uwPZQECHkMCtursKIpglboBHq416N-q2WZupkNNH3Gv4vtEHyPULezDb5 ...

随机推荐

  1. numpy计算数组中满足条件的个数

    Numpy计算数组中满足条件元素个数 需求:有一个非常大的数组比如1亿个数字,求出里面数字小于5000的数字数目 1. 使用numpy的random模块生成1亿个数字 2. 使用Python原生语法实 ...

  2. js中一个函数调用另一个函数变量;判断鼠标按住/手指左右滑动

    <script> function myFunction() { var x1=event.clientX;//只需要将被调用的变量前的var删除即可在下个函数调用: document.g ...

  3. WebView的一些简单用法

    一直想写一个关于 WebView 控件的 一些简单运用,都没什么时间,这次也是挤出时间写的,里面的一些基础知识就等有时间再更新讲解一下,今天就先把项目出来做一些简单介绍,过多的内容可以看我的源码,都传 ...

  4. python-使用函数求余弦函数的近似值

    本题要求实现一个函数,用下列公式求cos(x)近似值,精确到最后一项的绝对值小于eps(绝对值小于eps的项不要加): cos(x)=0!x0​−2!x2​+4!x4​−6!x6​+... 函数接口定 ...

  5. java中输出一个字符串里面的空格,字母还有数字的数目举例说明

    9.6 About string,"I am a teacher",这个字符串中有多少个字,且分别把每个字打印出来. /*本题的思路就是,当我有一个字符串,我需要一个一个字符的处理 ...

  6. audio微信自动播放以及自定义样式

    audio标签如下: <audio id="audioTag" src="" autoplay="autoplay" controls ...

  7. 基于express框架的留言板实现步骤

    这个留言板是基于express框架,和ejs模板引擎,首先需要在根目录安装express框架,然后安装ejs模块和body-parser(获取用户表单提交的数据):建立项目目录 message,然后依 ...

  8. FastAPI(七十一)实战开发《在线课程学习系统》接口开发-- 查看留言

    之前FastAPI(七十)实战开发<在线课程学习系统>接口开发--留言功能开发分享了留言开发,这次我们分享查看留言 梳理这里的逻辑,这个接口要依赖登录. 1.判断用户是否登录 2.判断对应 ...

  9. 对 rest 参数的理解

    扩展运算符被用在函数形参上时,它还可以把一个分离的参数序列整合成一个数组: function mutiple(...args) { let result = 1; for (var val of ar ...

  10. spring报错can't find resources

    整合spring的时候报错can't find resource[../././.xml] 这两天在整个spring,发现单元测试的时候就可以正常运行,放在tomcat中就报错initial cont ...