How to Create a Neural Network in Python

76

In this tutorial, you will learn how to create a neural network in Python. To create a Neural Network model, Python provides a few packages like TensorFlow and Keras, which helps to create a machine learning neural network model with very few lines of code by abstracting away the low-level code.

To create any machine learning model below steps need to be implemented.

  1. Import necessary packages
  2. Load the dataset and divide the data into input and output form
  3. Define the model
  4. Fit the model on the data, which is separated as input & output form
  5. Evaluate the model
  6. Make predictions with the model.

Let’s create a Neural Network model step by step by following the abovementioned steps.

Also ReadOr Operator in Python

How to Create a Neural Network in Python

how to create a neural network in python

Also ReadNatural Language Processing in Python: Techniques

Import necessary packages

Here we import the NumPy package to load the data. Also, Sequential and Dense classes from the Keras library to define the model. Below is the code to import the required libraries.

# import necessary packages
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

Also ReadPython Reserved Words List With Definitions and Examples

Load the Dataset

We used the diabetes dataset, which contains patient entries of glucose, insulin, blood pressure levels, BMI, etc.

I am attaching the image of the downloaded dataset for clear visualization.

load the dataset

We need to remove the first row, i.e., label names, while loading the dataset to create the neural network model. Attaching the names of the removed columns Excel sheet used in this article to create the model.

Use numpy.loadtxt() method to load a dataset accepts two parameters – filename, and delimiter.

Perform slicing on the loaded data to get the input and output data. Below is the code to load the dataset.

# load the dataset
data = np.loadtxt('diabetesDataset.csv', delimiter=',')
# split the data into input and output
input = data[:,0:8] # Data from 0-7 columns
output = data[:,8] # Data of column 8

Also ReadHow to Fix Unexpected EOF While Parsing Error In Python

Define the model

Create a neural network model using the classes Sequential and Dense. Below is the code which is used to create the neural network model.

# define the keras neural network model
model = Sequential()
model.add(Dense(12, input_shape=(8,), activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

After defining the model, compile the model using the “compile” method, which helps represent the network for training and make predictions to run. Below is the code to compile the model.

# compile the model
model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])

Also ReadHow To Copy List in Python

Fit the model on the data

We will fit the model on the input and output data so that the model gets trained from the input and output data which can be helpful while predicting. Below is the code to fit the model on the data.

# fit the model on input, output data
model.fit(X, y)

Also Read10 Best Programming Apps To Learn Python

Evaluate the Model

By evaluating the model, we will get the accuracy score of the model. The higher the accuracy, the better the model makes predictions. The accuracy score lies between 0 and 1. Below is the code which is used to evaluate the model.

# finding accuracy
accuracy = model.evaluate(input, output)
accuracy

Output:

step – loss: 0.4672 – accuracy: 0.7760
[0.46723151206970215, 0.7760416865348816]

Also ReadPython Program To Reverse A Number

Make Predictions

Using the predict() function, we can make predictions by passing the input data to the predict() function. Below is the code to make predictions from the trained model.

# making predictions
model.predict(input)

Also ReadPython Program to Find Sum of Digits [5 Methods]

Code:

# import necessary packages
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
 
# load the dataset
data = np.loadtxt('diabetesDataset.csv', delimiter=',')
# split the data into input and output
input = data[:,0:8] # Data from 0-7 columns
output = data[:,8] # Data of column 8
 
# define the keras neural network model
model = Sequential()
model.add(Dense(12, input_shape=(8,), activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
 
# compile the model
model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])
 
# fit the model on input, output data
model.fit(X, y)
 
# finding accuracy
accuracy = model.evaluate(input, output)
accuracy

Output

step – loss: 0.4672 – accuracy: 0.7760
[0.46723151206970215, 0.7760416865348816]