Flattening
Flattening is nothing but converting a 3D or 2D matrix into a 1D input for the model this will be our last step to process the image and connect the inputs to a fully connected dense layer for further classification.
To sum up, The way a convolution neural network works is:
- Applying convolution to find different importand features inside the image
syntax: model.add(layers.Conv2D(no. of kernels, size of the kernel, activation=’relu’, input_shape)
- Applying pooling to compress the image without losing its features
syntax: model.add(layers.MaxPooling2D((size of the kernel)))
- FLattening it to a 1-dimensional input from a 3D[color images] or 2D [Black and white images] to pass into the model
syntax: model.add(layers.Flatten()
- Fully connected input and hidden layers to play with weights and biases and activation functions and optimizers.
- Wola! You have built the best image classifier.
A typical CNN model will look like:
Python
# Importing the library import tensorflow as tf from tensorflow import keras # Designing the model model = tf.keras.models.Sequential([ # Convolutional layer1 tf.keras.layers.Conv2D( 32 , ( 3 , 3 ), activation = 'relu' , input_shape = ( 32 , 32 , 3 )) tf.keras.layers.MaxPooling2D(( 2 , 2 )) # Pooling # COnvolutional layer2 tf.keras.layers.Conv2D( 64 , ( 3 , 3 ), activation = 'relu' ) tf.keras.layers.MaxPooling2D(( 2 , 2 )) # Pooling # COnvolutional layer3 tf.keras.layers.Conv2D( 64 , ( 3 , 3 ), activation = 'relu' ) tf.keras.layers.MaxPooling2D(( 2 , 2 )) # Pooling # Flattening the input tf.keras.layers.Flatten(), # Fully connected layers tf.keras.layers.Dense( 128 , activation = 'relu' ), tf.keras.layers.Dense( 256 , activation = 'relu' ), tf.keras.layers.Dense( 10 , activation = 'softmax' ) ]) # Compiling the model model. compile (optimizer = 'adam' , loss = tf.keras.losses.SparseCategoricalCrossentropy( from_logits = True ), metrics = [ 'accuracy' ]) # FItting the data to a model history = model.fit(train_images, train_labels, epochs = 10 , validation_data = (test_images, test_labels)) |
Output:
Working of Convolutional Neural Network (CNN) in Tensorflow
In this article, we are going to see the working of convolution neural networks with TensorFlow a powerful machine learning library to create neural networks.
Now to know, how a convolution neural network lets break it into parts. the 3 most important parts of this convolution neural networks are,
- Convolution
- Pooling
- Flattening
These 3 actions are the very special things that make convolution neural networks perform way better compared with other artificial neural networks. Now, let’s discuss them in detail,