Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Please design a suitable Convolutional Neural Network ( CNN ) to classify handwritten digits. The code needs to be able to be run in Jupyter.

Please design a suitable Convolutional Neural Network (CNN) to classify handwritten digits. The code needs to be able to be run in Jupyter. The images in this dataset are blurred in a way that is similar to that caused by camera shake. The training and test images as well as the Training and Test labels are provided as separate CSV formatted files trainx.csv, testx.csv, trainy.csv, and testy.csv. The shape of trainy and testy is (10,) and image shape for testx and trainx is (784,). A jupyter code that can read the training images and displays one of them is given in CODE 1.
CODE 2 is the CNN code I have so far but does not open the csv images. Please adjust CODE 2 so that it is using and reading these files, either train x and test y or all 4 of them. A code that works please. The goal is to obtain as good a CNN as I can get by: (1) Adjusting the hyperparameters such as learning rate, number of training epochs, convolutional kernel size, stride, pooling strategy etc. (2) Changing the number of feature maps (3) Including an additional convolutional layer (4) Adding an extra fully connected layer. First I need a working code for my images in order to do that.
CODE 1:
import numpy as np
import csv
import matplotlib.pyplot as plt
with open('./trainx.csv','r') as csv_file:
csvreader = csv.reader(csv_file)
for data in csvreader:
img = np.array(data, dtype='int64')
print(img.shape)
pixels = img.reshape((28,28))
print(pixels.shape)
plt.imshow(pixels, cmap='gray')
plt.show()
CODE 2:
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
import matplotlib.pyplot as plt
%matplotlib inline
T = transforms.ToTensor()
train = datasets.MNIST(root="./Data", train=True, download=True, transform=T)
train
test = datasets.MNIST(root="./Data", train=False, download=True, transform=T)
test
train_loader = DataLoader(train, batch_size=100, shuffle=True)
test_loader = DataLoader(test, batch_size=500, shuffle=False)
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1= nn.Sequential(
nn.Conv2d(in_channels=1, out_channels=16,
kernel_size=5, stride=1, padding=2,),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2),)
self.conv2= nn.Sequential(
nn.Conv2d(16,32,5,1,2),
nn.ReLU(),
nn.MaxPool2d(2),)
self.out = nn.Linear(32*7*7,10)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = x.view(x.size(0),-1) # flatten conv2 output to (batch_size 32*7*7)
output = self.out(x)
return output, x # return x for visualization
cnn = CNN()
print(cnn)
loss_fn = nn.CrossEntropyLoss()
loss_fn
from torch import optim
optimizer = optim.Adam(cnn.parameters(), lr=0.001)
optimizer
from torch.autograd import Variable
num_epochs =4
def train_model(model, num_epochs, cnn, loader):
model.train()
total_step = len(loader)
for epoch in range(num_epochs):
for i,(images, labels) in enumerate(loader):
b_x = Variable(images)
b_y = Variable(labels)
output = cnn(b_x)[0]
loss = loss_fn(output, b_y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (i+1)%100==0:
print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
.format(epoch+1, num_epochs, i+1, total_step, loss.item()))
train_model(cnn, num_epochs, cnn, train_loader)
test_correct =[]
def eval_model(model, dataloader):
model.eval()
tst_corr =0
with torch.no_grad():
for i,(images, labels) in enumerate(dataloader):
test_output, last_layer = model(images)
predicted = torch.max(test_output, 1)[1].data.squeeze()
tst_corr +=(predicted == labels).sum()
test_correct.append(tst_corr)
eval_model(cnn, test_loader)
print(f'Test accuracy: {test_correct[-1].item()*100/10000:.3f}%')

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Relational Database Design A Practical Approach

Authors: Marilyn Campbell

1st Edition

1587193175, 978-1587193170

More Books