尝试一些用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. 一文弄懂-《Scalable IO In Java》

    目录 一. <Scalable IO In Java> 是什么? 二. IO架构的演变历程 1. Classic Service Designs 经典服务模型 2. Event-drive ...

  2. VScode 连接虚拟机

    VScode 连接虚拟机 在VScode上面使用SSH连接虚拟机,编写代码以及运行都将会方便许多 打开VScode,安装Remote-SSH插件 配置SSH连接信息 点击左侧第四个图标,然后单击设置按 ...

  3. C++实现邻接表

    对于无向图(V0,V1),(V1,V2),(V2,V3),(V0,V2)对应的邻接表表示就是 在代码中,你要单独对V1.V2.V3创建一种结构体类型.在对后面的节点0,1,2,3创建一种结构体类型 代 ...

  4. SQL 计算表A字段在表B字段中出现的次数

    SELECT A.Id,A.Name,COUNT(B.LiveID) AS count from SetLiveHistory B RIGHT JOIN Live A ON B.LiveId=A.Id ...

  5. Chapter Zero 0.1.4 计算机上常用的计算单位

    0.1 计算机硬件 计算机上常用的计算单位 容量单位: 计算机对于数据的判断依据有没有通电来记录信息,对于每个记录而言, 他只认识0或1,而0/1这个二进制单位我们成为bit. 因为bit太小,所以存 ...

  6. HDU 6611 K Subsequence(Dijkstra优化费用流 模板)题解

    题意: 有\(n\)个数\(a_1\cdots a_n\),现要你给出\(k\)个不相交的非降子序列,使得和最大. 思路: 费用流建图,每个点拆点,费用为\(-a[i]\),然后和源点连边,和后面非降 ...

  7. Gym 101170I Iron and Coal(BFS + 思维)题解

    题意:有一个有向图,有些点是煤,有些点是铁,但不会同时有铁和煤.现在我要从1出发,占领可以到达的点.问最少占领几个点能同时拥有一个煤和一个铁(1不用占领). 思路:思路很秀啊.我们从1往外bfs,得到 ...

  8. 使用opencv-python实现MATLAB的fspecial('Gaussian', [r, c], sigma)

    reference_opencv实现高斯核 reference_MATLAB_fspecial函数说明 # MATLAB H = fspecial('Gaussian', [r, c], sigma) ...

  9. js script all in one

    js script all in one 你不知道的 js secret https://html.spec.whatwg.org/multipage/scripting.html https://h ...

  10. App Store Connect

    App Store Connect https://developer.apple.com/support/app-store-connect/ https://developer.apple.com ...