I'm solving a simplified logical regression problem, that only uses weights w1 and w2 and no bias term. The data used here is generated synthetically to nicely fit into such model. (Not having a bias terms, reduces the parameters to update during training to w1 and w2, making it possible for me to visualise the entire gradient descent process with only 3 dimension axes later on).
Issue: doubtful about Adam optimiser’s behaviour
I am highly doubtful that my implementation is correctly reflecting behaviour of the Adam optimiser. It is taking very tiny steps, and when setting learning rate 0.02 it takes around 130 epochs to converge (it will stay at low accuracy near 20%, until around 123th epoch, then make big jumps in the coming three epochs to reach near 80% accuracy).
To my knowledge Adam optimiser is generally set to lower learning rates like 0.001, and there onwards it automatically adjusts the learning rate to more reasonable rate. But if I were to set my learning rate to 0.001, I’d need around 2536 epochs, just for a simple logistic regression problem with only two weights.
I feel like if Adam was correctly implemented here, it would have simply adjusted the learning rate during the training to converge much faster.
Code
Gradient Descent Class
python
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
class GradientDescent:
def __init__(self, optimizer=None):
self.weights = None
self.learning_rate = None
self.optimizer = optimizer
def fit(self, X_train, y_train, X_val, y_val, epochs=100, initial_weights=None, learning_rate=0.002, batch_size=32, verbose=True):
self.learning_rate = learning_rate
# Initialize lists to store metrics for each epoch
train_losses, train_accuracies, val_losses, val_accuracies, weight_history = [], [], [], [], []
for epoch in range(epochs):
if epoch == 0:
np.random.seed(42)
self.weights = np.array(initial_weights) if initial_weights else np.random.uniform(-1, 1, num_features)
else:
for i in range(0, X_train.shape[0], batch_size):
X_batch = X_train[i:i + batch_size]
y_true_batch = y_train[i:i + batch_size]
# Compute linear combination and apply sigmoid
linear_combination = np.dot(X_batch, self.weights)
y_pred_batch = 1 / (1 + np.exp(-linear_combination))
# Compute gradient of binary-crossentropy loss w.r.t weights
grad_loss = np.dot(X_batch.T, (y_pred_batch - y_true_batch)) / X_batch.shape[0]
# Apply optimizer
if self.optimizer:
grad_loss = self.optimizer.update(grad_loss)
# Update weights
self.weights -= self.learning_rate * grad_loss
# Training evaluation after the epoch
train_loss, train_accuracy = self.evaluate(X_train, y_train)
val_loss, val_accuracy = self.evaluate(X_val, y_val)
# Store metrics & display the metrics for the current epoch
weight_history.append(self.weights.copy()); train_losses.append(train_loss); train_accuracies.append(train_accuracy); val_losses.append(val_loss); val_accuracies.append(val_accuracy)
if verbose:
print(f"Epoch {epoch + 1}:\nWeights: {self.weights}\nTrain Loss: {train_loss:.8f}, Train Accuracy: {train_accuracy:.4f}\nValidation Loss: {val_loss:.8f}, Validation Accuracy: {val_accuracy:.4f}\n")
return train_losses, train_accuracies, val_losses, val_accuracies, weight_history
def evaluate(self, X, y_true):
linear_combination = np.dot(X, self.weights)
y_pred = 1 / (1 + np.exp(-linear_combination))
loss = -np.mean(y_true * np.log(y_pred + 1e-8) + (1 - y_true) * np.log(1 - y_pred + 1e-8)) # Cross-entropy loss
accuracy = np.mean((y_pred >= 0.5) == y_true)
return loss, accuracy
Adam Optimizer class
python
class Adam:
def __init__(self, beta1=0.9, beta2=0.999, epsilon=1e-7):
self.beta1 = beta1
self.beta2 = beta2
self.epsilon = epsilon
self.m_t = None # First moment estimate (momentum)
self.v_t = None # Second moment estimate (RMSProp-like)
self.t = 0 # Timestep for bias correction
def update(self, gradient):
if self.m_t is None:
self.m_t = np.zeros_like(gradient)
if self.v_t is None:
self.v_t = np.zeros_like(gradient)
self.t += 1
# Update biased first and second moment estimates
self.m_t = self.beta1 * self.m_t + (1 - self.beta1) * gradient
self.v_t = self.beta2 * self.v_t + (1 - self.beta2) * (gradient ** 2)
# Bias-corrected moment estimates
m_hat = self.m_t / (1 - self.beta1 ** self.t)
v_hat = self.v_t / (1 - self.beta2 ** self.t)
# Update weights
adjusted_gradient = m_hat / (np.sqrt(v_hat) + self.epsilon)
return adjusted_gradient
Performing Gradient Descent
python
# Generate Synthetic data
np.random.seed(42)
true_weights = np.array([-3, 3.5])
X = np.random.rand(500, len(true_weights)) * 10
y = (1 / (1 + np.exp(-np.dot(X, true_weights))) > 0.5).astype(int)
y[np.random.choice(500, int(0.1 * 500), replace=False)] ^= 1
# Split the data into training (60%), validation (20%), and test (20%) sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=42)
X_val, X_test, y_val, y_test = train_test_split(X_test, y_test, test_size=0.5, random_state=42)
# Training
gd = GradientDescent(optimizer=Adam())
# slowly converges at around 90th epoch
metrics = gd.fit(X_train, y_train, X_val, y_val, epochs=100, batch_size=32, initial_weights=[15.0, -20.0], learning_rate=0.03)
# slowly converges at around 130th epoch
metrics = gd.fit(X_train, y_train, X_val, y_val, epochs=500, batch_size=32, initial_weights=[15.0, -20.0], learning_rate=0.02)
# slowly converges at around 2536th epoch
metrics = gd.fit(X_train, y_train, X_val, y_val, epochs=5000, batch_size=32, initial_weights=[15.0, -20.0], learning_rate=0.001)
I’d be very very thankful if you could fix any problem in here, so that fixing it can make it such that Adam Optimizer here will work fine at lower learning rates (e.g. 0.002, 0.001…)?
Thank you for providing a detailed description of your implementation and the issues you're encountering with the Adam optimizer. Based on your description and the provided code, it appears there are a few areas that could be causing the unexpected behavior of the Adam optimizer. Let's go through these step-by-step and provide solutions to help you achieve the desired convergence behavior.
1. Initialization of Weights
Issue:
You're initializing the weights with large values (initial_weights=[15.0, -20.0]). Starting with large initial weights can cause the sigmoid activation to saturate, leading to very small gradients. This can significantly slow down the training process, especially when using optimizers like Adam, which rely on gradient information to adjust learning rates dynamically.
Solution:
Initialize the weights with smaller values, preferably close to zero. This prevents the sigmoid function from saturating and allows for more meaningful gradient updates from the beginning of training.
Implementation:
python
# Example of initializing with small random values
gd.fit(
X_train, y_train, X_val, y_val,
epochs=100,
batch_size=32,
initial_weights=[0.0, 0.0], # Start close to zero
learning_rate=0.001 # Start with a standard Adam learning rate
)
2. Handling the Learning Rate in the Adam Optimizer
Issue:
In your current implementation, the learning rate is managed externally within the GradientDescent class and then multiplied by the adjusted gradient returned by the Adam optimizer. While this approach is valid, it might lead to confusion, especially if the learning rate interacts unexpectedly with the adaptive learning rate adjustments that Adam performs internally.
Solution:
Integrate the learning rate directly into the Adam optimizer. This approach aligns more closely with standard implementations and ensures that the learning rate is consistently applied as intended.
Implementation:
Modify the Adam class to accept and use the learning rate directly:
python
class Adam:
def __init__(self, learning_rate=0.001, beta1=0.9, beta2=0.999, epsilon=1e-7):
self.alpha = learning_rate
self.beta1 = beta1
self.beta2 = beta2
self.epsilon = epsilon
self.m_t = None # First moment estimate (momentum)
self.v_t = None # Second moment estimate (RMSProp-like)
self.t = 0 # Timestep for bias correction
def update(self, gradient):
if self.m_t is None:
self.m_t = np.zeros_like(gradient)
if self.v_t is None:
self.v_t = np.zeros_like(gradient)
self.t += 1
# Update biased first and second moment estimates
self.m_t = self.beta1 * self.m_t + (1 - self.beta1) * gradient
self.v_t = self.beta2 * self.v_t + (1 - self.beta2) * (gradient ** 2)
# Bias-corrected moment estimates
m_hat = self.m_t / (1 - self.beta1 ** self.t)
v_hat = self.v_t / (1 - self.beta2 ** self.t)
# Compute the parameter update
adjusted_gradient = self.alpha * m_hat / (np.sqrt(v_hat) + self.epsilon)
return adjusted_gradient
Then, update the GradientDescent class to use the adjusted gradient without an external learning rate:
python
class GradientDescent:
def __init__(self, optimizer=None):
self.weights = None
self.optimizer = optimizer
def fit(self, X_train, y_train, X_val, y_val, epochs=100, initial_weights=None, batch_size=32, verbose=True):
# Initialize weights before starting epochs
np.random.seed(42)
self.weights = np.array(initial_weights) if initial_weights else np.random.uniform(-0.1, 0.1, X_train.shape[1])
# Initialize lists to store metrics for each epoch
train_losses, train_accuracies, val_losses, val_accuracies, weight_history = [], [], [], [], []
for epoch in range(epochs):
for i in range(0, X_train.shape[0], batch_size):
X_batch = X_train[i:i + batch_size]
y_true_batch = y_train[i:i + batch_size]
# Compute linear combination and apply sigmoid
linear_combination = np.dot(X_batch, self.weights)
y_pred_batch = 1 / (1 + np.exp(-linear_combination))
# Compute gradient of binary-crossentropy loss w.r.t weights
grad_loss = np.dot(X_batch.T, (y_pred_batch - y_true_batch)) / X_batch.shape[0]
# Apply optimizer
if self.optimizer:
grad_loss = self.optimizer.update(grad_loss)
# Update weights
self.weights -= grad_loss
# Training evaluation after the epoch
train_loss, train_accuracy = self.evaluate(X_train, y_train)
val_loss, val_accuracy = self.evaluate(X_val, y_val)
# Store metrics & display the metrics for the current epoch
weight_history.append(self.weights.copy())
train_losses.append(train_loss)
train_accuracies.append(train_accuracy)
val_losses.append(val_loss)
val_accuracies.append(val_accuracy)
if verbose:
print(f"Epoch {epoch + 1}:\nWeights: {self.weights}\nTrain Loss: {train_loss:.8f}, Train Accuracy: {train_accuracy:.4f}\nValidation Loss: {val_loss:.8f}, Validation Accuracy: {val_accuracy:.4f}\n")
return train_losses, train_accuracies, val_losses, val_accuracies, weight_history
Key Changes:
Learning Rate Integration: The learning rate (alpha) is now part of the Adam optimizer. This ensures that gradient adjustments are consistent with standard Adam implementations.
Weight Initialization: Moved weight initialization outside the epoch loop to ensure that weights are initialized only once. Initialized with small random values to prevent sigmoid saturation.
Weight Update: Removed the external learning_rate multiplication, as it's now handled within the Adam optimizer.
3. Weight Initialization Location
Issue:
In your original fit method, you initialize the weights inside the epoch loop when epoch == 0. This approach can lead to unwanted behavior, especially if the number of epochs is large or if there's any interaction between weight initialization and weight updates.
Solution:
Initialize the weights before entering the epoch loop. This ensures that weights are set once and then updated consistently across all epochs.
Implementation:
As shown in the updated GradientDescent class above, initialize the weights outside the epoch loop:
python
# Initialize weights before starting epochs
np.random.seed(42)
self.weights = np.array(initial_weights) if initial_weights else np.random.uniform(-0.1, 0.1, X_train.shape[1])
4. Putting It All Together
Updated Code Snippets
Here are the updated classes incorporating all the suggested changes:
python
Training with Updated Configuration
python
# Generate Synthetic data
np.random.seed(42)
true_weights = np.array([-3, 3.5])
X = np.random.rand(500, len(true_weights)) * 10
y = (1 / (1 + np.exp(-np.dot(X, true_weights))) > 0.5).astype(int)
y[np.random.choice(500, int(0.1 * 500), replace=False)] ^= 1
# Split the data into training (60%), validation (20%), and test (20%) sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=42)
X_val, X_test, y_val, y_test = train_test_split(X_test, y_test, test_size=0.5, random_state=42)
# Training with Adam Optimizer
adam_optimizer = Adam(learning_rate=0.001)
gd = GradientDescent(optimizer=adam_optimizer)
# Converges much faster with integrated learning rate and proper initialization
metrics = gd.fit(
X_train, y_train, X_val, y_val,
epochs=500, # Adjust as needed
batch_size=32,
initial_weights=[0.0, 0.0], # Small initial weights
verbose=True
)
5. Additional Recommendations
Learning Rate Tuning: While Adam is robust to different learning rates, starting with the standard 0.001 is advisable. You can experiment with values like 0.0005 or 0.002 to see how they affect convergence speed and stability.
Weight Initialization Range: The range [-0.1, 0.1] for initializing weights is a common choice. However, depending on your specific problem, you might need to adjust this range slightly.
Monitoring Gradient Norms: To ensure that gradients aren't vanishing or exploding, you can monitor their norms during training. This can provide insights into whether the optimizer is functioning correctly.
Using Established Libraries: For debugging purposes, consider implementing a small version of your problem using established libraries like TensorFlow or PyTorch. Comparing the behavior can help identify discrepancies in your custom implementation.
Bias Term: Although you've intentionally excluded the bias term for visualization purposes, ensure that the lack of a bias isn't inadvertently affecting the model's capacity to fit the data. Sometimes, adding a bias (even temporarily) can stabilize training.
6. Conclusion
By initializing the weights with smaller values and integrating the learning rate directly into the Adam optimizer, you should observe more stable and faster convergence. These changes align your implementation more closely with standard practices, leveraging Adam's strengths in adaptive learning rate adjustments. Additionally, always ensure that the initial conditions (like weight initialization) are conducive to effective training.
Feel free to reach out if you encounter further issues or have additional questions!
Not yet included in a published release.
import numpy as np
from sklearn.model_selection import train_test_split
class Adam:
def __init__(self, learning_rate=0.001, beta1=0.9, beta2=0.999, epsilon=1e-7):
self.alpha = learning_rate
self.beta1 = beta1
self.beta2 = beta2
self.epsilon = epsilon
self.m_t = None # First moment estimate (momentum)
self.v_t = None # Second moment estimate (RMSProp-like)
self.t = 0 # Timestep for bias correction
def update(self, gradient):
if self.m_t is None:
self.m_t = np.zeros_like(gradient)
if self.v_t is None:
self.v_t = np.zeros_like(gradient)
self.t += 1
# Update biased first and second moment estimates
self.m_t = self.beta1 * self.m_t + (1 - self.beta1) * gradient
self.v_t = self.beta2 * self.v_t + (1 - self.beta2) * (gradient ** 2)
# Bias-corrected moment estimates
m_hat = self.m_t / (1 - self.beta1 ** self.t)
v_hat = self.v_t / (1 - self.beta2 ** self.t)
# Compute the parameter update
adjusted_gradient = self.alpha * m_hat / (np.sqrt(v_hat) + self.epsilon)
return adjusted_gradient
class GradientDescent:
def __init__(self, optimizer=None):
self.weights = None
self.optimizer = optimizer
def fit(self, X_train, y_train, X_val, y_val, epochs=100, initial_weights=None, batch_size=32, verbose=True):
# Initialize weights before starting epochs
np.random.seed(42)
self.weights = np.array(initial_weights) if initial_weights else np.random.uniform(-0.1, 0.1, X_train.shape[1])
# Initialize lists to store metrics for each epoch
train_losses, train_accuracies, val_losses, val_accuracies, weight_history = [], [], [], [], []
for epoch in range(epochs):
for i in range(0, X_train.shape[0], batch_size):
X_batch = X_train[i:i + batch_size]
y_true_batch = y_train[i:i + batch_size]
# Compute linear combination and apply sigmoid
linear_combination = np.dot(X_batch, self.weights)
y_pred_batch = 1 / (1 + np.exp(-linear_combination))
# Compute gradient of binary-crossentropy loss w.r.t weights
grad_loss = np.dot(X_batch.T, (y_pred_batch - y_true_batch)) / X_batch.shape[0]
# Apply optimizer
if self.optimizer:
grad_loss = self.optimizer.update(grad_loss)
# Update weights
self.weights -= grad_loss
# Training evaluation after the epoch
train_loss, train_accuracy = self.evaluate(X_train, y_train)
val_loss, val_accuracy = self.evaluate(X_val, y_val)
# Store metrics & display the metrics for the current epoch
weight_history.append(self.weights.copy())
train_losses.append(train_loss)
train_accuracies.append(train_accuracy)
val_losses.append(val_loss)
val_accuracies.append(val_accuracy)
if verbose:
print(f"Epoch {epoch + 1}:\nWeights: {self.weights}\nTrain Loss: {train_loss:.8f}, Train Accuracy: {train_accuracy:.4f}\nValidation Loss: {val_loss:.8f}, Validation Accuracy: {val_accuracy:.4f}\n")
return train_losses, train_accuracies, val_losses, val_accuracies, weight_history
def evaluate(self, X, y_true):
linear_combination = np.dot(X, self.weights)
y_pred = 1 / (1 + np.exp(-linear_combination))
loss = -np.mean(y_true * np.log(y_pred + 1e-8) + (1 - y_true) * np.log(1 - y_pred + 1e-8)) # Cross-entropy loss
accuracy = np.mean((y_pred >= 0.5) == y_true)
return loss, accuracy