尝试一些用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. Python3.9.1中如何使用split()方法?

    本文出自:lunvey,半路出家学编程之Python.split()方法定义于str类中,str类大家都知道是python内置定义的一个字符串类. split()默认两个参数,分别是分隔符和分隔数量, ...

  2. RAID 技术全解

    图文并茂 RAID 技术全解 – RAID0.RAID1.RAID5.RAID100-- RAID 技术相信大家都有接触过,尤其是服务器运维人员,RAID 概念很多,有时候会概念混淆.这篇文章为网络转 ...

  3. 2019牛客暑期多校训练营(第七场)H.Pair(数位dp)

    题意:给你三个数A,B,C 现在要你找到满足  A and B >C 或者 A 异或 B < C 的对数. 思路:我们可以走对立面 把既满足 A and B <= C 也满足 A 异 ...

  4. windows10与linux进行ftp遇到550 Failed to change directory及553 Could not creat file

    第一个原因: 没有权限,可以使用带有l参数的ls命令来看文件或者目录的权限 ls -l 解决:给本地用户添加一个可写权限 chmod +w /home/student ##给对应的本地用户添加一个可写 ...

  5. POJ1142 Smith Numbers 暴力+分解质因子

    题意:题目定义了一个史密斯数,这个数的定义是:一个合数的各个位置上加起来的和等于它的素因数所有位置上的数字加起来的和.比如: 4937775=3∗5∗5∗658374+9+3+7+7+7+5=3+5+ ...

  6. Nestjs入门学习教程

    初次接触Nest,有问题欢迎指出: 简介 NestJS是一个用于构建高效.可扩展的Node.js服务器端应用程序的开发框架.简单来说是一款Node.js的后端框架. 它利用JavaScript的渐进增 ...

  7. 在kubernetes集群里集成Apollo配置中心(1)之交付Apollo-configservice至Kubernetes集群

    1.Apollo简介 Apollo(阿波罗)是携程框架部门研发的分布式配置中心,能够集中化管理应用不同环境.不同集群的配置,配置修改后能够实时推送到应用端,并且具备规范的权限.流程治理等特性,适用于微 ...

  8. linux 基础正则表达式练习

    感谢鸟哥!!! 如果Linux能够直接连网络,使用以下命令还获取文件吧 wget http://linux.vbird.org/linux_basic/0330regularex/regular_ex ...

  9. sql-libs(1) -字符型注入

    关于sql-libs的安装就不做过多的说明, 环境:win7虚拟机 192.168.48.130(NAT连接),然后用我的win10物理机去访问. 直接加 ' 报错,后测试 and '1'='1 成功 ...

  10. Vue2.0 多种组件传值方法-不过如此的 Vuex

    码文不易啊,转载请带上本文链接呀,感谢感谢 https://www.cnblogs.com/echoyya/p/14404397.html 在vue项目中了解组件间通讯很重要,也是最基础的面试题,可以 ...