gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
Make me a mutilayer perceptron from scratch in py with only numpy
- User
Make me a mutilayer perceptron from scratch in py with only numpy
- Assistant
Make me a mutilayer perceptron from scratch in py with only numpy
Sure! Here's an implementation of a Multi-Layer Perceptron (MLP) from scratch using only NumPy in Python:
import numpy as np
# Define the Multi-Layer Perceptron class
class MLP:
def __init__(self, num_inputs=3, hidden_layers=[3, 3], num_outputs=2):
self.num_inputs = num_inputs
self.hidden_layers = hidden_layers
self.num_outputs = num_outputs
layers = [self.num_inputs] + self.hidden_layers + [self.num_outputs]
# Initialize weights and biases for each layer
self.weights = []
self.biases = []
for i in range(len(layers) - 1):
weight = np.random.randn(layers[i], layers[i+1])
bias = np.zeros((1, layers[i+1]))
self.weights.append(weight)
self.biases.append(bias)
# Define the sigmoid activation function
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
# Define the derivative of the sigmoid function
def sigmoid_derivative(self, x):
return x * (1 - x)
# Define the forward propagation step
def forward_propagation(self, inputs):
self.activations = []
self.activations.append(inputs)
for i in range(len(self.weights)):
# Multiply inputs by weights and add biases
net_inputs = np.dot(self.activations[i], self.weights[i]) + self.biases[i]
# Apply the activation function
layer_output = self.sigmoid(net_inputs)
self.activations.append(layer_output)
return self.activations[-1]
# Define the backward propagation step
def backward_propagation(self, target, learning_rate=0.1):
deltas = []
error = target - self.activations[-1]
delta = error * self.sigmoid_derivative(self.activations[-1])
deltas.append(delta)
# Backpropagate the error and update weights and biases
for i in range(len(self.weights)-1, -1, -1):
error = deltas[-1].dot(self.weights[i].T)
delta = error * self.sigmoid_derivative(self.activations[i])
deltas.append(delta)
# Reverse the deltas list
deltas.reverse()
# Update weights and biases
for i in range(len(self.weights)):
self.weights[i] += self.activations[i].T.dot(deltas[i]) * learning_rate
self.biases[i] += np.sum(deltas[i], axis=0) * learning_rate
# Define the training function
def train(self, inputs, targets, epochs):
for i in range(epochs):
# Iterate through each training example
for j in range(len(inputs)):
output = self.forward_propagation(inputs[j])
self.backward_propagation(targets[j])
if (i + 1) % 10 == 0:
loss = np.mean(np.square(targets - self.forward_propagation(inputs)))
print(f"Epoch {i+1}/{epochs}, Loss: {loss}")
# Define the predict function
def predict(self, inputs):
return self.forward_propagation(inputs)
# Example usage
if __name__ == "__main__":
# Create a dataset for XOR gate
inputs = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
targets = np.array([[0], [1], [1], [0]])
# Create and train the Multi-Layer Perceptron
mlp = MLP(num_inputs=2, hidden_layers=[2], num_outputs=1)
mlp.train(inputs, targets, epochs=100)
# Test the trained model
test_input = np.array([[0, 0]])
print("Prediction:", mlp.predict(test_input))
In this example, we create a Multi-Layer Perceptron (MLP) using the MLP class. The constructor takes the number of inputs, hidden layers, and number of outputs as arguments. The forward_propagation method performs the forward pass, and the backward_propagation method performs the backward pass to update the weights and biases. The train method trains the MLP using the given inputs and targets for the specified number of epochs.
Finally, we test the trained MLP by passing a test input through the predict method.