后端程序员之路 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 ...
随机推荐
- C - C(换钱问题)
换钱问题: 给出n种钱,m个站点,现在有第 s种钱,身上有v 这么多: 下面 m行 站点有a,b两种钱,rab a->b的汇率,cab a-->b的手续费, 相反rba cba : 问在 ...
- HDU6321 Dynamic Graph Matching【状压DP 子集枚举】
HDU6321 Dynamic Graph Matching 题意: 给出\(N\)个点,一开始没有边,然后有\(M\)次操作,每次操作加一条无向边或者删一条已经存在的边,问每次操作后图中恰好匹配\( ...
- python+requests爬取百度文库ppt
实验网站:https://wenku.baidu.com/view/c7752014f18583d04964594d.html 在下面这种类型文件中的请求头的url打开后会得到一个页面 你会得到如下图 ...
- c#中几种常见的数据结构
数组(Array): 1.数组存储在连续的内存上 2.数组的元素类型必须相同 3.数组可以直接通过下标访问 4.查找与修改元素的速度非常快 5.必须在声明时指定长度 动态数组(ArrayLis ...
- WPF 中的逻辑树(Logical Tree)与可视化元素树(Visual Tree)
一.前言 WPF 中有两种"树":逻辑树(Logical Tree)和可视化元素树(Visual Tree). Logical Tree 最显著的特点就是它完全由布局组件和控件 ...
- 快速获取 Wi-Fi 密码——GitHub 热点速览 v.21.06
作者:HelloGitHub-小鱼干 还有 2 天开启春节七天宅家生活,GitHub 也凑了一把春节热闹,wifi-password 连续霸榜 3 天,作为一个能快速让你连上 Wi-Fi 的小工具,春 ...
- Zabbix 配置监控 & 触发器
Zabbix 自定义监控 zabbix-agent 获取数据,然后定义,交给 zabbix-server 端 Zabbix 配置监控项 监控的内容 # 监控服务器登录用户的数量 [root@web01 ...
- nginx的log、upstream和server
一.log 首先一个log格式化的例子. #配置格式main的log log_format main '$host $status [$time_local] $remote_addr [$time_ ...
- IFIX 5.9 历史数据 曲线 (非SQL模式)
装完 ifix 5.9 默认是没有Hist 开头的 历史数据源的,没存,至少我装的版本是这样. 那个Historian 也没有安装包,好像还要授权,自己研究不了. 1 先把数据存本地 在你的安装包里 ...
- mybatis(三)配置mapper.xml 的基本操作
参考:https://www.cnblogs.com/wuzhenzhao/p/11101555.html XML 映射文件 本文参考mybatis中文官网进行学习总结:http://www.myba ...