Python Keras Features Must to Know in 2020 with Real Time Use Case

In this DataFlair Keras features tutorial, we will discuss and study some of the features of Keras. We will also be performing handwritten digit classification on MNIST dataset using Python Keras and its features. This is one of the top Keras use case.

Before we start with Keras features, let’s revise Neural Networks for better understanding.

Keras Features

Keeping you updated with latest technology trends, Join DataFlair on Telegram

What is Keras?

Keras is a neural network library in python that generally uses TensorFlow, Microsoft CNTK or Theano as its backend.
You can install Keras and its backend (preferably TensorFlow) from PyPI as:

pip install Keras
pip install tensorFlow

Why Learn Keras ?

Keras focuses on user experiences, using Keras users have to write minimum code in order to perform common functions.
It is modular and extensible, we can reuse and extend a model or a piece of code in the future.

Keras Features

Let us see some of the top features of Keras that make it work learning:

1. Prelabeled Datasets

  • Keras provides a ton of prelabeled datasets that you can directly import and load.
    Example: CIFAR10 small image classification, IMDB movie review sentiment classification, Reuters newswire topics classification, MNIST handwritten digit dataset, and few others (these are the examples of some famous datasets that are available in Keras)
  • To import and load these MNIST dataset (a dataset):
from Keras.datasets import mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()

2. Numerous implemented layers and parameters

Keras contains numerous implemented layers and parameters like loss functions, optimizers, evaluations metric. We use these layers and parameters for construction, configuration, training and evaluation of neural networks.

  • We would load the required layers to build our digit classifier.
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.optimizers import Adam
from keras.utils import np_utils

Keras also has support for 1D and 2D convolutions and recurrent neural nets and for our digit classifier, we would use Convolution neural nets(Conv2D layer).

from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D

3. Multiple methods for Data Preprocessing

Keras also has a ton of methods for data preprocessing, here we would use Keras.np_utils.to_categorical() method for one-hot encoding of y_train and y_test.
Before that reshape and normalize the dataset for our requirements.

#reshape in form of (60000, 28, 28, 1)

X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], X_train.shape[2], 1).astype('float32')

X_test = X_test.reshape(X_test.shape[0], X_test.shape[1], X_test.shape[2], 1).astype('float32')

#normalize to get data in range of 0-1

number_of_classes = 10
y_train = np_utils.to_categorical(y_train, number_of_classes)
y_test = np_utils.to_categorical(y_test, number_of_classes)

4. .add() Method in Keras

To add layers imported above by specifying parameters to build our digit classifier,it is done using .add() method.

model = Sequential()
model.add(Conv2D(32, (5, 5), input_shape=(X_train.shape[1], X_train.shape[2], 1), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(32, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dense(128, activation='relu'))
model.add(Dense(number_of_classes, activation='softmax')

5. .compile() Method in Keras

Before training, we need to configure our learning process which is done using .compile() method.

model.compile(loss='categorical_crossentropy', optimizer=Adam(), metrics=['accuracy'])

6. .fit() method

We train Keras models on numpy arrays using .fit()., y_train, validation_data=(X_test, y_test), epochs=5, batch_size=200)

The training may take some time, here I have used only 5 epochs but you can increase the epoch count as per your systems.
The training looks like:

Features of Keras

7. Model Evaluation

After training our model we test our results on unseen data or we evaluate our model using .predict_classes() or .evaluate().
You can test your model on your own handwritten digits. I tested it on the following handwritten digit.


But before giving it as the input you need to convert it in the form of MNIST dataset digits.
MNIST dataset digits are grayscale images of (28*28*1) dimensions.

import cv2
img = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)
# resize image
resized = cv2.resize(img, (28,28), interpolation = cv2.INTER_AREA)
img = np.resize(resized, (28,28,1))
im2arr = np.array(img)
im2arr = im2arr.reshape(1,28,28,1)
y_pred = model.predict_classes(im2arr)



You can see my model predicted it successfully.

8. Modularity

As discussed above, Keras is modular, we can save the model we train and use this model later by loading it.

This is done as:'model.h5')


Finally, we have seen introduction to some common features of Keras. In this article, we learnt how to load a dataset, how to build a model, how to add layers with its parameters, how to compile, train and evaluate a model in Keras.

This article also has the codes to build a Handwritten digit classifier on MNIST dataset. It shows how we can make deep learning projects in Keras in only tens of lines of code.

Hope you enjoyed this article. Do share your feedback in the comment section.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.