Implementation of Perceptron Algorithm for AND Logic with 2-bit binary input in Python

Before we start the implementation question arises What is Perceptron?

Perceptron is an algorithm in machine learning used for binary classifiers. It is a supervised learning algorithm. To implement the perceptron algorithm, we use the function:

Perceptron Algorithm for AND Logic with 2-bit binary input in Python

In this function, is the weight vector and b is bias parameter, for any choice of W  and b, the function makes output y(unit vector ^) for the equivalent input vector X.

Now, in this problem, we have to implement it with the help of AND gate, as we know the logical truth table for AND gate for the 2-bit binary variable. Let’s consider input vector x=(x1, x2)  and output is y

Image:

Perceptron Algorithm for AND Logic with 2-bit binary input in Python

We now consider the weight vector

W=(w1, w2) of the input vector

X=(x1,  x2) Perceptron function

Image:

X=(x1,  x2) Perceptron function

Code: Perceptron Algorithm for AND Logic with 2-bit binary input in Python

For implementation in code, we consider weight W1= 2 and  W2= 2 and value of b(bias paramter) = -1 

 

import numpy as np 
  
# implementing unit Step 
def Steps(v): 
    if v >= 0: 
        return 1
    else: 
        return 0
  
# creating Perceptron 
def perceptron(x, w, b): 
    v = np.dot(w, x) + b 
    y = Steps(v) 
    return y 
   
def logic_AND(x): 
    w = np.array([2, 2]) 
    b = -1
    return perceptron(x, w, b) 
  
# testing the Perceptron Model 
p1 = np.array([0, 1]) 
p2 = np.array([1, 1]) 
p3 = np.array([0, 0]) 
p4 = np.array([1, 0]) 
  
print("AND(0, 1) = {}".format( logic_AND(p1))) 
print("AND(1, 1) = {}".format( logic_AND(p2))) 
print("AND(0, 0) = {}".format( logic_AND(p3))) 
print("AND(1, 0) = {}".format( logic_AND(p4)))

Output

AND(0, 1) = 1
AND(1, 1) = 1
AND(0, 0) = 0
AND(1, 0) = 1
[Program finished]

Also read:

Leave a Reply