The issues you're encountering—specifically, the rapid increase in loss values and the appearance of NaN (Not a Number) values—are indicative of numerical instability in your neural network training process. This instability is often caused by factors such as excessively large weight updates, which can lead to overflow errors during computations like matrix multiplications and exponential operations in the Softmax function.
Let's delve into the potential causes and provide actionable solutions to stabilize and improve your network’s training process.
1. Learning Rate is Too High
Cause:
A high learning rate can cause the weights to update too aggressively, leading to large changes that destabilize the training process. This can result in the loss function producing NaN values due to overflow in computations.
Solution:
Reduce the learning rate to ensure smaller, more controlled updates to the weights. A common strategy is to start with a smaller learning rate such as 0.001 or even 0.0001 and adjust as needed based on training behavior.
# Example: Reducing the learning rate
network.train(X_train, y_train, X_val, y_val, epochs=100, learning_rate=0.001, verbose=True)
2. Weight Initialization Strategy
Cause:
Initializing weights with values uniformly distributed between -1 and 1 can sometimes lead to large initial activations, especially in deeper networks, which can exacerbate the problem of numerical instability.
Solution:
Adopt a more sophisticated weight initialization method such as Xavier (Glorot) Initialization or He Initialization. These methods consider the size of the previous layer to maintain a controlled flow of gradients.
Xavier Initialization Example:
import numpy as np
def xavier_init(size_in, size_out):
limit = np.sqrt(6 / (size_in + size_out))
return np.random.uniform(-limit, limit, (size_out, size_in))
class DenseNeuralNetwork:
def __init__(self, layer_sizes, activations, loss_f):
self.learning_rate = None
self.layer_sizes = layer_sizes
self.loss_f = loss_f
np.random.seed(42)
self.W = [None] + [xavier_init(layer_sizes[i-1], layer_sizes[i])
for i in range(1, len(layer_sizes))]
self.b = [None] + [np.zeros(layer_sizes[i]) for i in range(1, len(layer_sizes))]
# ... rest of the initialization remains the same
He Initialization (suitable for ReLU activations):
def he_init(size_in, size_out):
stddev = np.sqrt(2 / size_in)
return np.random.randn(size_out, size_in) * stddev
3. Normalize Input Data
Cause:
Unnormalized input data can cause neurons to receive inputs that are too large or too small, which can lead to activation functions producing saturated outputs and gradients becoming too large during backpropagation.
Solution:
Ensure that your input data is properly normalized. Common practices include:
- Standardization: Subtract the mean and divide by the standard deviation.
- Min-Max Scaling: Scale the data to a fixed range, typically
[0, 1].
Example:
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_val = scaler.transform(X_val)
X_test = scaler.transform(X_test)
4. Check Activation Functions in Hidden Layers
Cause:
Certain activation functions like ReLU can produce large activations if not properly managed, especially if weights are not initialized correctly or if the learning rate is too high.
Solution:
Ensure that the activation functions used in hidden layers are appropriate and consider using activation variants that help mitigate issues like the dying ReLU problem (e.g., Leaky ReLU).
Example:
class LeakyReLU:
@staticmethod
def function(z, alpha=0.01):
return np.where(z > 0, z, alpha * z)
@staticmethod
def derivative(z, alpha=0.01):
return np.where(z > 0, 1, alpha)
5. Implement Gradient Clipping
Cause:
Even with a lower learning rate, gradients can sometimes become excessively large, leading to instability.
Solution:
Implement gradient clipping to limit the magnitude of gradients during backpropagation.
Example:
def propagate_backward(self, y_true):
# ... existing code to compute dW and db
# Gradient clipping
clip_value = 1.0
for layer in range(1, len(self.W)):
dW[layer] = np.clip(dW[layer], -clip_value, clip_value)
db[layer] = np.clip(db[layer], -clip_value, clip_value)
return dW, db
6. Verify the Loss Function and Its Gradient
Cause:
An incorrect implementation of the loss function or its gradient can lead to improper weight updates.
Solution:
Ensure that the loss function and its gradient are correctly implemented. For example, with Softmax and Categorical Cross-Entropy loss, the gradient should indeed be (a - y).
class CategoricalCrossEntropy:
@staticmethod
def function(y_true, y_pred):
# Adding epsilon for numerical stability
epsilon = 1e-15
y_pred = np.clip(y_pred, epsilon, 1 - epsilon)
return -np.sum(y_true * np.log(y_pred))
@staticmethod
def gradient(y_true, y_pred):
return y_pred - y_true
7. Monitor and Debug Intermediate Values
Cause:
Without visibility into intermediate computations, it's challenging to pinpoint where exactly the instability arises.
Solution:
Introduce debugging statements to monitor the range and distribution of activations and gradients.
Example:
def propagate_forward(self, x):
self.a[0] = x # Input layer activation
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
# Debugging statements
print(f"Layer {i} - z: {self.z[i]}")
print(f"Layer {i} - a: {self.a[i]}")
8. Complete Revised Code Example
Combining the above suggestions, here's a revised version of your neural network incorporating these fixes:
import numpy as np
# Softmax Activation Function
class Softmax:
@staticmethod
def function(z):
# Numerical stability
z -= np.max(z)
exp_z = np.exp(z)
return exp_z / np.sum(exp_z)
@staticmethod
def derivative(z):
softmax_val = Softmax.function(z)
jacobian = np.diag(softmax_val) - np.outer(softmax_val, softmax_val)
return jacobian
# Categorical Cross-Entropy Loss
class CategoricalCrossEntropy:
@staticmethod
def function(y_true, y_pred):
epsilon = 1e-15
y_pred = np.clip(y_pred, epsilon, 1 - epsilon)
return -np.sum(y_true * np.log(y_pred))
@staticmethod
def gradient(y_true, y_pred):
return y_pred - y_true
# Leaky ReLU Activation Function
class LeakyReLU:
@staticmethod
def function(z, alpha=0.01):
return np.where(z > 0, z, alpha * z)
@staticmethod
def derivative(z, alpha=0.01):
return np.where(z > 0, 1, alpha)
# Xavier Initialization
def xavier_init(size_in, size_out):
limit = np.sqrt(6 / (size_in + size_out))
return np.random.uniform(-limit, limit, (size_out, size_in))
# Dense Neural Network Class
class DenseNeuralNetwork:
def __init__(self, layer_sizes, activations, loss_f):
self.learning_rate = None
self.layer_sizes = layer_sizes
self.loss_f = loss_f
np.random.seed(42)
self.W = [None] + [xavier_init(layer_sizes[i-1], layer_sizes[i])
for i in range(1, len(layer_sizes))]
self.b = [None] + [np.zeros(layer_sizes[i]) for i in range(1, len(layer_sizes))]
self.a = [np.zeros(size) for size in layer_sizes] # Activations
self.z = [None] + [np.zeros(layer_sizes[i]) for i in range(1, len(layer_sizes))] # Net inputs
self.activation_f = activations # Activation functions for each layer
def propagate_forward(self, x):
self.a[0] = x # Input layer activation
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
# Debugging statements
print(f"Forward - Layer {i}: z = {self.z[i]}, a = {self.a[i]}")
def propagate_backward(self, y_true):
error_term = {}
dW = [None] + [np.zeros_like(w) for w in self.W[1:]] # Gradient accumulators for weights
db = [None] + [np.zeros_like(b) for b in self.b[1:]] # Gradient accumulators for biases
L = len(self.W) - 1 # Index of the last layer
# Compute error term for the output layer
if isinstance(self.activation_f[L], Softmax):
error_term[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
dW[L] = np.outer(error_term[L], self.a[L-1]) # Shape: (output_size, prev_layer_size)
db[L] = error_term[L] # Shape: (output_size,)
# Compute error and gradients for hidden layers
for i in reversed(range(1, L)):
if isinstance(self.activation_f[i], Softmax):
# Generally, Softmax is not used in hidden layers
print("Warning: Softmax activation found in hidden layers. This is uncommon.")
error = self.activation_f[i].derivative(self.z[i]) @ (self.W[i+1].T @ error_term[i+1])
else:
# For ReLU and others
error = self.activation_f[i].derivative(self.z[i]) * (self.W[i+1].T @ error_term[i+1])
error_term[i] = error # Shape: (layer_size,)
# Compute gradients for layer i
dW[i] = np.outer(error_term[i], self.a[i-1]) # Shape: (current_layer_size, prev_layer_size)
db[i] = error_term[i] # Shape: (current_layer_size,)
# Gradient clipping
clip_value = 1.0
for layer in range(1, len(self.W)):
dW[layer] = np.clip(dW[layer], -clip_value, clip_value)
db[layer] = np.clip(db[layer], -clip_value, clip_value)
return dW, db # Return gradients
def train(self, X_train, y_train, X_val, y_val, epochs=100, learning_rate=0.001, verbose=True):
training_losses, validation_losses, training_accuracies, validation_accuracies = [], [], [], []
self.learning_rate = learning_rate
for epoch in range(epochs):
# Initialize accumulators for gradients
dW_accum = [None] + [np.zeros_like(w) for w in self.W[1:]]
db_accum = [None] + [np.zeros_like(b) for b in self.b[1:]]
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
# Get gradients instead of updating weights
dW, db = self.propagate_backward(y_true)
# Accumulate gradients
for layer in range(1, len(self.W)):
dW_accum[layer] += dW[layer]
db_accum[layer] += db[layer]
# Average loss and accuracy
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)
# Update weights and biases using averaged gradients
for layer in range(1, len(self.W)):
self.W[layer] -= self.learning_rate * (dW_accum[layer] / X_train.shape[0])
self.b[layer] -= self.learning_rate * (db_accum[layer] / X_train.shape[0])
# 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
def is_correct_prediction(self, predicted, true):
if len(predicted) == 1:
# Binary classification
return ((predicted > 0.5).astype(int) == true).astype(int).sum()
else:
# Multiclass classification
return np.argmax(predicted) == np.argmax(true)
def predict(self, x):
self.propagate_forward(x)
y_pred = self.a[-1]
return y_pred
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
Summary of Recommendations
-
Reduce the Learning Rate: Start with a smaller learning rate (e.g., 0.001) to prevent large weight updates that can cause numerical instability.
-
Implement Better Weight Initialization: Use Xavier or He initialization to maintain a controlled flow of gradients through the network layers.
-
Normalize Input Data: Ensure that your input features are scaled appropriately to stabilize training.
-
Monitor Activation Values: Introduce debugging statements to monitor activations and gradients, ensuring they remain within reasonable ranges.
-
Use Gradient Clipping: Implement gradient clipping to prevent gradients from becoming excessively large during backpropagation.
-
Verify Loss Function Implementation: Ensure that both the loss function and its gradient are correctly implemented to facilitate proper learning.
By systematically applying these adjustments, you should observe improved stability in your network's training process, leading to more reliable and accurate performance.