Creating a Multilayer Perceptron (MLP) from scratch without the help of high-level libraries involves several steps, including initializing the network's weights and biases, performing feedforward operation, backpropagation with derivatives for updating the weights, and finally training the network.
Below is a Python implementation of a simple MLP with the ability to specify the number of neurons in each layer. This implementation uses only numpy for numerical operations:
import numpy as np
class MLP:
def __init__(self, layer_sizes):
self.layer_sizes = layer_sizes
self.weights = []
self.biases = []
for i in range(len(layer_sizes) - 1):
weight = np.random.randn(layer_sizes[i+1], layer_sizes[i]) * np.sqrt(1 / layer_sizes[i])
bias = np.zeros((layer_sizes[i+1], 1))
self.weights.append(weight)
self.biases.append(bias)
def sigmoid(self, z):
return 1 / (1 + np.exp(-z))
def sigmoid_derivative(self, z):
return self.sigmoid(z) * (1 - self.sigmoid(z))
def feedforward(self, x):
a = x.reshape(-1, 1)
activations = [a]
for weight, bias in zip(self.weights, self.biases):
z = np.dot(weight, a) + bias
a = self.sigmoid(z)
activations.append(a)
return activations
def backpropagation(self, x, y, activations):
m = y.shape[0]
deltas = [None] * len(self.weights)
# Output error
deltas[-1] = activations[-1] - y.reshape(-1, 1)
# Backpropagate the error
for l in range(len(deltas) - 2, -1, -1):
deltas[l] = self.weights[l + 1].T.dot(deltas[l + 1]) * self.sigmoid_derivative(activations[l + 1])
# Store the gradients for weight and bias
gradient_w = []
gradient_b = []
for l in range(len(deltas)):
gradient_w.append(deltas[l].dot(activations[l].T) / m)
gradient_b.append(np.mean(deltas[l], axis=1, keepdims=True))
return gradient_w, gradient_b
def update_weights(self, gradients_w, gradients_b, learning_rate):
for i in range(len(self.weights)):
self.weights[i] -= learning_rate * gradients_w[i]
self.biases[i] -= learning_rate * gradients_b[i]
def train(self, x, y, learning_rate=0.01, epochs=1000):
for epoch in range(epochs):
activations = self.feedforward(x)
gradients_w, gradients_b = self.backpropagation(x, y, activations)
self.update_weights(gradients_w, gradients_b, learning_rate)
if epoch % 100 == 0:
loss = np.mean(np.square(y - activations[-1]))
print(f'Epoch {epoch}, Loss: {loss}')
# Example usage for 2-layer MLP with 2 neurons in input layer,
# 3 neurons in hidden layer, and 1 neuron in output layer
mlp = MLP([2, 3, 1])
# XOR problem
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
Y = np.array([[0], [1], [1], [0]])
mlp.train(X, Y, learning_rate=0.1, epochs=5000)
Please note the following:
- The
MLP class allows the creation of a neural network with a customizable architecture.
- The
__init__ method initializes the network weights and biases with random values. Weights are initialized with small random values, scaled using the square root of the number of input units (He initialization).
- The
sigmoid function is used as the activation function.
- The
feedforward method calculates the output of the network given a set of inputs.
- The
backpropagation method computes the gradients of the loss with respect to the weights using the chain rule.
- The
update_weights method applies these gradients to the weights and biases, scaled by a learning rate.
- The
train method runs the feedforward and backpropagation steps iteratively in a training loop and updates the network weights and biases.
This example illustrates an MLP with one hidden layer, but the class can be instantiated with any number of layers, as specified by the layer_sizes parameter.
Remember that this is a highly simplified and non-optimized example. Building a full-featured MLP capable of handling real-world datasets and tasks would require additional functionality, such as better weight initialization methods, more advanced optimization techniques (like momentum or Adam), regularizations like dropout, and different activation functions.