I was tasked with building a webapp/webservice based on neural network which was built on keras. So, I decided to write down what and how I did it.
This article is divided into 3 sections.
- Building the Neural Network.
- Building the frontend for webservice.
- Building the backend for webservice.
Keras makes it very easy to architct and train neural network hence I decided to use it for this task. I built Convolutional Neural Network for recognizing digits based on the MNIST handwritten digit dataset. Since CNNs perform better than traditonal multi layered peceptrons(MLPs), using CNNs was the obvious choice. This CNN is built based upon the following diagram.
MNIST dataset consists of total 70,000 handwritten images of digits. Keras is shipped with functions for preprocessing this dataset which splits this dataset into 60,000 images for training the model and other 10,000 for evaluating the model. Dataset can be loaded by
This statement returns two tuples , each containing image vector and image label for training. As shown in diagram our CNN expects input to be of size 28x28x1, thus array is reshaped and normalized for better performance.
Note that I’ll be using the one hot vector for the output label. Keras makes it pretty easy with
After this layers can be stacked as given by the diagarm using a sequential model.
Loss function can be optimized with various algorithms ( RMSprop, Adam, etc) which happens to be adadelta in this case. Adadelta is an extension of Adagrad that seeks to reduce its aggressive, monotonically decreasing learning rate.
After training is over, this model can be exported to HDF5 file on disk by
This file saves all the weights for this neural network, Allowing anyone to use this trained network as a blackbox on anyother machine. If any exception is encountered make sure h5py package is installed on your system.
To build the frontend I used jquery + HTML5 canvas. HTML5 Canvas facilitates user to draw handwritten digits which then passed to backend for processing. So, HTML file looks like
In this canvas app, Two arrays X and Y are used for storing the coordinates. When mouse is first clicked on canvas, mousedown event fires and stars logging the X and Y coordinates into an array which is used to draw stuff on the canvas.
Paint variable is for tracking the state if user is still drawing on the canvas or not. When mouse is dragged after clicking somewhere on canvas, coordinates is pushed into an array and drawn at the same time.
When user releases the mouse or if the mouse goes out of canvas, The mouse coordinates arrays is cleared.
Where cleanArray looks like
When user clicks on predict button , predict() is fired and image is sent to backend using canvas.toDataURL() function through AJAX in JSON form. This function converts image to base64 data URLs when can be processed by the backend.
Data URLs are composed of four parts: a prefix (data:), a MIME type indicating the type of data, an optional base64 token if non-textual, and the data itself:
Building is backend is easy with Flask than any other python web framework. I tried to use Nodejs but that approach was inefficient, since it involved spawning new process for every request when using child_process module . I also tried various other Node/Python IPC but it did not feel smooth enough , besides Flask is easy to get up and running.
Data sent by the webapp is in data URL form, using request.get_json() first I extracted the base64 text and decoded it to binary form.
Pillow library provides methods which can be used to convert bytes to Image, thus
converts raw bytes into an PIL object which numpy can parse.
I made a seperate module to preprocess the image using scikit-image library before I threw the task of prediction at the network. It involves these three steps-
Network was trained on MNIST dataset which contains black and white 28x28 image in normalized float32 form thus preprocessing is necessary for correct output. This is also the reason why I made canvas background black.
Saved model can be loaded by keras.models.load_model() which provides predict() function to make prediction. In this case this methods returns probability vector because softmax was is being used for activation layer. Thus, we can simply return np.argmax() on the predict().
this result can be sent back to webapp in JSON form by
And final result looks like
Link to Project