尝试一些用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. 2019牛客暑期多校训练营(第七场)E-Find the median(思维+树状数组+离散化+二分)

    >传送门< 题意:给n个操作,每次和 (1e9范围内)即往数组里面插所有 的所有数,求每次操作后的中位数思路:区间离散化然后二分答案,因为小于中位数的数字恰好有个,这显然具有单调性.那么问 ...

  2. Codeforces Global Round 9 B. Neighbor Grid

    题目链接:https://codeforces.com/contest/1375/problem/B 题意 给出一个 $n \times m$ 的方阵,每个方格中有一个非负整数,一个好方格定义如下: ...

  3. AtCoder Beginner Contest 169

    比赛链接:https://atcoder.jp/contests/abc169/tasks A - Multiplication 1 #include <bits/stdc++.h> us ...

  4. hdu-6699 Block Breaker

    题意: 就是给你一个n行m列的矩形,后面将会有q次操作,每次操作会输入x,y表示要击碎第x行第y列的石块,当击碎它之后还去判断一下周围石块是否牢固 如果一个石块的左右两边至少一个已经被击碎且上下也至少 ...

  5. Long Long Message POJ - 2774 后缀数组

    The little cat is majoring in physics in the capital of Byterland. A piece of sad news comes to him ...

  6. CF1462-F. The Treasure of The Segments

    题意: 给出n个线段组成的集合,第i个线段用 \(\{l_i, r_i\}\) 表示线段从坐标轴的点\(l_i\)横跨到点\(r_i\).现在你可以删除其中的一些线段,使得剩下的线段组成的集合中至少存 ...

  7. ArcGIS处理栅格数据(三)

    六.制作镶嵌数据集(栅格数据集优点:a.浏览速度快:b.入库速度快:c.可指定区域显示) 1.右键目录中的数据库,新建"镶嵌数据集". 2.添加栅格数据. 3.定义金字塔. 4.构 ...

  8. SPOJ REPEATS Repeats (后缀数组 + RMQ:子串的最大循环节)题解

    题意: 给定一个串\(s\),\(s\)必有一个最大循环节的连续子串\(ss\),问最大循环次数是多少 思路: 我们可以知道,如果一个长度为\(L\)的子串连续出现了两次及以上,那么必然会存在\(s[ ...

  9. 设置chromium的默认搜索引擎为Bing

    设置 -> 搜索 -> 管理搜索引擎 第三项中添加: http://cn.bing.com/search?q=%s 即可.

  10. React Gatsby 最新教程

    React Gatsby 最新教程 https://www.gatsbyjs.com/docs/quick-start/ https://www.gatsbyjs.com/docs/tutorial/ ...