I want you to act as a machine learning engineer. I am working on an intro to deep learning assignment. Write me the pseudo code to build a two layer Neural Network using numpy. the details are as follows. The first layer (contains 128 nodes), a sigmoid activation function, second layer (contains 10 nodes), a softmax function, then cross entropy loss. Assume I have a functions prebuilt for softmax, sigmoid, and cross entropy loss
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Below is the pseudo code for building a two-layer Neural Network using NumPy, as per your specifications. This example assumes you have the following pre-built functions:
sigmoid(x): Applies the sigmoid activation function to x.
softmax(x): Applies the softmax activation function to x.
cross_entropy_loss(y_pred, y_true): Calculates the cross-entropy loss between predicted y_pred and actual labels y_true.
plaintext
# Pseudo Code: Two-Layer Neural Network with NumPy
### Import Necessary Libraries ###
import numpy as np
### Assuming these functions are pre-built and imported ###
# from your_utils import sigmoid, softmax, cross_entropy_loss
### Neural Network Class ###
class TwoLayerNN:
def __init__(self, input_dim, hidden_dim, output_dim):
"""
Initialize the neural network.
Parameters:
- input_dim (int): Number of features in the input data.
- hidden_dim (int): Number of nodes in the hidden layer (128 for this task).
- output_dim (int): Number of nodes in the output layer (10 for this task).
"""
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.output_dim = output_dim
# Initialize weights randomly (Xavier initialization for simplicity here)
self.weights1 = np.random.randn(input_dim, hidden_dim) * np.sqrt(1 / input_dim)
self.weights2 = np.random.randn(hidden_dim, output_dim) * np.sqrt(1 / hidden_dim)
# Initialize biases to zero
self.bias1 = np.zeros((1, hidden_dim))
self.bias2 = np.zeros((1, output_dim))
def forward(self, X):
"""
Forward pass of the neural network.
Parameters:
- X (numpy array): Input data of shape (batch_size, input_dim).
Returns:
- y_pred (numpy array): Predicted output of shape (batch_size, output_dim).
"""
# First Layer (Linear + Sigmoid)
hidden_layer = np.dot(X, self.weights1) + self.bias1 # Compute hidden layer activations
activated_hidden = sigmoid(hidden_layer) # Apply sigmoid activation
# Second Layer (Linear + Softmax)
output_layer = np.dot(activated_hidden, self.weights2) + self.bias2 # Compute output layer activations
y_pred = softmax(output_layer) # Apply softmax activation for multi-class classification
return y_pred
def calculate_loss(self, X, y_true):
"""
Calculate the cross-entropy loss.
Parameters:
- X (numpy array): Input data of shape (batch_size, input_dim).
- y_true (numpy array): True labels of shape (batch_size, output_dim).
Returns:
- loss (float): Cross-entropy loss value.
"""
y_pred = self.forward(X) # Get predictions
loss = cross_entropy_loss(y_pred, y_true) # Calculate loss using pre-built function
return loss
def train(self, X, y_true, learning_rate, epochs):
"""
Simple training loop (for demonstration; real-world scenarios might use more sophisticated methods).
Parameters:
- X (numpy array): Input data of shape (batch_size, input_dim).
- y_true (numpy array): True labels of shape (batch_size, output_dim).
- learning_rate (float): Learning rate for gradient descent.
- epochs (int): Number of training epochs.
"""
batch_size = X.shape[0]
for epoch in range(epochs):
# Forward Pass
hidden_layer = np.dot(X, self.weights1) + self.bias1 # Linear transformation for hidden layer
activated_hidden = sigmoid(hidden_layer) # Apply sigmoid activation
output_layer = np.dot(activated_hidden, self.weights2) + self.bias2 # Linear transformation for output layer
y_pred = softmax(output_layer) # Apply softmax activation
# Calculate Loss
loss = cross_entropy_loss(y_pred, y_true) # Compute cross-entropy loss
print(f"Epoch {epoch+1}, Loss: {loss}") # Print loss at each epoch
# Backward Pass
# Output Layer Gradients
d_output = y_pred - y_true # Gradient of loss w.r.t output layer (simplified for softmax + cross-entropy)
# Hidden Layer Gradients
d_hidden = d_output.dot(self.weights2.T) * activated_hidden * (1 - activated_hidden) # Chain rule for hidden layer gradient
# Weight Updates
self.weights2 -= learning_rate * (activated_hidden.T.dot(d_output) / batch_size) # Update weights2 using gradient descent
self.bias2 -= learning_rate * np.sum(d_output, axis=0, keepdims=True) / batch_size # Update bias2
self.weights1 -= learning_rate * (X.T.dot(d_hidden) / batch_size) # Update weights1
self.bias1 -= learning_rate * np.sum(d_hidden, axis=0, keepdims=True) / batch_size # Update bias1
### Example Usage ###
if __name__ == "__main__":
# Example dimensions
input_dim = 784 # For MNIST dataset (28x28 images)
hidden_dim = 128 # Number of neurons in the hidden layer
output_dim = 10 # Number of classes in the output layer (e.g., digits 0-9)
# Initialize the network
nn = TwoLayerNN(input_dim, hidden_dim, output_dim)
# Dummy data for demonstration
X_dummy = np.random.rand(100, input_dim) # 100 samples of 784 features each
y_true_dummy = np.zeros((100, output_dim)) # Dummy one-hot labels for 10 classes
y_true_dummy[np.arange(100), np.random.randint(0, output_dim, 100)] = 1 # Randomly set one-hot labels
# Train the network
nn.train(X_dummy, y_true_dummy, learning_rate=0.01, epochs=10)
Note:
This pseudo code provides a simplified version of a two-layer neural network for educational purposes. Real-world applications might require more sophisticated techniques for initialization, regularization, optimization, and training.
The backward pass (weight updates) in the train method is simplified. In practice, you might want to compute gradients more precisely, possibly using a library that supports automatic differentiation to ensure accuracy.
Error handling and input validation are omitted for brevity.