import torch
import torch.nn.functional as F
# Define model
class MLP(torch.nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super(MLP, self).__init__()
self.fc1 = torch.nn.Linear(input_size, hidden_size)
self.fc2 = torch.nn.Linear(hidden_size, num_classes)
def forward(self, x):
# Flatten image input
x = x.view(-1, 28*28)
# Pass input through first fc layer
x = F.relu(self.fc1(x))
# Pass through second fc layer
x = self.fc2(x)
return x
# Define hyperparameters
input_size = 28*28
hidden_size = 100
num_classes = 10
# Initialize model
model = MLP(input_size, hidden_size, num_classes)
# Cross entropy loss and Adam optimizer
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
# Train model
for epoch in range(5):
for images, labels in train_loader:
# Clear gradients
optimizer.zero_grad()
# Forward pass
outputs = model(images)
# Calculate loss
loss = criterion(outputs, labels)
# Backward pass
loss.backward()
# Update weights
optimizer.step()
This defines a simple two layer MLP, initializes it, and trains it for 5 epochs on the MNIST dataset using cross entropy loss and the Adam optimizer. Let me know if you have any questions!