后端程序员之路 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 ...
随机推荐
- Hadoop----hdfs dfs常用命令的使用
用法 -mkdir 创建目录 Usage:hdfs dfs -mkdir [-p] < paths> 选项:-p 很像Unix mkdir -p,沿路径创建父 ...
- PTA刷题记录
考虑到PAT甲级考试和开学后的XCPC比赛,决定寒假把PAT (Advanced Level) Practice刷完,进度条会在这篇博客下更新.由于主要以记录为主,大体上不会像单篇题解那么详细,但是对 ...
- AtCoder Beginner Contest 176
比赛链接:https://atcoder.jp/contests/abc176 A - Takoyaki #include <bits/stdc++.h> using namespace ...
- 【uva 11491】Erasing and Winning(算法效率--贪心+单调队列)
题意:有一个N位整数,要求输出删除其中D个数字之后的最大整数. 解法:贪心.(P.S.要小心,我WA了2次...)由于规定了整数的位数,那么我们要尽量让高位的数字大一些,也就是要尽量删去前面小的数字. ...
- 【noi 2.6_8787】数的划分(DP){附【转】整数划分的解题方法}
题意:问把整数N分成K份的分法数.(与"放苹果"不同,在这题不可以有一份为空,但可以类比)解法:f[i][j]表示把i分成j份的方案数.f[i][j]=f[i-1][j-1](新开 ...
- Bing壁纸-20200416
- OpenStack-知识点补充
登录计算节点查看进程 [root@compute ~]# ps aux | grep kvm root 824 0.0 0.0 0 0 ? S< 10:19 0:00 [kvm-irqfd-cl ...
- Linux 应用开发----socket编程笔记
Linux socket编程 套接字定义描述 套接字的域 AF_INET ====>IPv4 AF_INET6 ====>IPv6 AF_UNIX ====>unix 域 AF_UP ...
- Adobe DreamWeaver CC 快捷键
1 1 ADOBE DREAMWEAVER CC Shortcuts: DREAMWEAVER CC DOCUMENT EDITING SHORTCUTS Select Dreamweaver > ...
- How to unblock GitHub DMCA takedown repo
How to unblock GitHub DMCA takedown repo 如何解封 GitHub DMCA takedown 的仓库 support@github.com 发件人: GitHu ...