You are on page 1of 2

Experiment 3

Perceptron Learning Rule:

Input:

import numpy as np

R = int(input("Enter the number of rows:"))


C = int(input("Enter the number of columns:"))

print("Enter the inputs in a single line (separated by space): ")

entries = list(map(int, input().split()))


x = np.array(entries).reshape(R, C)
print(x)
# np.ones((2, 1))

gate = int(input("Enter 1 for OR, 2 for AND, 3 for NOR, 4 for NAND and 5 for XOR: "))
if gate==1:
y = np.logical_or(x[:,0],x[:,1])
if gate==2:
y = np.logical_and(x[:,0],x[:,1])
if gate==3:
y = np.logical_not(np.logical_or(x[:,0],x[:,1]))
if gate==4:
y = np.logical_not(np.logical_and(x[:,0],x[:,1]))
if gate==5:
y = np.logical_xor(x[:,0],x[:,1])

X = np.array([[-1, -1, 1],


[-1, 1, 1],
[1, -1, 1],
[1, 1, 1]])

Y = np.array([-1, -1, -1, 1])

def activation(x):
if x == 0:
return 0
return 1 if x > 0 else -1
def perceptron(x, y, epochs):
alpha = 1
w = np.zeros((x.shape[1], 1))
for e in range(epochs):
for i in range(4):
y_pred = activation(np.dot(x[i], w))
if(y_pred != y[i]):
w += alpha * y[i] * x[i].reshape(3, 1)
return w

w = perceptron(X, Y, 10)
print(f"w1 = {w[0][0]} w2 = {w[1][0]} wb ={w[2][0]}")

Output:

You might also like