A handwritten digital recognizer implemented in Python

Source: Internet
Author: User

A handwritten digital recognizer with a GUI interface, based on the Python Sklearn KNN algorithm, can be used to recognize handwritten numbers and train datasets as mnist. Detailed code download: http://www.demodashi.com/demo/13039.html Preface

The K-Nearest neighbor (KNN, K-nearestneighbor) algorithm is a basic classification and regression method,
In the popular point, it is given a training data set, to the new input instance, in the training data set to find the closest to the instance of the K instances, the K instances of the majority of a class, the input instance is divided into this class.

The Python third-party library Scikit-learn (Sklearn) provides a KNN classifier.

Mnist handwritten numerals database (Mixed National Institute of Standards and technology databases) contains
70000 handwritten digital pictures. These figures are collected by staff of the National Bureau of Statistics of the United States and students of American universities. Each picture
Are all 28x28 grayscale images.

A KNN classifier was trained with the mnist data set to identify the newly entered handwritten digits.

Preparatory work

1. Install the necessary third-party libraries:

Pip Install Scikit-learn
Pip Install NumPy
Pip Install WxPython

To install PIL, download the PIL library for installation at the following address:
Http://effbot.org/media/downloads/PIL-1.1.7.win32-py2.7.exe
(or found in http://effbot.org/downloads/that corresponds to your operating system and Python version
Version of PIL)

2. Download the Mnist data set:
You can download the Mnist dataset from the following address.
http://yann.lecun.com/exdb/mnist/
As follows:

Project Structure diagram

The overall project structure is very simple, altogether two script files, one is GUI interface script (digit_gui.py),
One is the classifier script (model.py).
As follows:

Partial code presentation of the implementation process

1. Import the relevant libraries in model.py:

Import NumPy as Npimport osfrom PIL import imageimport randomfrom sklearn.neighbors import kneighborsclassifier as Knnfrom Sklearn.externals Import Joblib

2. Write the relevant functions in the model.py,

To convert a picture to a vector:

def Img2vec (fname):    "converts images in jpg format to vector '    im = Image.open (fname). Convert (' L ')    im = Im.resize ((28,28))    tmp = Np.array (IM)    VEC = Tmp.ravel ()    return VEC

Randomly extract 1000 images as a training set:

def split_data (paths):    "randomly extract 1000 pictures as Training set" '    fn_list = os.llistdir (paths)    X = []    y = []    D0 = Random.sample (fn_list,1000) for    i,name in Enumerate (d0): Y.append        (name[0])        x.append (Img2vec (name))        DataSet = Np.array ([x, y])    return x, y

To build a classifier:

def KNN_CLF (X_train,label):    ' build classifier '    CLF = KNN ()    clf.fit (X_train,label)    return CLF

To save the model:

def save_model (model,output_name):    ' save model '    Joblib.dump (model,ouotput_name)

3. Training Model:

X_train,y_label = Split_data (file_path) CLF = KNN_CLF (X_train,y_label) Save_model (CLF, ' mnist_knn1000.m ')

4. Write the user interface in digit_gui.py:
To import related libraries:

Import Wxfrom Collections Import namedtuplefrom PIL import imageimport osimport model

Authoring Interface:

Class MainWindow (WX. Frame): Def __init__ (self,parent,title): WX. Frame.__init__ (self,parent,title=title,size= (600,-1)) Static_font = WX. Font (WX. SWISS, WX. NORMAL, WX. NORMAL) Size = namedtuple ("Size", [' X ', ' Y ']) s = size (100,50) sm = size (100,25) self.fi                Lename = None Self.model = Model B_labels = [u ' open ', U ' run '] tipstring = [u ' select picture ', U ' recognition number '] Funcs = [Self.choose_file,self.run] ' Create input area ' ' Self.in1 = wx. Textctrl (self,-1,size = (2*s.x,3*s.y)) self.out1 = WX. Textctrl (self,-1,size = (s.x,3*s.y)) ' Create button ' Self.sizer0 = wx. Flexgridsizer (Rows=1, hgap=4, vgap=2) self.sizer0.Add (self.in1) buttons = [] for I,label in E Numerate (b_labels): b = wx.              Button (self, id = I,label = label,size = (1.5*s.x,s.y)) Buttons.append (b) Self.sizer0.Add (b) SELF.SIZER0.ADD (self.out1) "Set the color and size of labels and buttons" for I,button in Enumerate (buttons): Butto N.setforegroundcolour (' Red ') button. SetFont (Static_font) button. Settooltipstring (Tipstring[i]) button. Bind (WX. Evt_button,funcs[i]) "Layout" self. Setsizer (SELF.SIZER0) self. Setautolayout (1) self.sizer0.Fit (self) self. Createstatusbar () self. Show (True)

The interface is as follows:

Write the control's callback function:

Run effect

Code Download: http://www.demodashi.com/demo/13039.html Note: This copyright belongs to the author, published by the demo master, refused to reprint, reprint needs the author authorization

A handwritten digital recognizer implemented in Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.