0% found this document useful (0 votes)
3 views

assignment no 13

The document provides a Python script for training a simple convolutional neural network (CNN) using the PyTorch library on the MNIST dataset. It includes data loading, model definition, training loop, and evaluation for accuracy. The model consists of a convolutional layer followed by a max pooling layer and a fully connected layer.

Uploaded by

sumitdorle91
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

assignment no 13

The document provides a Python script for training a simple convolutional neural network (CNN) using the PyTorch library on the MNIST dataset. It includes data loading, model definition, training loop, and evaluation for accuracy. The model consists of a convolutional layer followed by a max pooling layer and a fully connected layer.

Uploaded by

sumitdorle91
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

!pip install torch torchvision --index-url https://download.pytorch.

org/whl/cpu

import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader

transform = transforms.ToTensor()

train_loader = DataLoader(datasets.MNIST('./data', train=True, download=True,


transform=transform), batch_size=32, shuffle=True)
test_loader = DataLoader(datasets.MNIST('./data', train=False, download=True,
transform=transform), batch_size=32)

class SimpleCNN(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 8, 3) # 8 filters, 3x3 kernel
self.pool = nn.MaxPool2d(2, 2)
self.fc1 = nn.Linear(8 * 13 * 13, 10)

def forward(self, x):


x = self.pool(torch.relu(self.conv1(x))) # Conv + ReLU + Pool
x = x.view(-1, 8 * 13 * 13) # Flatten
return self.fc1(x) # Fully connected

model = SimpleCNN()
loss_fn = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)

for epoch in range(3):


​ for images, labels in train_loader:
​ preds = model(images)
​ loss = loss_fn(preds, labels)
​ optimizer.zero_grad()
​ loss.backward()
​ optimizer.step()
print(f"Epoch {epoch+1} done")

correct, total = 0, 0
with torch.no_grad():
​ for images, labels in test_loader:
​ preds = model(images)
​ correct += (preds.argmax(1) == labels).sum().item()
​ total += labels.size(0)

print(f"Accuracy: {100 * correct / total:.2f}%")

transform = transforms.ToTensor()

train_loader = DataLoader(datasets.MNIST('./data', train=True,


download=True, transform=transform), batch_size=32, shuffle=True)
test_loader = DataLoader(datasets.MNIST('./data', train=False,
download=True, transform=transform), batch_size=32)

You might also like