后端程序员之路 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 ...
随机推荐
- 2020Nowcode多校 Round5 C. Easy
C. Easy 构造两个序列分别要满足 \(\sum_{i=1}^{k} a_{i} = N\) \(\sum_{i=1}^{k} b_{i} = M\) 一种方案能贡献\(\prod_{i=1}^{ ...
- Codeforces Round #622 (Div. 2) C2. Skyscrapers (hard version)(单调栈,递推)
Codeforces Round #622 (Div. 2) C2. Skyscrapers (hard version) 题意: 你是一名建筑工程师,现给出 n 幢建筑的预计建设高度,你想建成峰状, ...
- HDU6504 Problem E. Split The Tree【dsu on tree】
Problem E. Split The Tree Problem Description You are given a tree with n vertices, numbered from 1 ...
- DNS 是什么?如何运作的?
前言 我们在上一篇说到,IP 地址的发明把我们纷乱复杂的网络设备整齐划一地统一在了同一个网络中. 但是类似于 192.168.1.0 这样的地址并不便于人类记忆,于是发明了 域名(Domain Nam ...
- 《软件建模与分析》——UML基本概念
UML-基本概念 UML本质上是一种语言,语言的学习离不开基本的单词(元素)和语法(视图.模型)的学习,今天我们就从它们开始. 元素 类图中的关系 控制权限 继承 实现 依赖:一个类A使用到了另一个类 ...
- 牛客网多校第9场 E Music Game 【思维+数学期望】
题目:戳这里 题意:鼠标点击n下,第i次点击成功的概率为p[i],连续点击成功x次可以获得x^m分,求n次点击总分数的数学期望. 解题思路:数学期望的题很多都需要转化思维,求某一个单独状态对整体答案的 ...
- 桶排序 && leetcode 41
桶排序 对于0-1000 ,用1001个桶 简单版 或者用10个桶0-9,先按各位装桶,然后依(桶)次放回,然后再按十位放桶,放回,然后百位. 也就是基数排序 https://www.cnblogs ...
- js的变量,作用域,内存
一,基本类型和引用类型的值基本类型的值是按值访问的,引用类型的值是保存在内存中的对象1,动态的属性 只有引用类型的值可以添加属性方法 不能给基本类型添加属性和方法2,复制变量值 复制基本类型的值,两个 ...
- 编写一个c函数,该函数给出一个字节中被置为1的位的个数
请编写一个c函数,该函数给出一个字节中被置为1的位的个数 #include <stdio.h> void fun(char ch) { int i; int temp; int count ...
- php 配置主机虚拟目录(使用虚拟域名访问 127.0.0.1) 一点也不好使?????
php 配置主机虚拟目录(使用虚拟域名访问 127.0.0.1)steps:1>打开目录 D:\xwamp\bin\apache\apache2.4.9\conf 修改文件 httpd ...