## Introduction to Keras CNN

Keras CNN stands for the keras convolution neural network, which consists of various layers, including conv1D layer, conv2D layer, conv3D layer, separable Conv 1D layer, separable Conv2D layer, depthwise conv2D layer, conv2D transpose layer, and Conv 3D transpose layer. In this article, we will look at the topic of keras which is keras CNN. We will gain more knowledge about it by looking at the subtopics, which include What is keras CNN, How to use keras CNN, Uses of keras CNN model, examples, and Conclusions about the same.

### What is keras CNN?

Keras CNN is the neural network that makes the use of convolution, which is a mathematical operation carried out on matrices. The neural network consists of convolution layers containing the filters, similar to the matrices containing numbers.

For the convolutional neural network, we need to pass certain input images, and after the filters are applied, convolution happens, and the output images are produced. The process of convolution contains the following things –

- We will have to overlay the filter we want at a particular location on top of the specified input images.
- After that, we need to calculate element-wise for the values present inside the filter matrix and the values corresponding to them inside the image.
- We will have to sum the products we got by elementwise multiplication, which will be our final value for the pixel inside our output image.
- The above three steps are repeated for every location.

### How to use keras CNN?

We can use it to classify images in CIFAR, which involves training and creating our keras model using sequential API or any other. The steps required to use the keras CNN for creating and training the model are as mentioned –

- Importing all the necessary libraries and classes. One of the important ones is Tensorflow at the top of the program.
- Prepare the raw input data by downloading the CIFAR10 data set containing almost ten classes with more than 60000 images in colored format. Out of this testing, images have an approximate count of 10000 while training ones are around 50000 images.
- The next step is to verify the data set and check if it’s correct.
- We will now need to create a base of convolution by following a common pattern of having a stack of layers like conv2D and maxpooling 2d.
- We will now add one more layer at the top, which will be a dense layer for completing our model. This layer will get the inputs from the output of all the other tensor layers, which will be responsible for performing classification.
- Compiling the model and then training the same will be our next step which can be easily done using the methods of .compile() and .fit() for compile and training, respectively.
- Now we can evaluate the model by using evaluate() method for plotting and labeling the values, which will give the final results of the model.

### Uses of keras CNN model

The features and uses of keras CNN are found immensely in the classification of CIFAR images. Below mentioned are the features of keras CNN which are convolutional neural networks.

- The value of the layer of input is 1,8,28.
- Conv2D forms the first layer of the model containing a total of 32 filters along with the presence of the relu function used for activation. In addition, it has the kernel size set to (3,3).
- There is a presence of one more conv2d layer, which acts as the second layer having a relu activation function along with 64 filters in it with a total size of kernel set to (3,3).
- The third layer of this neural network is Max pooling with (2,2) as the size of the pool.
- The flatten layer used for getting all the inputs flattened into one dimension is present in the fifth layer.
- The sixth layer is made up of 128 neurons and is a dense layer that also contains the relu activation function in it.
- The Droput layer forms the seventh layer of the neural network, which has a value of 0.5.
- Our CNN’s final and 8
^{th}layer comprises a softmax activation function and contains ten neurons. - We will make use of the loss function of categorical cross-entropy.
- The optimizer that will be used will be Ada delta.
- Metrics for our neural network will be accurate.
- The batch size is 128.
- The epoch value for the count of iterations of training is 20.

### Example of Keras CNN

Different examples are mentioned below:

`//importing the necessary classes and libraries`

import keras

from keras.datasets import mnist

from keras.sampleEducbaModels import Sequential

from keras.layers import Dense, Dropout, Flatten

from keras.layers import Conv2D, MaxPooling2D

from keras import backend as sampleEducba

import numpy as np

// Loading the mnist dataset for the sample purpose

(xValueForTraining, yValueForTraining), (xValueForTesting, yValueForTesting) = mnist.load_data()

//modify the existing data set for our requirement of the sampleEducbaModel.

rowsOfImage, columnsOfImage = 28, 28

if sampleEducba.image_data_format() == 'channels_first':

xValueForTraining = xValueForTraining.reshape(xValueForTraining.shape[0], 1, rowsOfImage, columnsOfImage)

xValueForTesting = xValueForTesting.reshape(xValueForTesting.shape[0], 1, rowsOfImage, columnsOfImage)

input_shape = (1, rowsOfImage, columnsOfImage)

else:

xValueForTraining = xValueForTraining.reshape(xValueForTraining.shape[0], rowsOfImage, columnsOfImage, 1)

xValueForTesting = xValueForTesting.reshape(xValueForTesting.shape[0], rowsOfImage, columnsOfImage, 1)

input_shape = (rowsOfImage, columnsOfImage, 1)

xValueForTraining = xValueForTraining.astype('float32')

xValueForTesting = xValueForTesting.astype('float32')

xValueForTraining /= 255

xValueForTesting /= 255

yValueForTraining = keras.utils.to_categorical(yValueForTraining, 10)

yValueForTesting = keras.utils.to_categorical(yValueForTesting, 10)

// Model creation

sampleEducbaModel = Sequential()

sampleEducbaModel.add(Conv2D(32, kernel_size = (3, 3),

activation = 'relu', input_shape = input_shape))

sampleEducbaModel.add(Conv2D(64, (3, 3), activation = 'relu'))

sampleEducbaModel.add(MaxPooling2D(pool_size = (2, 2)))

sampleEducbaModel.add(Dropout(0.25)) sampleEducbaModel.add(Flatten())

sampleEducbaModel.add(Dense(128, activation = 'relu'))

sampleEducbaModel.add(Dropout(0.5))

sampleEducbaModel.add(Dense(10, activation = 'softmax'))

// Model compilation

sampleEducbaModel.compile(loss = keras.losses.categorical_crossentropy,

optimizer = keras.optimizers.Adadelta(), metrics = ['accuracy'])

// training the sampleEducbaModel by using fit function

sampleEducbaModel.fit(

xValueForTraining, yValueForTraining,

batch_size = 128,

epochs = 12,

verbose = 1,

validation_data = (xValueForTesting, yValueForTesting)

)

Output on execution –

If we add the code for the evaluation of the model to the above one, as shown below –

`// Model evaluation by using test data`

score = sampleEducbaModel.evaluate(xValueForTesting, yValueForTesting, verbose = 0)

print('Loss acquired during testing :', score[0])

print('Test accuracy:', score[1])

The output of the execution of the above code snippet is –

99.22% is test accuracy for identification of handwriting. We will add the following code to the above for prediction, which will result in different outputs –

`// Prediction`

resultantPredictions = sampleEducbaModel.predict(xValueForTesting)

resultantPredictions = np.argmax(pred, axis = 1)[:5]
puttedLabel= np.argmax(yValueForTesting,axis = 1)[:5]
print(resultantPredictions)

print(puttedLabel)

Output after execution –

### Conclusion

Keras CNN, the convolutional neural network, is widely used to classify the images of type CIFAR. The network consists of many layers, which help to predict and evaluate the results.

### Recommended Articles

This is a guide to Keras CNN. Here we discuss keras CNN, How to use keras CNN, examples, and uses of the keras CNN model. You may also look at the following articles to learn more –