Neural Network Code
Neural Network Code
X = np.array([
[0, 1],
[1, 0],
[1, 1],
[0, 0]
])
y = np.array([
[1],
[1],
[0],
[0]
])
# Parameters
np.random.seed(1)
# Activation function
if derv:
return 1 / (1 + np.exp(-z))
# Forward propagation
z2 = W1.dot(a1) + B1 # 2x1
z3 = W2.dot(a2) + B2 # 1x1
if predict:
return a3
# Training function
for i in range(max_iter):
c = 0
dW1 = np.zeros_like(W1)
dW2 = np.zeros_like(W2)
dB1 = np.zeros_like(B1)
dB2 = np.zeros_like(B2)
for j in range(m):
# Forward propagation
a0 = X[j].reshape(X[j].shape[0], 1) # 2x1
z1 = W1.dot(a0) + B1 # 2x1
a1 = sigmoid(z1) # 2x1
z2 = W2.dot(a1) + B2 # 1x1
a2 = sigmoid(z2) # 1x1
# Backpropagation
# Compute cost
B1 -= learning_rate * (dB1 / m)
B2 -= learning_rate * (dB2 / m)
cost_history[i] = c / m
plt.plot(range(max_iter), cost_history)
plt.xlabel("Iterations")
plt.ylabel("Cost")
plt.show()