Implementation Of Single-Layer Perceptron

Implementation Of Single-Layer Perceptron

Table of contents

No heading

No headings in the article.

Step1: Import Necessary Libraries

Numpy: Numpy arrays are very fast and can perform large computations in a very short time.

Matplotlib: Used for Visualizations.

Tensorflow: This is an open-source library that is used for Machine Learning and Artificial Intelligence and provides a range of functions to achieve complex functionalities with single lines of code.

import numpy as np
import pandas as pd
from tensorflow import keras
import matplotlib.pyplot as plt

Step2: Now Load the dataset using "Keras" from the imported version of tensor flow.

(X_train,y_train),(X_test,y_test)=keras.datasets.mnist.load_data()

Step3: Now display the shape and image of the single image in the dataset.The image size contains a 28*28 matrix and length of the training set is 60,000 and testing set is 10,000

print(f"Training set:{X_train.shape}")
print(f"Testing set:{X_test.shape}")

print(X_train[1].shape) 
plt.matshow(X_train[1])

Step4: Now normalise the dataset in order to compute the calculations in a fast and accurate manner.

#Normalizing the dataset
x_train=X_train/255
x_test=X_test/255

#Flatting the dataset in order to compute for model building
x_train_flatten=x_train.reshape(len(x_train),28*28)
x_test_flatten=x_test.reshape(len(x_test),28*28)
x_train_flatten.shape

Step5: Building a neural network with single-layer perceptron.Here we can observe as the model is a single-layer perceptron that only contains one input layer and one output layer there is no presence of the hidden layers.

model=keras.Sequential([
    keras.layers.Dense(10,input_shape=(784,),
                      activation='sigmoid')
])

model.compile(
     optimizer='adam',
     loss='sparse_categorical_crossentropy',
     metrics=['accuracy'])

model.fit(x_train_flatten,y_train,epochs=5)

Step6: Output the accuracy of the model on the testing data.

model.evaluate(x_test_flatten,y_test)