Handwritten Digit Recognition using Convolutional Neural Networks in Python with Keras

A popular demonstration of the capability of deep learning techniques is object recognition in image data.

The “hello world” of object recognition for machine learning and deep learning is the MNIST dataset for handwritten digit recognition.

In this post you will discover how to develop a deep learning model to achieve near state of the art performance on the MNIST handwritten digit recognition task in Python using the Keras deep learning library.

After completing this tutorial, you will know:

  • How to load the MNIST dataset in Keras.
  • How to develop and evaluate a baseline neural network model for the MNIST problem.
  • How to implement and evaluate a simple Convolutional Neural Network for MNIST.
  • How to implement a close to state-of-the-art deep learning model for MNIST.

Let’s get started.

  • Update Oct/2016: Updated examples for Keras 1.1.0, TensorFlow 0.10.0 and scikit-learn v0.18.
  • Update Mar/2017: Updated example for Keras 2.0.2, TensorFlow 1.0.1 and Theano 0.9.0.
Handwritten Digit Recognition using Convolutional Neural Networks in Python with Keras

Handwritten Digit Recognition using Convolutional Neural Networks in Python with Keras
Photo by Jamie, some rights reserved.

Description of the MNIST Handwritten Digit Recognition Problem

The MNIST problem is a dataset developed by Yann LeCun, Corinna Cortes and Christopher Burges for evaluating machine learning models on the handwritten digit classification problem.

The dataset was constructed from a number of scanned document dataset available from the National Institute of Standards and Technology (NIST). This is where the name for the dataset comes from, as the Modified NIST or MNIST dataset.

Images of digits were taken from a variety of scanned documents, normalized in size and centered. This makes it an excellent dataset for evaluating models, allowing the developer to focus on the machine learning with very little data cleaning or preparation required.

Each image is a 28 by 28 pixel square (784 pixels total). A standard spit of the dataset is used to evaluate and compare models, where 60,000 images are used to train a model and a separate set of 10,000 images are used to test it.

It is a digit recognition task. As such there are 10 digits (0 to 9) or 10 classes to predict. Results are reported using prediction error, which is nothing more than the inverted classification accuracy.

Excellent results achieve a prediction error of less than 1%. State-of-the-art prediction error of approximately 0.2% can be achieved with large Convolutional Neural Networks. There is a listing of the state-of-the-art results and links to the relevant papers on the MNIST and other datasets on Rodrigo Benenson’s webpage.

Beat the Math/Theory Doldrums and Start using Deep Learning in your own projects Today, without getting lost in “documentation hell”

Deep Learning With Python Mini-CourseGet my free Deep Learning With Python mini course and develop your own deep nets by the time you’ve finished the first PDF with just a few lines of Python.

Daily lessons in your inbox for 14 days, and a DL-With-Python “Cheat Sheet” you can download right now.   

Download Your FREE Mini-Course  

 

Loading the MNIST dataset in Keras

The Keras deep learning library provides a convenience method for loading the MNIST dataset.

The dataset is downloaded automatically the first time this function is called and is stored in your home directory in ~/.keras/datasets/mnist.pkl.gz as a 15MB file.

This is very handy for developing and testing deep learning models.

To demonstrate how easy it is to load the MNIST dataset, we will first write a little script to download and visualize the first 4 images in the training dataset.

You can see that downloading and loading the MNIST dataset is as easy as calling the mnist.load_data() function. Running the above example, you should see the image below.

Examples from the MNIST dataset

Examples from the MNIST dataset

Baseline Model with Multi-Layer Perceptrons

Do we really need a complex model like a convolutional neural network to get the best results with MNIST?

You can get very good results using a very simple neural network model with a single hidden layer. In this section we will create a simple multi-layer perceptron model that achieves an error rate of 1.74%. We will use this as a baseline for comparing more complex convolutional neural network models.

Let’s start off by importing the classes and functions we will need.

It is always a good idea to initialize the random number generator to a constant to ensure that the results of your script are reproducible.

Now we can load the MNIST dataset using the Keras helper function.

The training dataset is structured as a 3-dimensional array of instance, image width and image height. For a multi-layer perceptron model we must reduce the images down into a vector of pixels. In this case the 28×28 sized images will be 784 pixel input values.

We can do this transform easily using the reshape() function on the NumPy array. We can also reduce our memory requirements by forcing the precision of the pixel values to be 32 bit, the default precision used by Keras anyway.

The pixel values are gray scale between 0 and 255. It is almost always a good idea to perform some scaling of input values when using neural network models. Because the scale is well known and well behaved, we can very quickly normalize the pixel values to the range 0 and 1 by dividing each value by the maximum of 255.

Finally, the output variable is an integer from 0 to 9. This is a multi-class classification problem. As such, it is good practice to use a one hot encoding of the class values, transforming the vector of class integers into a binary matrix.

