Building a Simple Neural Network using TensorFlow

Shashi Gharti
Women Data Greenhorns
4 min readJul 17, 2018

TensorFlow is an open source, deep learning library initially developed by Google Brain Team. It was made publicly available on November 9, 2015, and is actively maintained by Google. TensorFlow has various applications and it is widely being used for deep learning. Real-world usage of TensorFlow is in image recognition, sentiment analysis, speech recognition, e-commerce application and many more.

I will show you how to develop a simple machine learning model to detect malignant and benign breast cancer using freely available data from Kaggle.

Prerequisites to get started:

  1. Download the data from Kaggle.
  2. Google Collab cloud platform : It a cloud service provided by google. We can use it to develop and test our AI models using GPU accelerators for free. We don’t have to set up our local machine to get started, easy !!.
  3. Python 3 , Numpy, Tensorflow and Keras

In Google Collab, create a new python notebook. Go to File->New Python 3 notebook as shown in the image below. A new notebook will be created.

Change runtime to use GPU accelerator in order to speed up the processing time. To set GPU go to Runtime->Change Run Time -> Hardware Acceleration -> GPU. Now you are ready to code!!!

To use TensorFlow with GPU run the following code:

import tensorflow as tfdevice_name = tf.test.gpu_device_name()
if device_name != ‘/device:GPU:0’:
raise SystemError(‘GPU device not found’)
print(‘Found GPU at: {}’.format(device_name))

https://colab.research.google.com

Upload the data using following code:

import pandas as pd
from sklearn.model_selection import train_test_split
import io
from google.colab import files
file_uploaded = files.upload()

Upload the file that you downloaded from Kaggle as shown in the image below:

Read the data from CSV file and split it to X and Y variables:

import pandas as pd
import io
import keras
from sklearn.model_selection import train_test_split
dataset = pd.read_csv(io.StringIO(file_uploaded['data.csv'].decode('utf-8')))# split into input (X) and output (Y) variables
dataset['diagnosis'] = dataset['diagnosis'].map({'B': 1, 'M': 0})
X = dataset.iloc[:, 2:32].values
y = dataset.iloc[:, 1].values
y = keras.utils.to_categorical(y, num_classes = 2)

Now let’s split the data into train and test data. We will use sklearn library to split the data.

X_train, X_test, y_train, y_test = train_test_split(X, y,test_size = 0.2)#test the shape of the train and test 
print(‘x_train shape:’, X_test.shape)
print(X_train.shape[0], ‘train samples’)
print(X_test.shape[0], ‘test samples’)

Next setup is to build a 2 layered CNN model. In sequential model, we can stack up the hidden layers as shown in the code below. Both layers have 32 neurons each. LeakyReLU is an activation function and is very popular in CNN among other activation functions as it avoids vanishing gradient problem. We use sigmoid activation for the output layer.

model = Sequential()
dim = X_train.shape[1]
#Layer 1
model.add(Dense(32, input_dim = dim))
model.add(LeakyReLU())
model.add(Dropout(0.25))
#Layer 2
model.add(Dense(32))
model.add(LeakyReLU())
model.add(Dropout(0.25))
#output layer
model.add(Dense(2))
model.add(Activation(‘sigmoid’))
model.compile(optimizer = ’rmsprop’,loss = ’binary_crossentropy’,
metrics = [‘accuracy’])

Let’s train our model. We have set batch size to 32 which means 32 rows will be processed at once. The whole training process will have 5 iterations as we have set epochs to 5.

#Fit/Train the model
bsize = 32
model.fit(X_train, y_train, batch_size = bsize, epochs = 5, verbose = 1,validation_data = (X_test, y_test))

Output

Finally!! we trained a model and you can see the results. In each epoch, the accuracy is increased and the final accuracy is 63% which is not bad :). This means our trained model can now detect a malignant or benign breast cancer with 63% accuracy. You can download the running version of the code from here.

Summary

In this article, we learned how to quickly develop our own Neural Network model using open source data from Kaggle, TensorFlow, Keras and Google Collab cloud service. This tutorial is a simple example of how quickly we can develop a Neural Network model. I hope this tutorial will be helpful for starters who want to learn machine learning.

--

--

Shashi Gharti
Women Data Greenhorns

Full-Stack Developer, Entrepreneur, Machine Learning and AI Enthusiasts