make minimal changes to implement batch gradient descent (i.e. just one batch instead of SGD performed below):
class DenseNeuralNetwork:
def init(self, layer_sizes, activations, loss_f):
self.learning_rate = None # Learning rate
self.layer_sizes = layer_sizes # Array storing the layer sizes
self.loss_f = loss_f # Loss function
code
Assistant
# The array of weights, biases, net inputs, and activation functions have their first element as None to represent that
# input layers don't have them, this also helps match the indexes of expressions here match with their mathematical formulas
# To store weights(W) and biases(b)
np.random.seed(42)
self.W = [None] + [np.random.uniform(-1, 1, (layer_sizes[i], layer_sizes[i-1])) for i in range(1, len(layer_sizes))]
self.b = [None] + [np.random.uniform(-1, 1, layer_sizes[i]) for i in range(1, len(layer_sizes))]
# To store activations(a) and net inputs(z)
self.a = [np.zeros(size) for size in layer_sizes] # This one does not start with None, because input layer activates with same value as the inputs
self.z = [None] + [np.zeros(layer_sizes[i]) for i in range(1, len(layer_sizes))]
# Set the activation functions for each layer
self.activation_f = activations # The first None element is passed as input here
def propagate_forward(self, x):
# Set input layer activations
self.a[0] = x
for i in range(1, len(self.W)):
self.z[i] = self.W[i] @ self.a[i-1] + self.b[i] # Weighted sum
self.a[i] = self.activation_f[i].function(self.z[i]) # Activation
def propagate_backward(self, y_true):
error_term = {}
# Store the index of the last layer as L
L = len(self.W) - 1
# For output layer:-
if self.activation_f[L] == Softmax:
error_term[L] = self.activation_f[L].derivative(self.z[L]) @ self.loss_f.gradient(y_true, self.a[L])
# print('LAST LAYER ERROR TERM (FROM MATRIX MULTIPLICATION): ', error_term[L]) # For debugging
else:
error_term[L] = self.activation_f[L].derivative(self.z[L]) * self.loss_f.gradient(y_true, self.a[L])
# Update weights and biases for output layer based on those error terms
self.W[L] -= self.learning_rate * np.outer(error_term[L], self.a[L-1])
self.b[L] -= self.learning_rate * error_term[L]
# For hidden layers:-
for i in reversed(range(1, L)):
## Propgating error terms backward
if self.activation_f[i] == Softmax:
error_term[i] = self.activation_f[i].derivative(self.z[i]) @ (self.W[i+1].T @ error_term[i+1])
else:
error_term[i] = self.activation_f[i].derivative(self.z[i]) * (self.W[i+1].T @ error_term[i+1])
## Updating the weights and biases based on those error terms
self.W[i] -= self.learning_rate * np.outer(error_term[i], self.a[i-1])
self.b[i] -= self.learning_rate * error_term[i]
# Training loop
def train(self, X_train, y_train, X_val, y_val, epochs=100, learning_rate=0.01, verbose=True):
training_losses, validation_losses, training_accuracies, validation_accuracies = [], [], [], []
self.learning_rate = learning_rate
for epoch in range(epochs):
total_loss, correct_predictions = 0, 0
for i in range(X_train.shape[0]):
x, y_true = X_train[i], y_train[i]
self.propagate_forward(x)
total_loss += self.loss_f.function(y_true, self.a[-1])
if self.is_correct_prediction(self.a[-1], y_true):
correct_predictions += 1
self.propagate_backward(y_true)
avg_loss = total_loss / X_train.shape[0]
accuracy = correct_predictions / X_train.shape[0] * 100
training_losses.append(avg_loss)
training_accuracies.append(accuracy)
# Validation phase
val_loss, val_correct_predictions = 0, 0
for i in range(X_val.shape[0]):
x, y_true = X_val[i], y_val[i]
self.propagate_forward(x)
val_loss += self.loss_f.function(y_true, self.a[-1])
# Use np.argmax for validation comparison as well
if self.is_correct_prediction(self.a[-1], y_true):
val_correct_predictions += 1
val_avg_loss = val_loss / X_val.shape[0]
val_accuracy = val_correct_predictions / X_val.shape[0] * 100
validation_losses.append(val_avg_loss)
validation_accuracies.append(val_accuracy)
if verbose:
print(f"Epoch {epoch+1}")
print(f"Training Loss = {avg_loss}, Validation Loss = {val_avg_loss}")
print(f"Training Accuracy: {accuracy:.3f}%, Validation Accuracy: {val_accuracy:.3f}%")
print("----------------------------------------------------------------------")
return training_losses, validation_losses, training_accuracies, validation_accuracies
# Checks if the prediction has been made correctly; used to evalutue accuracy
# This function may need to be altered based on the type of problem being solved
def is_correct_prediction(self, predicted, true):
if len(predicted) == 1:
# For binary classification, if neuron o/p > 0.5 we consider it postive class
return ((predicted > 0.5).astype(int)) == true
else:
# For multiclass classification
# Use np.argmax to convert predicted and true values to class labels for comparison
return np.argmax(predicted) == np.argmax(true)
# For making predctions after training the network
def predict(self, x):
# Forward propagate through all layers
self.propagate_forward(x)
# The output of the last layer is the prediction
y_pred = self.a[-1]
return y_pred
# For evaluating test accuracy later on
def get_test_accuracy(self, X_test, y_test):
correct_predictions = 0
total_loss = 0
for i in range(X_test.shape[0]):
x, y_true = X_test[i], y_test[i]
self.propagate_forward(x)
# Accumulate loss
total_loss += self.loss_f.function(y_true, self.a[-1])
# Check if predicted class matches the true class
if self.is_correct_prediction(self.a[-1], y_true):
correct_predictions += 1
# Calculate accuracy
accuracy = correct_predictions / X_test.shape[0] * 100
# Average loss
avg_loss = total_loss / X_test.shape[0]
print(f"Test Loss: {avg_loss}")
print(f"Test Accuracy: {accuracy:.3f}%")
return avg_loss, accuracy
To implement batch gradient descent in your DenseNeuralNetwork class with minimal changes, you need to modify the training loop so that gradients are accumulated over the entire training dataset before updating the weights and biases. This change ensures that updates are based on the average gradient of the entire batch rather than individual samples, which is characteristic of batch gradient descent.
Here's how you can achieve this:
Modify the propagate_backward Method:
Instead of updating the weights and biases immediately within the propagate_backward method, adjust this method to return the gradients. This allows accumulation of gradients over all training samples before applying the update.
Update the train Method:
In the training loop, accumulate the gradients returned by propagate_backward for each training sample. After processing all samples in an epoch, update the weights and biases using the accumulated gradients.
Below is the updated code with the necessary modifications:
python
import numpy as np
class DenseNeuralNetwork:
def __init__(self, layer_sizes, activations, loss_f):
self.learning_rate = None # Learning rate
self.layer_sizes = layer_sizes # Array storing the layer sizes
self.loss_f = loss_f # Loss function
# The array of weights(W) and biases(b) have their first element as None
np.random.seed(42)
self.W = [None] + [np.random.uniform(-1, 1, (layer_sizes[i], layer_sizes[i-1]))
for i in range(1, len(layer_sizes))]
self.b = [None] + [np.random.uniform(-1, 1, layer_sizes[i])
for i in range(1, len(layer_sizes))]
# To store activations(a) and net inputs(z)
self.a = [np.zeros(size) for size in layer_sizes] # Input layer activates with input values
self.z = [None] + [np.zeros(layer_sizes[i]) for i in range(1, len(layer_sizes))]
# Set the activation functions for each layer
self.activation_f = activations # The first None element is passed as input here
def propagate_forward(self, x):
# Set input layer activations
self.a[0] = x
for i in range(1, len(self.W)):
self.z[i] = self.W[i] @ self.a[i-1] + self.b[i] # Weighted sum
self.a[i] = self.activation_f[i].function(self.z[i]) # Activation
def propagate_backward(self, y_true):
error_term = {}
grad_W = [None] + [np.zeros_like(w) for w in self.W[1:]]
grad_b = [None] + [np.zeros_like(bias) for bias in self.b[1:]]
# Store the index of the last layer as L
L = len(self.W) - 1
# For output layer
if isinstance(self.activation_f[L], Softmax):
error_term[L] = self.activation_f[L].derivative(self.z[L]) @ self.loss_f.gradient(y_true, self.a[L])
else:
error_term[L] = self.activation_f[L].derivative(self.z[L]) * self.loss_f.gradient(y_true, self.a[L])
# Compute gradients for the output layer
grad_W[L] = np.outer(error_term[L], self.a[L-1])
grad_b[L] = error_term[L]
# For hidden layers
for i in reversed(range(1, L)):
if isinstance(self.activation_f[i], Softmax):
error_term[i] = self.activation_f[i].derivative(self.z[i]) @ (self.W[i+1].T @ error_term[i+1])
else:
error_term[i] = self.activation_f[i].derivative(self.z[i]) * (self.W[i+1].T @ error_term[i+1])
# Compute gradients for hidden layers
grad_W[i] = np.outer(error_term[i], self.a[i-1])
grad_b[i] = error_term[i]
return grad_W, grad_b
# Training loop with Batch Gradient Descent
def train(self, X_train, y_train, X_val, y_val, epochs=100, learning_rate=0.01, verbose=True):
training_losses, validation_losses, training_accuracies, validation_accuracies = [], [], [], []
self.learning_rate = learning_rate
for epoch in range(epochs):
total_loss, correct_predictions = 0, 0
# Initialize gradient accumulators
grad_W_accum = [None] + [np.zeros_like(w) for w in self.W[1:]]
grad_b_accum = [None] + [np.zeros_like(bias) for bias in self.b[1:]]
for i in range(X_train.shape[0]):
x, y_true = X_train[i], y_train[i]
self.propagate_forward(x)
total_loss += self.loss_f.function(y_true, self.a[-1])
if self.is_correct_prediction(self.a[-1], y_true):
correct_predictions += 1
# Get gradients from backward propagation
grad_W, grad_b = self.propagate_backward(y_true)
# Accumulate gradients
for l in range(1, len(self.W)):
grad_W_accum[l] += grad_W[l]
grad_b_accum[l] += grad_b[l]
# Update weights and biases after processing the entire batch
for l in range(1, len(self.W)):
self.W[l] -= (self.learning_rate / X_train.shape[0]) * grad_W_accum[l]
self.b[l] -= (self.learning_rate / X_train.shape[0]) * grad_b_accum[l]
# Calculate average loss and accuracy for the epoch
avg_loss = total_loss / X_train.shape[0]
accuracy = (correct_predictions / X_train.shape[0]) * 100
training_losses.append(avg_loss)
training_accuracies.append(accuracy)
# Validation phase
val_loss, val_correct_predictions = 0, 0
for i in range(X_val.shape[0]):
x, y_true = X_val[i], y_val[i]
self.propagate_forward(x)
val_loss += self.loss_f.function(y_true, self.a[-1])
if self.is_correct_prediction(self.a[-1], y_true):
val_correct_predictions += 1
val_avg_loss = val_loss / X_val.shape[0]
val_accuracy = (val_correct_predictions / X_val.shape[0]) * 100
validation_losses.append(val_avg_loss)
validation_accuracies.append(val_accuracy)
if verbose:
print(f"Epoch {epoch+1}")
print(f"Training Loss = {avg_loss:.4f}, Validation Loss = {val_avg_loss:.4f}")
print(f"Training Accuracy: {accuracy:.2f}%, Validation Accuracy: {val_accuracy:.2f}%")
print("----------------------------------------------------------------------")
return training_losses, validation_losses, training_accuracies, validation_accuracies
# Checks if the prediction has been made correctly; used to evaluate accuracy
def is_correct_prediction(self, predicted, true):
if len(predicted) == 1:
# For binary classification, if neuron output > 0.5, consider it positive class
return ((predicted > 0.5).astype(int) == true).all()
else:
# For multiclass classification, use np.argmax for comparison
return np.argmax(predicted) == np.argmax(true)
# For making predictions after training the network
def predict(self, x):
self.propagate_forward(x)
return self.a[-1]
# For evaluating test accuracy later on
def get_test_accuracy(self, X_test, y_test):
correct_predictions = 0
total_loss = 0
for i in range(X_test.shape[0]):
x, y_true = X_test[i], y_test[i]
self.propagate_forward(x)
total_loss += self.loss_f.function(y_true, self.a[-1])
if self.is_correct_prediction(self.a[-1], y_true):
correct_predictions += 1
accuracy = (correct_predictions / X_test.shape[0]) * 100
avg_loss = total_loss / X_test.shape[0]
print(f"Test Loss: {avg_loss:.4f}")
print(f"Test Accuracy: {accuracy:.2f}%")
return avg_loss, accuracy
Explanation of Changes:
propagate_backward Method:
Purpose: Instead of updating the weights and biases immediately, this method now calculates and returns the gradients for weights (grad_W) and biases (grad_b).
Implementation:
Initializes grad_W and grad_b as lists of zero matrices/vectors corresponding to each layer.
Computes the error_term for each layer as before.
Calculates the gradients using the outer product for weights and direct error terms for biases.
Returns the accumulated gradients for all layers.
train Method:
Gradient Accumulators:
Before the inner loop over training samples, initialize grad_W_accum and grad_b_accum to accumulate gradients for each layer.
Accumulating Gradients:
For each training sample, perform forward propagation and compute the loss.
Use propagate_backward to obtain gradients for the current sample.
Accumulate these gradients in grad_W_accum and grad_b_accum.
Updating Weights and Biases:
After processing all samples in the training set, update the weights and biases once per epoch using the average gradients.
The gradients are averaged by dividing by the number of training samples (X_train.shape[0]).
Logging:
The training and validation losses and accuracies are computed and logged as before.
Maintaining Other Functionalities:
The is_correct_prediction, predict, and get_test_accuracy methods remain unchanged, ensuring that other functionalities of the neural network are preserved.
Benefits of This Approach:
Batch Gradient Descent Implementation: By accumulating gradients over the entire batch before updating, the training process aligns with the batch gradient descent methodology.
Minimal Code Changes: The core structure of the class remains intact. Only the backward propagation and training loop are adjusted to support batch updates.
Scalability: Although this implementation uses batch gradient descent, further modifications can allow for mini-batch gradient descent by adjusting the gradient accumulation logic.
Notes:
Memory Considerations: Batch gradient descent can be memory-intensive for very large datasets since gradients for all samples need to be stored simultaneously. For such cases, mini-batch gradient descent is recommended.
Activation Function Check: Ensure that the activation function comparison uses isinstance (as shown) rather than direct comparison (e.g., self.activation_f[L] == Softmax) to avoid potential issues with class references.
By following these modifications, your neural network will now perform batch gradient descent, updating its parameters once per epoch based on the accumulated gradients from the entire training dataset.