Write a Python program that uses Automatic Differentiation to train a Neural Network…
- User
Write a Python program that uses Automatic Differentiation to train a Neural Network using Dual Numbers without using any specific library.
Assistant
Below is a simplified example of a Python program that uses automatic differentiation with dual numbers to train a basic neural network. This example focuses on illustrating the concept rather than achieving state-of-the-art performance or handling large datasets. We'll implement a simple neural network with one hidden layer, using mean squared error (MSE) as the loss function, and gradient descent for optimization.
Dual Number Implementation for Automatic Differentiation
Dual numbers are an extension of real numbers that can be used to efficiently compute derivatives. A dual number has the form , where and are real numbers, and is a nilpotent infinitesimal, i.e., . This allows us to track both the value of a function and its derivative simultaneously through arithmetic operations.
pythonclass DualNumber: def __init__(self, real, dual=0.0): self.real = real self.dual = dual def __add__(self, other): if isinstance(other, DualNumber): return DualNumber(self.real + other.real, self.dual + other.dual) else: return DualNumber(self.real + other, self.dual) def __sub__(self, other): if isinstance(other, DualNumber): return DualNumber(self.real - other.real, self.dual - other.dual) else: return DualNumber(self.real - other, self.dual) def __mul__(self, other): if isinstance(other, DualNumber): return DualNumber(self.real * other.real, self.real * other.dual + other.real * self.dual) else: return DualNumber(self.real * other, self.dual * other) def __truediv__(self, other): if isinstance(other, DualNumber): # Simplified, does not handle dual part of denominator for simplicity return DualNumber(self.real / other.real, (self.dual * other.real - self.real * other.dual) / (other.real ** 2)) else: return DualNumber(self.real / other, self.dual / other) def __repr__(self): return f"Real: {self.real}, Dual: {self.dual}"Simple Neural Network with One Hidden Layer
pythonimport numpy as np def sigmoid(x): return 1 / (1 + np.exp(-x)) def sigmoid_derivative(x): return x * (1 - x) class NeuralNetwork: def __init__(self, input_dim, hidden_dim, output_dim): self.input_dim = input_dim self.hidden_dim = hidden_dim self.output_dim = output_dim # Initialize weights randomly self.weights1 = np.random.rand(self.input_dim, self.hidden_dim) self.weights2 = np.random.rand(self.hidden_dim, self.output_dim) # Initialize bias self.bias1 = np.zeros((1, self.hidden_dim)) self.bias2 = np.zeros((1, self.output_dim)) def forward(self, x): # Forward pass using dual numbers for automatic differentiation x_dual = np.array([[DualNumber(xi) for xi in row] for row in x]) # First layer z1_dual = np.dot(x_dual, np.array([[DualNumber(w) for w in row] for row in self.weights1])) + np.array([[DualNumber(b) for b in row] for row in self.bias1]) a1_dual = np.vectorize(lambda z: DualNumber(sigmoid(z.real), z.dual * sigmoid_derivative(z.real)))(z1_dual) # Second layer z2_dual = np.dot(a1_dual, np.array([[DualNumber(w) for w in row] for row in self.weights2])) + np.array([[DualNumber(b) for b in row] for row in self.bias2]) a2_dual = np.vectorize(lambda z: DualNumber(sigmoid(z.real), z.dual * sigmoid_derivative(z.real)))(z2_dual) return a1_dual, a2_dual def train(self, inputs, targets, learning_rate, epochs): for epoch in range(epochs): a1_dual, a2_dual = self.forward(inputs) # Calculate loss and its derivative (using dual part) loss = np.mean((np.array([[z.real for z in row] for row in a2_dual]) - targets) ** 2) loss_derivative = np.mean(np.array([[z.dual for z in row] for row in a2_dual])) # Backpropagation d_weights2 = np.dot(np.array([[z.real for z in row] for row in a1_dual]).T, (np.array([[z.real for z in row] for row in a2_dual]) - targets) * sigmoid_derivative(np.array([[z.real for z in row] for row in a2_dual]))) d_weights1 = np.dot(inputs.T, np.dot((np.array([[z.real for z in row] for row in a2_dual]) - targets) * sigmoid_derivative(np.array([[z.real for z in row] for row in a2_dual])), self.weights2.T) * sigmoid_derivative(np.array([[z.real for z in row] for row in a1_dual]))) # Weight updates self.weights2 -= learning_rate * d_weights2 self.weights1 -= learning_rate * d_weights1 print(f"Epoch {epoch+1}, Loss: {loss}, Loss Derivative: {loss_derivative}") # Example Usage if __name__ == "__main__": np.random.seed(0) # Example inputs and targets inputs = np.random.rand(10, 5) # 10 samples, 5 features targets = np.random.rand(10, 3) # 10 samples, 3 outputs nn = NeuralNetwork(input_dim=5, hidden_dim=10, output_dim=3) nn.train(inputs, targets, learning_rate=0.1, epochs=100)Important Notes:
-
Simplification for Illustration: While the backpropagation step in the
trainmethod is more accurate, the use of dual numbers for automatic differentiation in neural networks is still a simplification. Dual numbers are typically used for first-order derivatives and may not be practical for deeper networks or more complex models. -
Dual Number Limitation: This example does not handle the complexity of nested function derivatives that arise in deeper networks or more complex architectures. For practical applications, libraries like TensorFlow or PyTorch, which can handle these complexities, are recommended.
-
Learning Rate and Epochs: The choice of learning rate and number of epochs in the example is arbitrary and may not lead to optimal convergence in a real scenario.
-
Activation Functions: Only sigmoid activation functions are used here for simplicity. In practice, other activations like ReLU, tanh, or softmax might be more appropriate depending on the task.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.