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

In this DataFlair Keras features tutorial, you study some of the features of Keras that you must know in 2021.

You will also perform handwritten digit classification on the MNIST dataset using Python Keras and its features. This is one of the top Keras use case.

So let’s start.

Keras Features

Don't become Obsolete & get a Pink Slip
Follow DataFlair on Google News & Stay ahead of the game

What is Keras?

Keras is a neural network library in python that generally uses TensorFlow, Microsoft CNTK or Theano as its backend.

It is more user friendly and easy as compared to TensorFlow.

You can install Keras and its backend (preferably TensorFlow) from PyPI as:

pip install Keras
pip install tensorFlow

Why Learn Keras?

Keras is based on python that is very easy to debug and explore.

It focuses on user experiences. Using Keras you have to write minimum code in order to perform common functions.

It is modular and extensible, you can reuse and extend a model or a piece of code in the future.

It also supports almost all neural network models.

Keras Features

Let us see some of the top features of Keras that make it worth 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 this 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.

You can use these layers and parameters for construction, configuration, training, and evaluation of neural networks.

  • You would load the required layers to build your 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, you 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 you 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 your 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 your 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, you need to configure your learning process which is done using .compile() method.

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

6. .fit() method

You can 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 this:

Features of Keras

7. Model Evaluation

After training your model, you need to test your results on unseen data or you can evaluate your 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. You can save the model you train and use this model later by loading it.

This is done as:'model.h5')


Finally, you have seen some common features of Keras.

You also learned 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 you can make deep learning projects in Keras in only tens of lines of code.

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.