deep learning model in python with keras

Share on facebook
Share on twitter
Share on linkedin
Share on telegram
Share on whatsapp

Contents

This article was published as part of the Data Science Blogathon

Introduction

An artificial neural network is a subfield of artificial intelligence compiled under deep learning neural networks that attempts to mimic the network of neurons that the human brain makes, allowing them to understand and respond like a human.

44394first20keras20model20feature20img-2377445

Table of Contents

  • Neural network overview
  • Introduction to Keras
  • Step-by-step implementation of your first Keras model
  • Combining all the code
  • EndNote

Brief description of the neural network

The neural network consists of a larger set of neurons, called layered units. In simple words, Neural Network is designed to perform a more complex task where Machine Learning algorithms do not find their use and do not achieve the required performance.

Neural networks are used to perform many complex tasks, including image classification, object detection, face identification, the text summary, voice recognition and the list is endless.

How do neural networks learn complex characteristics? A neural network has many layers and each layer performs a specific and complex function the network. The more layers are, more performance is received. That is why the neural network is also called a multilayer perceptron..

Introduction to the Kears Library

Keras is a fast neural network library, Open source and easy to use written in Python that runs on top of Theano or Tensorflow. Tensorflow provides both low-level and high-level APIs; in fact, Keras only provides high-level API.

As a beginner, it is recommended to work first with Keras and then move to TensorFlow. The reason is that using Tensorflow functions as a beginner is a bit complex to understand and interpret, but Keras functionality is simple.

Create your first neural network model with Keras

We will build a simple artificial neural network using Keras step by step which will help you create your own model in the future.

Paso 1) Load data

We are going to use the Pima Indians diabetes data that you can download from here. It is a simple data set provided by the UCI Machine Learning data set, containing a medical record of Indian patients. We have to predict whether the patient has an onset of diabetes within 5 years.

import pandas as pd
data = pd.read_csv('diabetes.csv')
x = data.drop("Outcome", axis=1)
y = data["Outcome"]
25441diabetes_dataset_img-8297579

It is a binary classification problem where we have to say if your diabetes onset is 1 or not like 0. All columns are numeric, which facilitates the direct creation of a neural network on it. Therefore, we have separated independent and dependent data.

Paso 2) Define the Keras model

The model in Keras is always defined as a sequence of layers. It means we initialize the sequence model and add the layers one after another which runs as the sequence from the list. We practically have to try experimenting with the process of adding and removing layers until we are happy with our architecture..

What you need to take care of is that the first layer has the correct number of input characteristics that is specified using the input_dim parameter. we can specify the number of neurons as the first argument of a layer. to define the activation function use the activation argument.

In this example, we will define a fully connected network with three layers. To define the fully connected layer, use Keras Dense class.

  • The first layer has 12 neurons and activation function as relu
  • The second hidden layer has 8 neurons and activation function as relu
  • Finally, in the output layer, we use 1 unit and activation as sigmoid because it is a binary classification problem.
from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
model.add(Dense(12, input_dim=8, activation="resume"))
model.add(Dense(12, activation="resume"))
model.add(Dense(1, activation="sigmoid"))

Remember to specify the correct shape of the data in the first layer known as the input layer.

Paso 3) Compile the Keras model

When we compile the Keras model, use backend numeric libraries like TensorFlow or Theano. Whatever backend you are using, automatically chooses the best way to represent the network on your hardware, as CPU, GPU o TPU.

When we compile the model, we need to specify some additional parameters to better evaluate the model and find the best set of weights to assign inputs to outputs.

  1. Loss function: the loss function must be specified to evaluate the set of weights to which the model will be mapped. We will use the cross entropy as a loss function which is actually known as binary cross entropy used for binary classification.
  2. Optimizer: the second is the optimizer to optimize the loss. We will use adam, which is a popular version of gradient descent and gives the best result on most problems.
model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"])

Paso 4) Start training (fit the model)

After successful compilation of the model, we are ready to fit the data to the model and start training the neural network. In addition to providing data to model, we need to define a number of epochs and a batch size in which the training occurs.

  • Epoch: single pass through all rows of training dataset
  • Batch size: number of samples considered by the model before updating the weights.
model.fit(x,Y, epochs=150, batch_size=10)

An epoch can be made up of more than one batch. These parameters are finally decided after the heat and test method.

Paso 5) Evaluate the model

After training the model, let's know the performance of a neural network. The model is always evaluated in a test set. In this example, For simplicity, we have trained on a complete data set, but while working on any project, basically splits the data and trains the network.

_, accuracy = model.evaluate(x, Y)
print("Model accuracy: %.2f"% (accuracy*100))

To evaluate the model, use the evaluation method and pass the input and output to the model and check the performance.

Paso 6) Make predictions

predict the output of new data simply using the prediction method. we have a binary classification problem statement, so the output will be simply 0 O 1.

predictions = model.predict(x)
print([round(x[0]) for x in predictions])

Alternatively, you can also use the predict_classes function to directly predict classes.

That is solved, we have easily created a neural network with 3 layers using just a few lines of code with Keras.

Compile all the code together

model = Sequential()  #define model
model.add(Dense(12, input_dim=8, activation="resume"))
model.add(Dense(8, activation="resume"))
model.add(Dense(1, activation="sigmoid"))
model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"]) #compile model
model.fit(x,Y, epochs=150, batch_size=10)  #training
_, accuracy = model.evaluate(x,Y)    #testing
print("Model accuracy: %.2f"% (accuracy*100))
predictions = model.predict(x)     #make predictions
#round the prediction
rounded = [round(x[0]) for x in predictions]

EndNote

A neural network builds a network of connected layers with multiple neurons in each layer. As we increase the number of layers, the network is capable of learning more complex characteristics.

You have easily created your first neural network model with Keras. I hope it was easy to grasp all the things. If you have any question, please comment. I'll be happy to help you.

If you like the article, check out my other items. Link

Subscribe to our Newsletter

We will not send you SPAM mail. We hate it as much as you.