We can easily do this using the built-in np_utils.to_categorical() helper function in Keras.

We are now ready to create our simple neural network model. We will define our model in a function. This is handy if you want to extend the example later and try and get a better score.

The model is a simple neural network with one hidden layer with the same number of neurons as there are inputs (784). A rectifier activation function is used for the neurons in the hidden layer.

A softmax activation function is used on the output layer to turn the outputs into probability-like values and allow one class of the 10 to be selected as the model’s output prediction. Logarithmic loss is used as the loss function (called categorical_crossentropy in Keras) and the efficient ADAM gradient descent algorithm is used to learn the weights.

We can now fit and evaluate the model. The model is fit over 10 epochs with updates every 200 images. The test data is used as the validation dataset, allowing you to see the skill of the model as it trains. A verbose value of 2 is used to reduce the output to one line for each training epoch.

Finally, the test dataset is used to evaluate the model and a classification error rate is printed.

Running the example might take a few minutes when run on a CPU. You should see the output below. This very simple network defined in very few lines of code achieves a respectable error rate of 1.91%.

Simple Convolutional Neural Network for MNIST

Now that we have seen how to load the MNIST dataset and train a simple multi-layer perceptron model on it, it is time to develop a more sophisticated convolutional neural network or CNN model.

Keras does provide a lot of capability for creating convolutional neural networks.

In this section we will create a simple CNN for MNIST that demonstrates how to use all of the aspects of a modern CNN implementation, including Convolutional layers, Pooling layers and Dropout layers.

The first step is to import the classes and functions needed.

Again, we always initialize the random number generator to a constant seed value for reproducibility of results.

Next we need to load the MNIST dataset and reshape it so that it is suitable for use training a CNN. In Keras, the layers used for two-dimensional convolutions expect pixel values with the dimensions [pixels][width][height].

In the case of RGB, the first dimension pixels would be 3 for the red, green and blue components and it would be like having 3 image inputs for every color image. In the case of MNIST where the pixel values are gray scale, the pixel dimension is set to 1.

As before, it is a good idea to normalize the pixel values to the range 0 and 1 and one hot encode the output variables.

Next we define our neural network model.

Convolutional neural networks are more complex than standard multi-layer perceptrons, so we will start by using a simple structure to begin with that uses all of the elements for state of the art results. Below summarizes the network architecture.

  1. The first hidden layer is a convolutional layer called a Convolution2D. The layer has 32 feature maps, which with the size of 5×5 and a rectifier activation function. This is the input layer, expecting images with the structure outline above [pixels][width][height].
  2. Next we define a pooling layer that takes the max called MaxPooling2D. It is configured with a pool size of 2×2.
  3. The next layer is a regularization layer using dropout called Dropout. It is configured to randomly exclude 20% of neurons in the layer in order to reduce overfitting.
  4. Next is a layer that converts the 2D matrix data to a vector called Flatten. It allows the output to be processed by standard fully connected layers.
  5. Next a fully connected layer with 128 neurons and rectifier activation function.
  6. Finally, the output layer has 10 neurons for the 10 classes and a softmax activation function to output probability-like predictions for each class.

As before, the model is trained using logarithmic loss and the ADAM gradient descent algorithm.

We evaluate the model the same way as before with the multi-layer perceptron. The CNN is fit over 10 epochs with a batch size of 200.

Running the example, the accuracy on the training and validation test is printed each epoch and at the end of the classification error rate is printed.

Epochs may take about 45 seconds to run on the GPU (e.g. on AWS). You can see that the network achieves an error rate of 1.03, which is better than our simple multi-layer perceptron model above.

Larger Convolutional Neural Network for MNIST

Now that we have seen how to create a simple CNN, let’s take a look at a model capable of close to state of the art results.

We import classes and function then load and prepare the data the same as in the previous CNN example.

This time we define a large CNN architecture with additional convolutional, max pooling layers and fully connected layers. The network topology can be summarized as follows.

  1. Convolutional layer with 30 feature maps of size 5×5.
  2. Pooling layer taking the max over 2*2 patches.
  3. Convolutional layer with 15 feature maps of size 3×3.
  4. Pooling layer taking the max over 2*2 patches.
  5. Dropout layer with a probability of 20%.
  6. Flatten layer.
  7. Fully connected layer with 128 neurons and rectifier activation.
  8. Fully connected layer with 50 neurons and rectifier activation.
  9. Output layer.

Like the previous two experiments, the model is fit over 10 epochs with a batch size of 200.

Running the example prints accuracy on the training and validation datasets each epoch and a final classification error rate.

The model takes about 100 seconds to run per epoch. This slightly larger model achieves the respectable classification error rate of 0.89%.

This is not an optimized network topology. Nor is a reproduction of a network topology from a recent paper. There is a lot of opportunity for you to tune and improve upon this model.

What is the best error rate score you can achieve?

