4a.Write a program for Back Propagation Algorithm

import numpy as np
import math


x1, x2 = 0, 1
alpha = 0.25
v1 = np.array([0.6, 0.3])
v2 = np.array([-0.1, 0.4])
w = np.array([-0.2, 0.4, 0.1])

b1, b2 = 0.3, 0.5


zin1 = b1 + x1*v1[0] + x2*v2[0]
zin2 = b2 + x1*v1[1] + x2*v2[1]

z1 = 1 / (1 + math.exp(-zin1))
z2 = 1 / (1 + math.exp(-zin2))

yin = w[0] + z1*w[1] + z2*w[2]
y = 1 / (1 + math.exp(-yin))

print("Output y =", round(y, 4))


fy = y * (1 - y)
dk = (1 - y) * fy


dw1 = alpha * dk * z1
dw2 = alpha * dk * z2
dw0 = alpha * dk


din1 = dk * w[1]
din2 = dk * w[2]


d1 = din1 * z1 * (1 - z1)
d2 = din2 * z2 * (1 - z2)


v1[0] += alpha * d1 * x1
v1[1] += alpha * d2 * x1
v2[0] += alpha * d1 * x2
v2[1] += alpha * d2 * x2


b1 += alpha * d1
b2 += alpha * d2


w[1] += dw1
w[2] += dw2
w[0] += dw0


print("Updated v1 =", v1)
print("Updated v2 =", v2)
print("Updated w =", w)
print("Updated b1 =", b1, " b2 =", b2)



4b : Write a program for error Backpropagation algorithm.

x = 1
target = 0.8
learning_rate = 0.5

w1 = 0.4
w2 = 0.6

def sigmoid(x):
    return 1 / (1 + math.exp(-x))

net_hidden = x * w1
hidden_output = sigmoid(net_hidden)

net_output = hidden_output * w2
final_output = sigmoid(net_output)

print("Network Output:", final_output)

error = target - final_output

delta_output = error * final_output * (1 - final_output)

delta_hidden = delta_output * w2 * hidden_output * (1 - hidden_output)


w2 = w2 + learning_rate * delta_output * hidden_output

w1 = w1 + learning_rate * delta_hidden * x


print("Updated Weight w1:", w1)
print("Updated Weight w2:", w2)