import numpy as np
class NeuralNetwork:
def __init__(self, layer_sizes):
"""
Initialize the network.
:param layer_sizes: A list of integers, e.g., [2, 4, 1]
(2 inputs, 4 hidden neurons, 1 output)
"""
self.layer_sizes = layer_sizes
self.num_layers = len(layer_sizes)
# Initialize weights and biases
# We use a dictionary to store parameters W1, b1, W2, b2...
self.parameters = {}
for l in range(1, self.num_layers):
# He initialization: sqrt(2 / n_previous_layer) helps with convergence
# Shape: (current_layer_size, previous_layer_size)
self.parameters[f"W{l}"] = np.random.randn(
layer_sizes[l], layer_sizes[l-1]
) * np.sqrt(2. / layer_sizes[l-1])
# Shape: (current_layer_size, 1)
self.parameters[f"b{l}"] = np.zeros((layer_sizes[l], 1))
# --- Activation Functions ---
def sigmoid(self, Z):
return 1 / (1 + np.exp(-Z))
def sigmoid_derivative(self, Z):
s = self.sigmoid(Z)
return s * (1 - s)
# --- Core Linear Algebra Steps ---
def forward_step(self, A_prev, W, b):
"""
Performs the linear combination: Z = W * A_prev + b
"""
Z = np.dot(W, A_prev) + b
cache = (A_prev, W, b, Z) # Store for backprop
return Z, cache
def forward_propagation(self, X):
"""
Runs the input X through the network layers.
"""
caches = []
A = X
L = self.num_layers - 1 # Number of weight layers
# Hidden Layers
for l in range(1, L):
A_prev = A
Z, linear_cache = self.forward_step(A_prev, self.parameters[f"W{l}"], self.parameters[f"b{l}"])
A = self.sigmoid(Z)
caches.append((linear_cache, Z)) # combined cache
# Output Layer
Z, linear_cache = self.forward_step(A, self.parameters[f"W{L}"], self.parameters[f"b{L}"])
A_output = self.sigmoid(Z)
caches.append((linear_cache, Z))
return A_output, caches
def compute_cost(self, Y_hat, Y):
"""
Cross-Entropy Loss
"""
m = Y.shape[1]
# Add small epsilon to avoid log(0)
epsilon = 1e-8
cost = -1/m * np.sum(Y * np.log(Y_hat + epsilon) + (1 - Y) * np.log(1 - Y_hat + epsilon))
return np.squeeze(cost)
def backward_step(self, dZ, cache):
"""
Calculates gradients for a single layer.
dZ: Gradient of the loss with respect to Z
"""
A_prev, W, b, Z = cache
m = A_prev.shape[1]
# Linear Algebra Gradient Calculations
# dW = dZ * A_prev^T
dW = (1/m) * np.dot(dZ, A_prev.T)
# db = sum of dZ across examples
db = (1/m) * np.sum(dZ, axis=1, keepdims=True)
# dA_prev = W^T * dZ (Propagate error backward)
dA_prev = np.dot(W.T, dZ)
return dA_prev, dW, db
def backward_propagation(self, Y_hat, Y, caches):
"""
Performs backpropagation through the entire network.
"""
grads = {}
L = self.num_layers - 1
m = Y_hat.shape[1]
Y = Y.reshape(Y_hat.shape)
# Derivative of Cost with respect to final Activation (Output Layer)
# Using simplified derivative for Sigmoid + Cross-Entropy: dCost/dZ = Y_hat - Y
epsilon = 1e-8
dA = -(np.divide(Y, Y_hat + epsilon) - np.divide(1 - Y, 1 - Y_hat + epsilon))
# Alternatively, usually for sigmoid output + cross entropy, the derivative dZ simplifies to (Y_hat - Y)
# Let's calculate dZ explicitly for clarity using chain rule logic
# dZ = dA * sigmoid_derivative(Z)
# Output Layer Gradients
linear_cache, activation_cache = caches[L-1] # Last cache
dZ = dA * self.sigmoid_derivative(activation_cache)
dA_prev, dW, db = self.backward_step(dZ, linear_cache)
grads[f"dW{L}"] = dW
grads[f"db{L}"] = db
dA = dA_prev
# Hidden Layers Gradients (Loop backward)
for l in reversed(range(1, L)):
linear_cache, activation_cache = caches[l-1]
dZ = dA * self.sigmoid_derivative(activation_cache)
dA_prev, dW, db = self.backward_step(dZ, linear_cache)
grads[f"dW{l}"] = dW
grads[f"db{l}"] = db
dA = dA_prev
return grads
def update_parameters(self, grads, learning_rate):
"""
Updates weights and biases using Gradient Descent.
W = W - learning_rate * dW
"""
L = self.num_layers - 1
for l in range(1, L + 1):
self.parameters[f"W{l}"] -= learning_rate * grads[f"dW{l}"]
self.parameters[f"b{l}"] -= learning_rate * grads[f"db{l}"]
# --- Training Loop ---
def train(self, X, Y, epochs, learning_rate=0.1, print_cost=True):
costs = []
for i in range(epochs):
# 1. Forward
Y_hat, caches = self.forward_propagation(X)
# 2. Cost
cost = self.compute_cost(Y_hat, Y)
# 3. Backward
grads = self.backward_propagation(Y_hat, Y, caches)
# 4. Update
self.update_parameters(grads, learning_rate)
if print_cost and i % 1000 == 0:
print(f"Cost after iteration {i}: {cost:.6f}")
costs.append(cost)
return costs
def predict(self, X):
Y_hat, _ = self.forward_propagation(X)
return (Y_hat > 0.5).astype(int)
# ==========================================
# EXAMPLE USAGE: Solving the XOR Problem
# ==========================================
# Input data (4 examples, 2 features each)
X_train = np.array([[0, 0, 1, 1],
[0, 1, 0, 1]])
# Labels (XOR logic: 0^0=0, 0^1=1, 1^0=1, 1^1=0)
Y_train = np.array([[0, 1, 1, 0]])
# Architecture: 2 inputs -> 4 hidden neurons -> 1 output
nn = NeuralNetwork(layer_sizes=[2, 4, 1])
print("Training Neural Network on XOR problem...")
nn.train(X_train, Y_train, epochs=10000, learning_rate=0.5)
# Test predictions
predictions = nn.predict(X_train)
print("\nPredictions:")
print(predictions)
print("\nGround Truth:")
print(Y_train)