后端程序员之路 13、使用KNN进行数字识别
尝试一些用KNN来做数字识别,测试数据来自:
MNIST handwritten digit database, Yann LeCun, Corinna Cortes and Chris Burges
http://yann.lecun.com/exdb/mnist/
1、数据
将位图转为向量(数组),k尝试取值3-15,距离计算采用欧式距离。
d(x,y)=\sqrt{\sum_{i=1}^{n}(x_i-y_i)^2}
2、测试
调整k的取值和基础样本数量,测试得出k取值对识别正确率的影响,以及分类识别的耗时。
如何用python解析mnist图片 - 海上扬凡的博客 - 博客频道 - CSDN.NET
http://blog.csdn.net/u014046170/article/details/47445919
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 08 14:38:15 2017
@author: zapline<278998871@qq.com>
"""
import struct
import os
import numpy
def read_file_data(filename):
f = open(filename, 'rb')
buf = f.read()
f.close()
return buf
def loadImageDataSet(filename):
index = 0
buf = read_file_data(filename)
magic, images, rows, columns = struct.unpack_from('>IIII' , buf , index)
index += struct.calcsize('>IIII')
data = numpy.zeros((images, rows * columns))
for i in xrange(images):
imgVector = numpy.zeros((1, rows * columns))
for x in xrange(rows):
for y in xrange(columns):
imgVector[0, x * columns + y] = int(struct.unpack_from('>B', buf, index)[0])
index += struct.calcsize('>B')
data[i, :] = imgVector
return data
def loadLableDataSet(filename):
index = 0
buf = read_file_data(filename)
magic, images = struct.unpack_from('>II' , buf , index)
index += struct.calcsize('>II')
data = []
for i in xrange(images):
lable = int(struct.unpack_from('>B', buf, index)[0])
index += struct.calcsize('>B')
data.append(lable)
return data
def loadDataSet():
path = "D:\\kingsoft\\ml\\dataset\\"
trainingImageFile = path + "train-images.idx3-ubyte"
trainingLableFile = path + "train-labels.idx1-ubyte"
testingImageFile = path + "t10k-images.idx3-ubyte"
testingLableFile = path + "t10k-labels.idx1-ubyte"
train_x = loadImageDataSet(trainingImageFile)
train_y = loadLableDataSet(trainingLableFile)
test_x = loadImageDataSet(testingImageFile)
test_y = loadLableDataSet(testingLableFile)
return train_x, train_y, test_x, test_y
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 08 14:35:55 2017
@author: zapline<278998871@qq.com>
"""
import numpy
def kNNClassify(newInput, dataSet, labels, k):
numSamples = dataSet.shape[0]
diff = numpy.tile(newInput, (numSamples, 1)) - dataSet
squaredDiff = diff ** 2
squaredDist = numpy.sum(squaredDiff, axis = 1)
distance = squaredDist ** 0.5
sortedDistIndices = numpy.argsort(distance)
classCount = {}
for i in xrange(k):
voteLabel = labels[sortedDistIndices[i]]
classCount[voteLabel] = classCount.get(voteLabel, 0) + 1
maxCount = 0
for key, value in classCount.items():
if value > maxCount:
maxCount = value
maxIndex = key
return maxIndex
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 08 14:39:21 2017
@author: zapline<278998871@qq.com>
"""
import dataset
import knn
def testHandWritingClass():
print "step 1: load data..."
train_x, train_y, test_x, test_y = dataset.loadDataSet()
print "step 2: training..."
pass
print "step 3: testing..."
numTestSamples = test_x.shape[0]
matchCount = 0
for i in xrange(numTestSamples):
predict = knn.kNNClassify(test_x[i], train_x, train_y, 3)
if predict == test_y[i]:
matchCount += 1
accuracy = float(matchCount) / numTestSamples
print "step 4: show the result..."
print 'The classify accuracy is: %.2f%%' % (accuracy * 100)
testHandWritingClass()
print "game over"
总结:上述代码跑起来比较慢,但是在train数据够多的情况下,准确率不错
后端程序员之路 13、使用KNN进行数字识别的更多相关文章
- 后端程序员之路 12、K最近邻(k-Nearest Neighbour,KNN)分类算法
K最近邻(k-Nearest Neighbour,KNN)分类算法,是最简单的机器学习算法之一.由于KNN方法主要靠周围有限的邻近的样本,而不是靠判别类域的方法来确定所属类别的,因此对于类域的交叉或重 ...
- 后端程序员之路 59、go uiprogress
gosuri/uiprogress: A go library to render progress bars in terminal applicationshttps://github.com/g ...
- 后端程序员之路 52、A Tour of Go-2
# flowcontrol - for - for i := 0; i < 10; i++ { - for ; sum < 1000; { ...
- 后端程序员之路 43、Redis list
Redis数据类型之LIST类型 - Web程序猿 - 博客频道 - CSDN.NEThttp://blog.csdn.net/thinkercode/article/details/46565051 ...
- 后端程序员之路 22、RESTful API
理解RESTful架构 - 阮一峰的网络日志http://www.ruanyifeng.com/blog/2011/09/restful.html RESTful API 设计指南 - 阮一峰的网络日 ...
- 后端程序员之路 16、信息熵 、决策树、ID3
信息论的熵 - guisu,程序人生. 逆水行舟,不进则退. - 博客频道 - CSDN.NEThttp://blog.csdn.net/hguisu/article/details/27305435 ...
- 后端程序员之路 7、Zookeeper
Zookeeper是hadoop的一个子项目,提供分布式应用程序协调服务. Apache ZooKeeper - Homehttps://zookeeper.apache.org/ zookeeper ...
- 后端程序员之路 4、一种monitor的做法
record_t包含_sum._count._time_stamp._max._min最基础的一条记录,可以用来记录最大值.最小值.计数.总和metric_t含有RECORD_NUM(6)份recor ...
- 后端程序员之路 58、go wlog
daviddengcn/go-colortext: Change the color of console text.https://github.com/daviddengcn/go-colorte ...
随机推荐
- Java初体验
参考书籍「Java语言程序设计基础篇」 比特与字节 计算机中只有0和1,二进制,即比特(bit,二进制数): 字节(byte)是最小的存储单元,每个字节有8个比特组成 即:1byte=8bit 各种数 ...
- BZOJ 3675: 序列分割 (斜率优化dp)
Description 小H最近迷上了一个分隔序列的游戏.在这个游戏里,小H需要将一个长度为n的非负整数序列分割成k+1个非空的子序列.为了得到k+1个子序列,小H需要重复k次以下的步骤: 1.小H首 ...
- Codeforces 1144F Graph Without Long Directed Paths DFS染色
题意: 输入一张有向图,无自回路和重边,判断能否将它变为有向图,使得图中任意一条路径长度都小于2. 如果可以,按照输入的边的顺序输出构造的每条边的方向,构造的边与输入的方向一致就输出1,否则输出0. ...
- hdu2126 Buy the souvenirs
Problem Description When the winter holiday comes, a lot of people will have a trip. Generally, ther ...
- Codeforces Round #479 (Div. 3) C. Less or Equal (排序,贪心)
题意:有一个长度为\(n\)的序列,要求在\([1,10^9]\)中找一个\(x\),使得序列中恰好\(k\)个数满足\(\le x\).如果找不到\(x\),输出\(-1\). 题解:先对这个序列排 ...
- jackson学习之十(终篇):springboot整合(配置类)
欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...
- Redis 多实例 & 主从复制
Redis 多实例 多实例目录 [root@db01 ~]# mkdir /service/redis/{6380,6381} 多实例配置文件 # 第一台多实例配置 [root@db01 ~]# vi ...
- CS144学习(2)TCP协议实现
Lab1-4 分别是完成一个流重组器,TCP接收端,TCP发送端,TCP连接四个部分,将四个部分组合在一起就是一个完整的TCP端了.之后经过包装就可以进行TCP的接收和发送了. 代码全部在github ...
- pure CSS3 实现三角形icon的方法
pure CSS3 实现三角形icon的方法 border: color+transparent transform : rotate() /rotateZ() ? 使用 实体字符"◆&qu ...
- holy shit CSDN
holy shit CSDN 垃圾 CSDN 到处都是垃圾文章, 无人子弟 到处都是垃圾广告,看的恶心 毫无底线,窃取别人的知识成果,毫无版权意识 垃圾爬虫,垃圾小号 ...等等 Google Sea ...