尝试一些用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进行数字识别的更多相关文章

  1. 后端程序员之路 12、K最近邻(k-Nearest Neighbour,KNN)分类算法

    K最近邻(k-Nearest Neighbour,KNN)分类算法,是最简单的机器学习算法之一.由于KNN方法主要靠周围有限的邻近的样本,而不是靠判别类域的方法来确定所属类别的,因此对于类域的交叉或重 ...

  2. 后端程序员之路 59、go uiprogress

    gosuri/uiprogress: A go library to render progress bars in terminal applicationshttps://github.com/g ...

  3. 后端程序员之路 52、A Tour of Go-2

    # flowcontrol    - for        - for i := 0; i < 10; i++ {        - for ; sum < 1000; {        ...

  4. 后端程序员之路 43、Redis list

    Redis数据类型之LIST类型 - Web程序猿 - 博客频道 - CSDN.NEThttp://blog.csdn.net/thinkercode/article/details/46565051 ...

  5. 后端程序员之路 22、RESTful API

    理解RESTful架构 - 阮一峰的网络日志http://www.ruanyifeng.com/blog/2011/09/restful.html RESTful API 设计指南 - 阮一峰的网络日 ...

  6. 后端程序员之路 16、信息熵 、决策树、ID3

    信息论的熵 - guisu,程序人生. 逆水行舟,不进则退. - 博客频道 - CSDN.NEThttp://blog.csdn.net/hguisu/article/details/27305435 ...

  7. 后端程序员之路 7、Zookeeper

    Zookeeper是hadoop的一个子项目,提供分布式应用程序协调服务. Apache ZooKeeper - Homehttps://zookeeper.apache.org/ zookeeper ...

  8. 后端程序员之路 4、一种monitor的做法

    record_t包含_sum._count._time_stamp._max._min最基础的一条记录,可以用来记录最大值.最小值.计数.总和metric_t含有RECORD_NUM(6)份recor ...

  9. 后端程序员之路 58、go wlog

    daviddengcn/go-colortext: Change the color of console text.https://github.com/daviddengcn/go-colorte ...

随机推荐

  1. 一周精彩内容分享(第 1 期):"世纪逼空大战"

    这里记录过去一周,我看到的值得分享的东西. 一方面是整理记录一下自己一周的学习,另一方面也是期待自己有更多的输出,有更多的价值. 周刊开源(Github:wmyskxz/weekly),欢迎提交 is ...

  2. 2019牛客暑期多校训练营(第二场) H-Second Large Rectangle(单调栈)

    题意:给出由01组成的矩阵,求求全是1的次大子矩阵. 思路: 单调栈 全是1的最大子矩阵的变形,不能直接把所有的面积存起来然后排序取第二大的,因为次大子矩阵可能在最大子矩阵里面,比如: 1 0 0 1 ...

  3. Educational Codeforces Round 17

    Educational Codeforces Round 17 A. k-th divisor 水题,把所有因子找出来排序然后找第\(k\)大 view code //#pragma GCC opti ...

  4. Codeforces Round #627 (Div. 3) D - Pair of Topics(双指针)

    题意: 有长为n的a,b两序列,问满足ai+aj>bi+bj(i<j)的i,j对数. 思路: 移项得:(ai-bi)+(aj-bj)>0,i<j即i!=j,用c序列保存所有ai ...

  5. codeforces644B. Processing Queries (模拟)

    In this problem you have to simulate the workflow of one-thread server. There are n queries to proce ...

  6. 【noi 2.6_9289】Ant Counting 数蚂蚁{Usaco2005 Nov}(DP)

    题意:有M个家族的蚂蚁,各Ni只(互相相同).问选出 l~r 只的不同方案数. 解法:很基础的一种DP,不要被"排列组合"所迷惑了啊~我之前接触过这个类型,可惜又忘了,一定要记住! ...

  7. Java 窗口 绘制图形 #2

    写在前面: 高考结束咧,爽到啊,好耶 完善了Java 窗口 绘制图形 #1里面的程序 加入了缩放平移功能,给代码加了注释 1 package my_package; 2 3 import java.a ...

  8. How many integers can you find HDU - 1796 容斥原理

    题意: 给你一个数n,找出来区间[1,n]内有多少书和n不互质 题解: 容斥原理 这一道题就让我真正了解容斥原理的实体部分 "容斥原理+枚举状态,碰到奇数加上(n-1)/lcm(a,b,c. ...

  9. poj 3436 ACM Computer Factory 最大流+记录路径

    题目 题意: 每一个机器有一个物品最大工作数量,还有一个对什么物品进行加工,加工后的物品是什么样.给你无限多个初始都是000....的机器,你需要找出来经过这些机器操作后最多有多少成功的机器(111. ...

  10. Hyper-V安装CentOS修改分辨率

    grubby --update-kernel=ALL --args="video=hyperv_fb:1600x900" reboot https://blog.csdn.net/ ...