Post your configuration and best score in the comments.

Resources on MNIST

The MNIST dataset is very well studied. Below are some additional resources you might like to look into.

Summary

In this post you discovered the MNIST handwritten digit recognition problem and deep learning models developed in Python using the Keras library that are capable of achieving excellent results.

Working through this tutorial you learned:

  • How to load the MNIST dataset in Keras and generate plots of the dataset.
  • How to reshape the MNIST dataset and develop a simple but well performing multi-layer perceptron model on the problem.
  • How to use Keras to create convolutional neural network models for MNIST.
  • How to develop and evaluate larger CNN models for MNIST capable of near world class results.

Do you have any questions about handwriting recognition with deep learning or this post? Ask your question in the comments and I will do my best to answer.

Frustrated With Your Progress In Deep Learning?

 What If You Could Develop Your Own Deep Nets in Minutes

...with just a few lines of Python

Discover how in my new Ebook: Deep Learning With Python

It covers self-study tutorials and end-to-end projects on topics like:
Multilayer PerceptronsConvolutional Nets and Recurrent Neural Nets, and more...

Finally Bring Deep Learning To
Your Own Projects

Skip the Academics. Just Results.

Click to learn more.

112 Responses to Handwritten Digit Recognition using Convolutional Neural Networks in Python with Keras

  1. nitangle July 6, 2016 at 2:18 pm #

    Thanks for this tutorial. It was great. Though(it might sound silly) how do I see it in action? I mean if I wanna see it predict an answer for an image how do I do that?
    Thanks again.

    • Jason Brownlee July 7, 2016 at 7:27 am #

      In it’s current form it is not a robust system.

      You will have to provide a digit image with the same dimensions.

      • alex_rovers August 14, 2016 at 8:00 pm #

        great work!!
        but can you show that in action with a sample image

  2. Adrian August 29, 2016 at 8:19 am #

    Do you have a working program which recogniting the numbers ?

  3. Matthew September 6, 2016 at 1:22 pm #

    When I try the baseline model with MLPs I get much worse performance than what you are showing (an error rate of 53.64%). Any idea why I could be seeing such vastly different results when I’m using the same code? Thanks.

    • Jason Brownlee September 7, 2016 at 9:17 am #

      Hi Matthew, that is surprising that the numbers are so different.

      Theano backend? or TensorFlow? What Platform? What version of Python?

      Try running the example 3 times and report all 3 scores.

      • Adrian September 19, 2016 at 1:14 am #

        I have the same problem. I using Theano backend. platform: Pycharm. version 3.5

        • Jason Brownlee September 19, 2016 at 7:42 am #

          Sorry to hear that Adrian.

          Does it work if you run on the command line?

    • John Ellis November 22, 2016 at 12:25 pm #

      To get an error rate that high, the code must have been copied incorrectly or something similar. Beyond that, do notice that each time you run this, the final output will be slightly different each time because of the Dropout layer in the neural network. It will randomly choose that 20% each time it runs thereby slightly affecting the final outcome.

  4. Vinay September 12, 2016 at 5:08 am #

    Could you please give some simple example for CNN for ex may be in uci repository data set. Whether is possible to apply CNN for numeric features.

  5. Dinesh September 21, 2016 at 6:22 pm #

    Hello Jason, I tried running the script, but the baseline model is taking too much time.. its running from past 20 hours and still is on 4th EPoch,, can you please suggest some way to speed up the process.. I am using 4 gb ram computer, and running on Anaconda Theano backened Keras

  6. Mike October 2, 2016 at 6:44 pm #

    Hi! Great post! I tried it, but for the first CNN It does not seem to compile. I got:

    ValueError: Filter must not be larger than the input: Filter: (5, 5) Input: (1, 28)

    just after model = baseline_model()

  7. Jack October 6, 2016 at 7:45 pm #

    Hi jason, I tried it, but I got the error below. I use tensorflow r0.11. I’m not sure whether it is the casuse.

    Using TensorFlow backend.
    Traceback (most recent call last):
    File “/Users/Jack/.pyenv/versions/3.5.1/lib/python3.5/site-packages/tensorflow/python/framework/common_shapes.py”, line 594, in call_cpp_shape_fn
    status)
    File “/Users/Jack/.pyenv/versions/3.5.1/lib/python3.5/contextlib.py”, line 66, in __exit__
    next(self.gen)
    File “/Users/Jack/.pyenv/versions/3.5.1/lib/python3.5/site-packages/tensorflow/python/framework/errors.py”, line 463, in raise_exception_on_not_ok_status
    pywrap_tensorflow.TF_GetCode(status))
    tensorflow.python.framework.errors.InvalidArgumentError: Negative dimension size caused by subtracting 5 from 1

    • Jason Brownlee October 7, 2016 at 7:54 am #

      Ouch Jack, that does not look good.

      It looks like the API has changed. I’ll dive into it and fix up the examples.

      • Jason Brownlee October 7, 2016 at 11:46 am #

        OK, I have updated the examples.

        Firstly, I recommend using TensorFlow 0.10.0, NOT 0.11 as there are issues with the latest version.

        Secondly, You must add the following two lines to make the CNNs work:

        Fix taken from here: https://github.com/fchollet/keras/issues/2681

        I hope that helps Jack.

        • Ermia October 29, 2016 at 5:49 pm #

          Hi Jason.
          Thanks for the great tutorial.

          Your comment has not solved the problem yet, and we still the same error, Could you please modify your model to work with TF backend?

  8. Abhai Kollara October 15, 2016 at 1:32 am #

    Hi, thanks for the great tutorial !

    I tried predicting with a test set and got the one-hot encoded predictions. I was just wondering if there’s a built-in function to convert it back to original labels (0,1,2,3…).

  9. Berisha Mekayhu October 31, 2016 at 5:15 am #

    Hello,

    Thank you very much for your usual brief and comprehensive illustration and discussion.

  10. gs November 2, 2016 at 9:01 pm #

    Hello,

    After finishing learning, how can I recognize my own pictures with this network.

    • Jason Brownlee November 3, 2016 at 7:58 am #

      Great question gs, I don’t have an example at the moment.

      You will need to encode your own pictures in the same way as the MNIST dataset – mainly rescale to the same size. Then load them as a matrix of pixel values and you can make predictions.

  11. Nick November 3, 2016 at 11:58 pm #

    Hello,
    Thanks for great example, but how do I save the state of the net,
    I mean that net learns on 60000 examples, then it tests and try to guess 10000
    But if I want to use always, every day, for example, how can I use it without training it every day?

  12. John Ellis November 22, 2016 at 12:28 pm #

    Jason, does your book explain “WHY” you chose the various layers you did in this tutorial and shed light on how and why to choose certain designs for different data sets?

    • Jason Brownlee November 23, 2016 at 8:50 am #

      No, just the how John.

      Why us hard, in most cases best results are achieved with trial and error. There is no “theory of neural networks” that helps you configure them.

  13. Nassim November 24, 2016 at 9:29 pm #

    hello
    when i try to make a prediction for my own image, the net get it wrong
    this is depressing me.
    i use the command model.predict_classes(img)
    please is there a way to get correct answer for my handwritten digit

    • Jason Brownlee November 25, 2016 at 9:33 am #

      Perhaps you need more and different training examples Nassim?

      Perhaps some image augmentation can make your model more robust?

  14. Anthony November 26, 2016 at 10:04 am #

    Great tutorial Jason, in fact you are the best, very easy to follow, I enjoy all your tutorials, thank you! In fact,
    I achieved an error rate of 0.74 at one point using GPU and it took about 30sec to run.

  15. BWen December 19, 2016 at 5:17 am #

    Thanks for the great tutorial. Just one thing I didn’t understand. In the Convolution2D layer, there is a border_mode=”valid” parameter. What does this do? What’s its purpose? The Keras documentation doesn’t seem to have an explanation for it either.

  16. Sanjaya Subedi December 19, 2016 at 6:53 am #

    Excellent tutorial Jason. I really enjoyed reading it and implementing it. I just figured that if you have cuDNN installed it makes things waay fast (at least for the toy examples I’ve tried). I recommend anyone reading this to install cuDNN and configure theano to use it. You just have to put
    [dnn]
    enabled = True
    in theanorc file.

  17. Ganesh January 4, 2017 at 10:06 pm #

    Hi Jason,
    I am trying to apply the CONVOLUTION1D for the IRIS Data.
    The code is as below

    —————————————————————————————–
    max_features = 150
    maxlen = 4
    batch_size = 16
    embedding_dims = 3
    nb_epoch = 3
    nb_classes =3
    dropoutVal = 0.5
    nb_filter = 5
    hidden_dims = 500
    filter_length = 4

    import pandas as pd
    data_load = pd.read_csv(“iris.csv”)

    data = data_load.ix[:,0:4]
    target = data_load.ix[:,4]
    X_train = np.array(data[:100].values.astype(‘float32’))
    Y_train = np.array(target[:100])
    Y_train = np_utils.to_categorical(Y_train,nb_classes)
    X_test = np.array(data[100:].values.astype(‘float32′))
    Y_test = np.array(target[100:])
    Y_test = np_utils.to_categorical(Y_test,nb_classes)

    std = StandardScaler()
    X_train = X_train_scaled = std.fit_transform(X_train)
    X_test = X_test_scaled = std.transform(X_test)

    X_train1 = sequence.pad_sequences(X_train_scaled,maxlen=maxlen)
    X_test1 = sequence.pad_sequences(X_test_scaled,maxlen=maxlen)

    model = Sequential()
    model.add(Embedding(max_features,embedding_dims,input_length=maxlen))

    model.add(Convolution1D(nb_filter=nb_filter,filter_length=filter_length, border_mode=’valid’,activation=’relu’))
    model.add(GlobalMaxPooling1D())

    model.add(Dense(hidden_dims,activation=’softmax’))

    model.add(Dense(nb_classes))
    model.add(Activation(‘sigmoid’))
    model.compile(loss=’binary_crossentropy’, optimizer=’adam’, metrics=[‘accuracy’])

    model.fit(X_train1, Y_train, nb_epoch=5, batch_size=10)

    scores = model.evaluate(X_test1, Y_test, verbose=0)

    predictions = model.predict(X_test1)

    —————————————————————————————-
    I want to check if I am in the right direction on this.
    I am not getting the accuracy more than 66% which is quite surprising.

    Am I doing the Embedding Layer correctly. As when I see the embedding layer weights I see there is difference in what Layer Paremeters I set with the Weights I retreive.

    Please advise.

    Regards
    Ganesh

  18. Ger January 20, 2017 at 4:19 am #

    Thank you very much for this post. (:

  19. Remon January 26, 2017 at 9:09 pm #

    can you tell me how can i give the system an image and he tells me what number is it ? sorry i am new to this , thank you !

    • Jason Brownlee January 27, 2017 at 12:05 pm #

      Hi Remon,

      The image will have to be scaled to the same dimensions as those expected by the network.

      Also, in this example, the network expects images to have a specific set of proportions and to be white digits on a black background. New examples will have to be prepared in the same way.

  20. joe January 31, 2017 at 6:41 am #

    Hi jason,
    snippet of your code:
    ————————-
    in the step # load data
    (X_train, y_train), (X_test, y_test) = mnist.load_data()
    # reshape to be [samples][pixels][width][height]
    X_train = X_train.reshape(X_train.shape[0], 1, 28, 28).astype(‘float32’)
    X_test = X_test.reshape(X_test.shape[0], 1, 28, 28).astype(‘float32’)

    you are using mnist data. what kind of data strurcture is it?
    how to pre process images (in a list) an labels(in a list) into this structure anf fid it to keras model?

    what exactly this line
    X_train = X_train.reshape(X_train.shape[0], 1, 28, 28).astype(‘float32’)

    does?
    thanks
    joseph

    • Jason Brownlee February 1, 2017 at 10:30 am #

      Hi Joe,

      The MNIST data is available within Keras.

      It is stored as NumPy arrays of pixel data.

      When used with a CNN, the data is reshaped into the format: [samples, pixels, width, height]

      I hope that helps.

  21. Amy February 1, 2017 at 3:52 am #

    Hi Jason, what led you to choose 128 neurons for the fully-connected layer? (Calculating the number of activations leading into the fully-connected layer, it’s much larger than 128) Thanks!

  22. Shaik Mohammed Siraj February 6, 2017 at 10:52 am #

    Hi @Jason Brownlee, first things first awesome tut u got there ..!!
    There’s a small problem at d following lines:

    Small CNN:
    # build the model
    model = baseline_model()

    Large CNN:
    # build the model
    model = larger_model()

    Using the recent versions of Tensorfllow throws an AttributeError:
    => AttributeError: module ‘tensorflow.python’ has no attribute ‘control_flow_ops’ <=

    solution:
    Add following lines:

    import tensorflow as tf
    tf.python.control_flow_ops = tf

    ref:
    https://github.com/fchollet/keras/issues/3857

    can u plz update the code..!!
    once again thanx for d grt tut.
    keep up the good work..!!

    • Jason Brownlee February 7, 2017 at 10:06 am #

      Thanks for the note Shaik, I’ll investigate.

  23. Mouz February 15, 2017 at 1:04 am #

    your posts are great for an awesome start with keras. m loving it sir.

  24. Faruk Ahmad February 17, 2017 at 6:12 pm #

    Hello sir, thanks for your great writing and well explanation. I have tried it and it works. But how can I train the network using my own handwriting data set instead of MNIST data.

    It would be very helpful if you shed some light on this..

    Thanks in advance.

    • Jason Brownlee February 18, 2017 at 8:37 am #

      Hi Faruk,

      Generally, you will need to make the data consistent in dimensions as a starting point.

      From there, you can separate the data into train/test sets or similar and begin exploring different configurations.

      Does that help? Perhaps I misunderstand the question?

  25. Arash February 21, 2017 at 4:32 am #

    Hi
    Thanks for your nice explanation. I succesfully trained all the networks you introduced here. However, when I want to use the trained model to make some predictions, using this pice of code:

    im=misc.imread(‘test8.png’)
    im=im[:,:,1]
    im=im.flatten()
    print(model.predict(im))

    it gives me the error:
    Error when checking : expected dense_input_1 to have shape (None, 784) but got array with shape (784, 1)

    the ‘im’ has the shape (,784) , how can I feed in an array of size (None,784) ?

    • Jason Brownlee February 21, 2017 at 9:37 am #

      Hi Arash,

      Consider reshaping as follows:

  26. Jundong February 25, 2017 at 2:21 am #

    Hi Jason,

    Thank you for your wonderful tutorial!

    I have question about the ‘model.add(Dropout(0.2))’. As you stated ‘The next layer is a regularization layer using dropout called Dropout. It is configured to randomly exclude 20% of neurons in the layer in order to reduce overfitting.’ in the post, Dropout is treated as a separated layer in Keras, instead of a regularization operation on the existing layers such as convolution layer and fully-connected layer. How is this being achieved?

    Since this Dropout is between MaxPooling and the next fully-connected layer, which part of the weights was applied Dropout?

    Thank you very much!

    • Jason Brownlee February 25, 2017 at 6:01 am #

      Good question, it affects the weights between the layers it is inserted.

  27. ANJI February 26, 2017 at 8:38 pm #

    Hello sir, thanks for your well explanation. I have tried it and it works well. But how can I train the network using my own handwriting data set instead of MNIST data set.

    It would be very thankful if you shed some light on this..

    Thanks in advance.

    • Jason Brownlee February 27, 2017 at 5:50 am #

      You will need to load the data from file, adjust it so that it all has the same dimensions, then fit your model.

      I do not have an example of working with custom data at the moment, sorry.

  28. pramod March 3, 2017 at 6:09 pm #

    i tried the simple CNN with theano backend.

    ”’ImportError: (‘The following error happened while compiling the node’, DotModulo(A, s, m, A2, s2, m2), ‘\n’, ‘/home/pramod/.theano/compiledir_Linux-4.8–generic-x86_64-with-debian-stretch-sid-x86_64-2.7.13-64/tmpXpzrkl/d16654b784f584f17fdc481825fd2cca.so: undefined symbol: _ZdlPvm’, ‘[DotModulo(A, s, m, A2, s2, m2)]’)”’

    i got this error while running the baseline model.

    can you please tell me how to correct this?. i tried multiple ways of installing theano including pip and conda .

    im guessing my theano installation is faulty .
    clueless on how to proceed . please help.

    thank you

    • Jason Brownlee March 6, 2017 at 10:43 am #

      I have not seen this error, sorry.

      Many of my students have great success using Keras and Theano with Anaconda Python.

  29. Chris Hanning March 13, 2017 at 4:03 pm #

    Got the verbatim code from above with one change:
    X_train = X_train[:-20000 or None]
    y_train = y_train[:-20000 or None]
    to reduce the memory usage to run on a Mac OSX El Capitan (GeForce 650M with 512MB)
    The error rate was a little higher at
    1.51%
    I used keras with the tensorflow-GPU backend.

  30. Vikalp March 19, 2017 at 1:28 am #

    Hi Jason,

    Really awesome introduction to keras and digit recognition for a beginner like me.
    You are using mnist dataset which is in form of pickled object (I guess). But my question is how will you convert set of existing images to this pickled object?

    Secondly, you are calculating error rate compared to your test dataset. But suppose I have an image with a number written on it, how will you return class label of it, without making much changes in the above program.

    • Jason Brownlee March 19, 2017 at 9:09 am #

      Thanks Vikalp.

      I would recommend loading your image data as numpy arrays and working with them directly.

      You can make a prediction with the network (y = model.predict(x)) and use the numpy argmax() function to convert the one hot encoded output into a class index.

      • Vikalp March 22, 2017 at 4:02 pm #

        Hi Jason,

        Thanks for quick reply.

        I was looking into the way you suggested. Following is the code for that:

        color_image = cv2.imread(“two.jpg”)
        gray_image = cv2.cvtColor(color_image, cv2.COLOR_BGR2GRAY)
        a = model.predict(numpy.array(gray_image))
        print(a)

        But getting following error:
        ValueError: Error when checking : expected dense_1_input to have shape (None, 784) but got array with shape (1024, 791)

        I am not sure if I am doing correct. Please guide over this. Thank you.

        • Jason Brownlee March 23, 2017 at 8:46 am #

          The loaded image must have the exact same dimensions as the data used to fit the model.

          You may need to resize it.

  31. Marten March 30, 2017 at 1:36 am #

    Hello,

    I tried to save and load the model as you describe in another post, but I get always erros like:
    ValueError: Error when checking model target: expected dense_3 to have shape (None, 1) but got array with shape (10000, 10)

    The error happens at the
    score = model.evaluate(…)
    line after load

    #

    # save model and weights
    print("Saving model...")
    model_json = model.to_json()
    with open('mnist_model.json', 'w') as json_file:
    json_file.write(model_json)
    model.save_weights("mnist_weights.h5")
    print("model saved to disk")

    # load model and weights
    print("Laoding model...")
    with open('mnist_model.json') as json_file:
    model_json = json_file.read()

    model = model_from_json(model_json)
    model.load_weights('mnist_weights.h5')
    print("mode loaded from disk")

    print("compiling model...")
    model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

    scores = model.evaluate(X_test, y_test, verbose=0)
    print("Baseline Error: %.2f%%" % (100-scores[1]*100))

  32. Dhanachandra March 30, 2017 at 5:04 pm #

    How to get precision and recall and f-measure of predicted output?

  33. Steve March 31, 2017 at 1:18 pm #

    Hi Jason,

    Great site and tutorial. I understand you haven’t been able to describe how to pre-process our own images to be readable in our MNIST trained models, as a lot of other people here have asked. Perfectly understand if you don’t have the time to explain how to do this.

    Would you be able to guide me on how I might continue my search to do this though? I’ve tried creating a new 28×28 pixel image, black background with white foreground for the image drawing, converting this to grayscale (for 1,28,28 input dimensions). Then I divide that by 255. The prediction accuracy for these customs images are very low (the model has a 99% accuracy on the MNIST test images).

    Looking at the individual features, I see that the locations of the decimals for the custom images pre-processed as described above seem quite different to the MNIST ones, with the decimals and 0’s appearing in vastly different locations compared to the MNIST data. Completely different patterns. This leads me to believe some more complicated pre-processing must be going on besides the intuitive steps done above. I looked at instructions on the MNIST page for how the pre-processing took place, but don’t know how to implement these instructions in python. There also seem to be some pre-processing scripts out there but I can’t get these to work.

    Any other suggestions on how I might continue my search to find how to pre-process custom images? All instructions in Google are too complex or the implementation seems to fail.

    • Jason Brownlee April 1, 2017 at 5:48 am #

      Generally, you need to train a model on data that will be representative of the type of images you need to make predictions on later.

      Images will need to be of the same size (width x height) and the same colors.

      If you expect a lot of variation in char placement in images, you can use image augmentation to create copies of your input data with random transforms:
      http://machinelearningmastery.com/image-augmentation-deep-learning-keras/

      I hope that helps as a start.

  34. Andreas April 3, 2017 at 5:58 am #

    Hi Jason,
    thx for your wonderfull courses!

    My question is, why the pixels should be standardized to 0…1?

    I have input like this:

    70.67, 3170.27, 56.31, 1.28, 0.39, 0
    204.70, 26419.57, 162.54, 0.42, -0.97, 1
    173.70, 20141.12, 141.92, 0.61, -1.14, 3
    219.80, 42211.29, 205.45, 0.55, -1.41, 0
    243.00, 43254.00, 207.98, 0.23, -1.73, 0
    241.22, 21973.94, 148.24, 0.07, -0.60, 3
    245.42, 46176.45, 214.89, 0.29, -1.80, 0
    164.78, 25253.94, 158.91, 1.08, -0.13, 0
    115.29, 9792.57, 98.96, 0.56, -1.25, 1

    The last row is the result I have split it away and converted it to one shot hot.
    I am trying many models and many different parameters but none is learning anything. Even trying oversampling on few collums and looking if a model can reproduce the trained outputs fails!

    But all your examples run without problems and produce the same results like you describe. So my setup: latest python 3.6 with anaconda runing on windows 10, should be all right.

    So I fear that somethig with my inputs is wrong 🙁 . Should I standardice them? How can I do it? Later I will also have mixed inputs: numbers and strings. How could I work with this?

    Would be very nice to get your kind help!

    Thanks!
    (pls excuse my very little perhaps bad english from school)

  35. Girindra Gautama May 1, 2017 at 5:36 am #

    Hi Jason,

    Thanks for this! This is really helpful. I was just wondering; I realized you used all 60,000 training data. How would the code look like if you were to use only say 10k or 30k of the training data, yet achieve a low error?

    Thanks!

  36. Ehsan May 1, 2017 at 9:24 am #

    Hello,
    Thanks for your code.
    I have a question.
    How can I add a new activation function to this code?
    I found the place where I can add the activation function, but I don’t know where should I add the derivative of the new activation function.
    I really appreciate if you help me.
    Thanks.
    Ehsan.

    • Jason Brownlee May 2, 2017 at 5:53 am #

      Hi Ehsan,

      You can specify the activation function between layers (e.g. model.add(…)) or on the layer (e.g. Dense(activation=’…’)).

  37. Paul May 19, 2017 at 7:26 am #

    Hello,
    I couldn’t run the above example.
    got the following error.

    runfile(‘C:/Users/Paul/Desktop/CNN.py’, wdir=’C:/Users/Paul/Desktop’)
    Traceback (most recent call last):

    File “”, line 1, in
    runfile(‘C:/Users/Paul/Desktop/CNN.py’, wdir=’C:/Users/Paul/Desktop’)

    File “C:\Users\Paul\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py”, line 714, in runfile
    execfile(filename, namespace)

    File “C:\Users\Paul\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py”, line 74, in execfile
    exec(compile(scripttext, filename, ‘exec’), glob, loc)

    File “C:/Users/Paul/Desktop/CNN.py”, line 54, in
    model = larger_model()

    File “C:/Users/Paul/Desktop/CNN.py”, line 40, in larger_model
    model.add(Conv2D(30, (5, 5), input_shape=(1, 28, 28), activation=’relu’))

    TypeError: __init__() takes at least 4 arguments (4 given)

    Can you help me out?

    • Jason Brownlee May 19, 2017 at 8:26 am #

      Sorry to hear that Paul, the case of your error is not obvious to me.

      Perhaps confirm that you have the latest versions of all libraries and there were no copy paste errors with the code.

  38. jose mendez May 23, 2017 at 12:43 pm #

    Nice work and spirit Jason, Thank you… it worked for me. I’m used Anaconda and GPU

  39. lakshmi May 24, 2017 at 5:30 pm #

    hello team, I have following dought please help me
    # create model
    model = Sequential()
    model.add(Conv2D(30, (5, 5), input_shape=(1, 28, 28), activation=’relu’))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    in the above code input shape=(1,28,28)that’s for binary image, for color image we kept (3,28,28)..but what we kept for non image data?

    I have dataset of 10248 obs with 18 variables including target variable.

    what I need to kept in the input_shape?

    please help me.

    • Jason Brownlee June 2, 2017 at 11:31 am #

      CNN is for image data.

      For non-image data, you may want to consider an MLP. For sequence data, consider an RNN.

  40. Joy May 29, 2017 at 8:51 pm #

    Sir, the input to my neural network is in a numpy array e.g. [[1,1,1,2], [1,2,1,2], ……..] and in this line of code
    X_train = X_train.reshape(X_train.shape[0], 1, 28, 28).astype(‘float32’)

    the compiler throws an error:
    ValueError: total size of new array must be unchanged

    looking forward for an solution to the problem

    • Jason Brownlee June 2, 2017 at 12:26 pm #

      If your data is not image data, consider starting with an MLP, not a CNN.

  41. Wenjing May 31, 2017 at 9:27 pm #

    HI, Jason. Great tutorial! This is my first CNN and I cannot believe it is actually working, exited!

    I am just wondering why there is no need to initialize the weights in CNN, using “kernel_initializer=”? In the baseline MLP you initialize every layer whereas for CNN, those lines are not there, no matter for the conv layer, the maxpooling layer, or the final fully connected layer.

    Did I miss something? Thanks in advance.

  42. Nahid Hasan June 2, 2017 at 9:32 pm #

    Great work .Thank you Sir . After Completing the training and testing I want to predict a character where I have a new character Image which Contains a New handwritten character . How Can I Do that sir .Please help me

  43. Russel June 6, 2017 at 2:49 pm #

    How can I evaluate my models and estimate their performance
    on unseen data.

  44. li June 12, 2017 at 9:49 pm #

    Hi, Jason
    My question is :
    test_data is for check the model once you have already defined a model ( by using train_data).
    why do you use the test data in your model training?

    model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=200, verbose=2)
    # Final evaluation of the model
    scores = model.evaluate(X_test, y_test, verbose=0)

    • Jason Brownlee June 13, 2017 at 8:20 am #

      It is only used to report the skill of the model on unseen during training (validation dataset).

  45. Herve Nsangu June 13, 2017 at 5:36 am #

    Good evening, I really have your explanation on the recognition of manuscript characters and its helped me a lot to understand the architecture and operation of a CNN with keras. But, I have a concern, you will not have a good tutorial that deals with the problem of face recognition with CNN … I have done with other approaches like OpenCV, dlib … But, Would like to do it with a CNN.
    Thank you…

  46. Abhranil June 16, 2017 at 9:24 pm #

    How will predict the prediction on a new test example?

    • Jason Brownlee June 17, 2017 at 7:25 am #

      Fit the model on the entire available dataset, then pass in an image to:

  47. Antonio June 23, 2017 at 5:53 am #

    Hi, Jason. A start to play with mnist and CNN in keras and your post was very helpful!
    Thanks!

    I have one question: In my tests I got poor probabilities distribution. In most cases we got 1 for the predicted class and 0 for others. I try figure out how to get a more informative distribution specially to able to find possible prediction errors. Initially I think that results have connection to a sigmoid activation function but look in the model we have only ReLu and Sofmax linear functions. Any suggestion on how we get more descriptive probabilities distribution?

    • Antonio June 23, 2017 at 6:14 am #

      I just see we have using Sofplus not Softmax function. I’ll try linear and relu functions to see whats the difference in outputs =)

Leave a Reply