import numpy as np
# Sigmoid activation and its derivative
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
# x is the output of sigmoid function
return x * (1 - x)
# Create fake dataset (X: inputs, y: outputs)
# For example, XOR problem
X = np.array([[0,0],
[0,1],
[1,0],
[1,1]])
y = np.array([[0],
[1],
[1],
[0]])
# Network architecture
input_size = 2
hidden_size = 3
output_size = 1
# Initialize weights and biases
np.random.seed(42)
W1 = np.random.randn(input_size, hidden_size)
b1 = np.zeros((1, hidden_size))
W2 = np.random.randn(hidden_size, output_size)
b2 = np.zeros((1, output_size))
# Hyperparameters
learning_rate = 0.1
epochs = 10000
for epoch in range(epochs):
# Forward pass
z1 = X.dot(W1) + b1
a1 = sigmoid(z1)
z2 = a1.dot(W2) + b2
a2 = sigmoid(z2) # Output prediction
# Compute loss (MSE)
loss = np.mean((a2 - y)**2)
# Backpropagation
# Output layer error
delta2 = (a2 - y) * sigmoid_derivative(a2) # shape (4,1)
# Hidden layer error
delta1 = delta2.dot(W2.T) * sigmoid_derivative(a1) # shape (4,3)
# Gradients for weights and biases
dW2 = a1.T.dot(delta2) # shape (3,1)
db2 = np.sum(delta2, axis=0, keepdims=True) # shape (1,1)
dW1 = X.T.dot(delta1) # shape (2,3)
db1 = np.sum(delta1, axis=0, keepdims=True) # shape (1,3)
# Update weights and biases
W2 -= learning_rate * dW2
b2 -= learning_rate * db2
W1 -= learning_rate * dW1
b1 -= learning_rate * db1
# Print loss every 1000 epochs
if epoch % 1000 == 0:
print(f"Epoch {epoch}, Loss: {loss:.4f}")
# Testing
print("\nFinal Predictions after training:")
print(np.round(a2, 3))