Below is an implementation of a simple Multi-Layer Perceptron (MLP) model using only NumPy for the neural network computations. The CIFAR-10 dataset is loaded using PyTorch's torchvision.datasets and torch.utils.data.DataLoader for convenience. The model is trained on the CIFAR-10 dataset.
import numpy as np
import torch
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
# Set random seed for reproducibility
np.random.seed(42)
# Define the MLP model using NumPy
class MLP:
def __init__(self, input_size, hidden_size, output_size):
# Initialize weights and biases
self.weights1 = np.random.randn(input_size, hidden_size) * 0.01
self.bias1 = np.zeros((1, hidden_size))
self.weights2 = np.random.randn(hidden_size, output_size) * 0.01
self.bias2 = np.zeros((1, output_size))
def relu(self, x):
return np.maximum(0, x)
def relu_derivative(self, x):
return (x > 0).astype(float)
def softmax(self, x):
exp_x = np.exp(x - np.max(x, axis=1, keepdims=True))
return exp_x / np.sum(exp_x, axis=1, keepdims=True)
def forward(self, x):
# Forward pass
self.z1 = np.dot(x, self.weights1) + self.bias1
self.a1 = self.relu(self.z1)
self.z2 = np.dot(self.a1, self.weights2) + self.bias2
self.a2 = self.softmax(self.z2)
return self.a2
def backward(self, x, y, output, learning_rate):
# Backward pass
m = y.shape[0]
y_one_hot = np.zeros_like(output)
y_one_hot[np.arange(m), y] = 1
dz2 = output - y_one_hot
dw2 = np.dot(self.a1.T, dz2) / m
db2 = np.sum(dz2, axis=0, keepdims=True) / m
da1 = np.dot(dz2, self.weights2.T)
dz1 = da1 * self.relu_derivative(self.z1)
dw1 = np.dot(x.T, dz1) / m
db1 = np.sum(dz1, axis=0, keepdims=True) / m
# Update weights and biases
self.weights1 -= learning_rate * dw1
self.bias1 -= learning_rate * db1
self.weights2 -= learning_rate * dw2
self.bias2 -= learning_rate * db2
def compute_loss(self, output, y):
m = y.shape[0]
y_one_hot = np.zeros_like(output)
y_one_hot[np.arange(m), y] = 1
loss = -np.sum(y_one_hot * np.log(output + 1e-8)) / m
return loss
# Load CIFAR-10 dataset using PyTorch
def load_cifar10(batch_size=64):
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])
train_dataset = datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
test_dataset = datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
return train_loader, test_loader
# Train the MLP model
def train_mlp():
# Hyperparameters
input_size = 32 * 32 * 3 # CIFAR-10 images are 32x32x3
hidden_size = 128
output_size = 10 # CIFAR-10 has 10 classes
learning_rate = 0.01
epochs = 10
batch_size = 64
# Load data
train_loader, test_loader = load_cifar10(batch_size)
# Initialize model
model = MLP(input_size, hidden_size, output_size)
# Training loop
for epoch in range(epochs):
total_loss = 0
for batch_idx, (images, labels) in enumerate(train_loader):
# Flatten images and convert to NumPy
images = images.view(images.size(0), -1).numpy()
labels = labels.numpy()
# Forward pass
outputs = model.forward(images)
# Compute loss
loss = model.compute_loss(outputs, labels)
total_loss += loss
# Backward pass and update weights
model.backward(images, labels, outputs, learning_rate)
print(f"Epoch {epoch + 1}/{epochs}, Loss: {total_loss / len(train_loader)}")
# Run the training
if __name__ == "__main__":
train_mlp()
Explanation:
-
MLP Class:
- Implements a simple 2-layer MLP with ReLU activation for the hidden layer and softmax for the output layer.
- Includes forward propagation, backward propagation, and weight updates using gradient descent.
-
CIFAR-10 Dataset:
- The dataset is loaded using PyTorch's
torchvision.datasets and normalized to have values between -1 and 1.
- Images are flattened into vectors of size
32 * 32 * 3 before being passed to the MLP.
-
Training Loop:
- For each epoch, the model processes batches of data, computes the loss, and updates the weights using backpropagation.
-
Loss Function:
- Cross-entropy loss is implemented manually using NumPy.
Notes:
- This implementation is for educational purposes and is not optimized for performance.
- Training on CIFAR-10 with this simple MLP may not yield high accuracy due to the lack of advanced techniques like convolutional layers, regularization, or data augmentation.
- Ensure you have the required PyTorch libraries installed to load the dataset.