How To Make A CNN Using Tensorflow and Keras

Mohammed AL-Ma'amari
4 min readSep 5, 2018

--

Convolutional neural network is a useful topic to learn nowadays , from image recognition ,video analysis to natural language processing , their applications are everywhere .

What is Convolutional Neural Network [1]

A convolutional neural network (CNN, or ConvNet) is a class of deep, feed-forward artificial neural networks, most commonly applied to analyzing visual imagery. Convolutional networks were inspired by biological processes in that the connectivity pattern between neurons resembles the organization of the animal visual cortex. They have applications in image and video recognition, recommender systems and natural language processing.

Applications of CNNs [2] :

  • Image recognition
  • Video analysis
  • Natural language processing
  • Drug discovery
  • Health Risk Assessment and Biomarkers of Aging discovery

Why I Chose TensorFlow :

There are many reasons that made me a big fan of TF , I’ll mention some of them :

  • It is easy to learn
  • TF has a big community .
  • TensorFlow is flixable ,and it supports many types of ML models
  • You can use graphs to debug your models .

Now we are going to build a CNN .

It is such an easy thing to achieve , all you have to do is following the next four steps :

Step 1 :

Import the next modules:

import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D

Step 2 :

Load your data, I had my data ready to be used, and it was saved before as numpy array :

X = np.load('X_data.npy')
y = np.load('y_data.npy')

Don’t forget to normalize your data :

X = X/255.0

I divided X by 255 because of the fact that my data contain gray scale images

Step 3 :

Define a model , In our case we chose Sequential (to learn more about this visit https://goo.gl/2AvHg2 ) :

model = Sequential()

Now add some layers :

Because we want to make a convolutional neural network (CNN) we will be using Conv2D as our first and second hidden layers . it’s totally fine to use more than two convolutional hidden layers , but in this example I’ll use two .

1- The first conv layer :

I have to mention that in this layer we have to specify the shape of our input , we used X.shape[1:] to get the shape of our input data. Also we’ll choose relu as our activation function , relu stands for Rectified Linear

# Conv2D( number_of_filters , kernal_size , input_shape(add this parameter just for the input conv layer))
model.add(Conv2D(64 , (3,3) , input_shape = X.shape[1:] ))
# define the activaion function for this layer
model.add(Activation('relu'))
# define the pooling for this layer
model.add(MaxPooling2D(pool_size= (2,2)))

2- The second conv layer :

model.add(Conv2D(64 , (3,3) ))
# define the activaion function for this layer
model.add(Activation('relu'))
# define the pooling for this layer
model.add(MaxPooling2D(pool_size= (2,2)))

3- Now add a dense layer (with 64 nodes) :

But first you have to flatten the data , Flatten() is used to convert 3D features to 1D feartures :

model.add(Flatten())
model.add(Dense(64))

4- Now add the output layer (with 1 output node):

The output will be eather 0 or 1 .

model.add(Dense(1))
model.add(Activation('sigmoid'))

Step 4 :

Configure the model for training :

  • loss function is binary crossentropy
  • Optimizer is adam
  • Scoring metric will be accuracy
model.compile(loss = 'binary_crossentropy', 
optimizer = 'adam',
metrics = ['accuracy'])

Then fit the model , in our case we’ll use the next parameters :

  • batch_size = 32
  • 3 epoches
  • 10% of data for validating the model
model.fit(X, y, batch_size = 32, epochs = 3, validation_split = 0.1)

Congratulations! , you made your first CNN

Now if you want to save it to use it later without going through the previous steps , you can use the following line :

model.save('myFirstCNN.model')

Finally , if you want to print a summary about your CNN :

model.summary()

Conclusion :

Convolutional neural network is a must learn subject in these days , especially when we need to design a ML system that deals with images as its inputs .

Resources :

This notebook is inspired by a tutorial created by Sentdix , you can find it on :

Other resources :

[1]

https://en.wikipedia.org/wiki/Convolutional_neural_network

[2] https://en.wikipedia.org/wiki/Convolutional_neural_network#Applications

[3]

You can follow me on Twitter @ModMaamari

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Mohammed AL-Ma'amari
Mohammed AL-Ma'amari

Written by Mohammed AL-Ma'amari

I am a computer engineer | I love machine learning and data science and spend my time learning new stuff about them.

No responses yet

Write a response