Week 7 - Mnist-Mlp
Week 7 - Mnist-Mlp
/Users/sourangshu/miniconda3/envs/dl/lib/python3.11/site-
packages/torchvision/io/image.py:13: UserWarning: Failed to load image Python
extension: 'dlopen(/Users/sourangshu/miniconda3/envs/dl/lib/python3.11/site-
packages/torchvision/image.so, 0x0006): Symbol not found:
__ZN3c1017RegisterOperatorsD1Ev
Referenced from: <CFED5F8E-EC3F-36FD-AAA3-2C6C7F8D3DD9>
/Users/sourangshu/miniconda3/envs/dl/lib/python3.11/site-
packages/torchvision/image.so
Expected in: <CDAC6E34-8608-3E70-8B2F-32BCD38E90FB>
/Users/sourangshu/miniconda3/envs/dl/lib/python3.11/site-
packages/torch/lib/libtorch_cpu.dylib'If you don't plan on using image
functionality from `torchvision.io`, you can ignore this warning. Otherwise,
there might be something wrong with your environment. Did you have `libjpeg` or
`libpng` installed before building `torchvision` from source?
warn(
[2]: # Hyperparameters
input_size = 784 # 28x28 images flattened
hidden_size = 128
num_classes = 10
num_epochs = 5
batch_size = 100
learning_rate = 0.001
# MNIST dataset
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,)) # Normalizing the dataset
])
1
[3]: train_dataset = torchvision.datasets.MNIST(root='./data', train=True,␣
↪transform=transform, download=True)
MLP(
(fc1): Linear(in_features=784, out_features=128, bias=True)
(relu): ReLU()
(fc2): Linear(in_features=128, out_features=10, bias=True)
)
2
loss.backward()
optimizer.step()
if (i+1) % 100 == 0:
print(f'Epoch [{epoch+1}/{num_epochs}], Step [{i+1}/
↪{len(train_loader)}], Loss: {loss.item():.4f}')
3
correct += (predicted == labels).sum().item()
# Function to display a row of images with their predicted and true labels
def show_images(images, labels, preds, title):
fig, axes = plt.subplots(1, 10, figsize=(20, 2)) # Create a row of 10␣
↪subplots
for i in range(10):
axes[i].imshow(images[i].squeeze(), cmap='gray')
axes[i].set_title(f'True: {labels[i]}\nPred: {preds[i]}')
axes[i].axis('off') # Hide axis
fig.suptitle(title, fontsize=16)
plt.show()
with torch.no_grad():
for images, labels in test_loader:
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
4
# Prepare data for visualization
correct_images = [img for img, _, _ in correct_examples]
correct_labels = [label for _, label, _ in correct_examples]
correct_preds = [pred for _, _, pred in correct_examples]
5
all_preds = []
with torch.no_grad():
for images, labels in test_loader:
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
all_labels.extend(labels.cpu().numpy())
all_preds.extend(predicted.cpu().numpy())
plt.xlabel('Predicted Labels')
plt.ylabel('True Labels')
plt.title('Confusion Matrix for MNIST Classification')
plt.show()
6
[ ]: