Automatic Differentiation is a powerful technique used in machine learning to compute the gradients of a function with respect to its inputs. In this case, we will use Dual Numbers to implement Automatic Differentiation and train a Neural Network without using any specific library.
Here's a simple example of how you can implement a Neural Network using Automatic Differentiation with Dual Numbers in Python:
python
class DualNumber:
def __init__(self, value, derivative):
self.value = value
self.derivative = derivative
def __add__(self, other):
if isinstance(other, (int, float)):
return DualNumber(self.value + other, self.derivative)
return DualNumber(self.value + other.value, self.derivative + other.derivative)
def __sub__(self, other):
if isinstance(other, (int, float)):
return DualNumber(self.value - other, self.derivative)
return DualNumber(self.value - other.value, self.derivative - other.derivative)
def __mul__(self, other):
if isinstance(other, (int, float)):
return DualNumber(self.value * other, self.derivative * other)
return DualNumber(self.value * other.value, self.value * other.derivative + self.derivative * other.value)
def __truediv__(self, other):
if isinstance(other, (int, float)):
return DualNumber(self.value / other, self.derivative / other)
return DualNumber((self.value * other.value) / (other.value ** 2), (self.derivative * other.value - self.value * other.derivative) / (other.value ** 2))
def __radd__(self, other):
return self + other
def __rsub__(self, other):
return -self + other
def __rmul__(self, other):
return self * other
def __rtruediv__(self, other):
return DualNumber(other / self.value, -other * self.derivative / (self.value ** 2))
def __repr__(self):
return f"DualNumber({self.value}, {self.derivative})"
def sigmoid(x):
return 1 / (1 + exp(-x))
def sigmoid_derivative(x):
return x * (1 - x)
def mse_loss(y_true, y_pred):
return ((y_true - y_pred) ** 2).value
def mse_loss_derivative(y_true, y_pred):
return -2 * (y_true - y_pred)
# Define the neural network architecture
input_size = 2
hidden_size = 3
output_size = 1
# Initialize weights and biases
weights_input_hidden = [DualNumber(random(), 0) for _ in range(input_size * hidden_size)]
biases_hidden = [DualNumber(random(), 0) for _ in range(hidden_size)]
weights_hidden_output = [DualNumber(random(), 0) for _ in range(hidden_size * output_size)]
biases_output = [DualNumber(random(), 0) for _ in range(output_size)]
# Define the forward pass
def forward(x):
hidden_layer = [sigmoid(sum(weights_input_hidden[i * hidden_size + j] * x[j] for j in range(input_size)) + biases_hidden[i]) for i in range(hidden_size)]
output_layer = sum(weights_hidden_output[i] * hidden_layer[i] for i in range(hidden_size)) + biases_output[0]
return output_layer
# Define the training loop
learning_rate = 0.1
num_epochs = 1000
for epoch in range(num_epochs):
total_loss = 0
for x, y_true in dataset:
# Forward pass
y_pred = forward(x)
# Compute loss
loss = mse_loss(y_true, y_pred)
total_loss += loss
# Backward pass
grad_y_pred = mse_loss_derivative(y_true, y_pred)
grad_output = grad_y_pred
grad_hidden = [0] * hidden_size
for i in range(hidden_size):
grad_hidden[i] = grad_output * weights_hidden_output[i] * sigmoid_derivative(hidden_layer[i])
# Update weights and biases
for i in range(hidden_size):
for j in range(input_size):
weights_input_hidden[i * input_size + j] -= learning_rate * grad_hidden[i] * x[j]
biases_hidden[i] -= learning_rate * grad_hidden[i]
for i in range(output_size):
for j in range(hidden_size):
weights_hidden_output[i * hidden_size + j] -= learning_rate * grad_output * hidden_layer[j]
biases_output[i] -= learning_rate * grad_output
# Print the average loss for this epoch
average_loss = total_loss / len(dataset)
print(f"Epoch {epoch + 1}/{num_epochs} - Loss: {average_loss}")
In this example, we define a DualNumber class that represents a number with both a value and a derivative. We then define some mathematical operations for DualNumber objects, such as addition, subtraction, multiplication, and division.
We also define the sigmoid activation function and its derivative, as well as the mean squared error loss function and its derivative.
The neural network architecture is defined with an input layer, a hidden layer, and an output layer. We initialize the weights and biases randomly.
The forward pass of the neural network is defined in the forward function, which takes an input x and returns the predicted output y_pred.
The training loop is defined using the mean squared error loss function and the gradient descent optimization algorithm. In each iteration of the loop, we compute the loss and the gradients of the loss with respect to the weights and biases using Automatic Differentiation with Dual Numbers. We then update the weights and biases using the gradients and a learning rate.
You can replace the dataset variable with your own dataset to train the neural network on your data.