Answered step by step
Verified Expert Solution
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 and image shape for testx and trainx is A jupyter code that can read the training images and displays one of them is given in CODE
CODE is the CNN code I have so far but does not open the csv images. Please adjust CODE so that it is using and reading these files, either train x and test y or all of them. A code that works please. The goal is to obtain as good a CNN as I can get by: Adjusting the hyperparameters such as learning rate, number of training epochs, convolutional kernel size, stride, pooling strategy etc. Changing the number of feature maps Including an additional convolutional layer Adding an extra fully connected layer. First I need a working code for my images in order to do that.
CODE :
import numpy as np
import csv
import matplotlib.pyplot as plt
with opentrainxcsvr as csvfile:
csvreader csvreadercsvfile
for data in csvreader:
img nparraydata dtype'int
printimgshape
pixels img.reshape
printpixelsshape
pltimshowpixels cmap'gray'
pltshow
CODE :
import numpy as np
import torch
import torch.nn as nn
import torch.nnfunctional 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.MNISTrootData trainTrue, downloadTrue, transformT
train
test datasets.MNISTrootData trainFalse, downloadTrue, transformT
test
trainloader DataLoadertrain batchsize shuffleTrue
testloader DataLoadertest batchsize shuffleFalse
class CNNnnModule:
def initself:
superCNN selfinit
self.conv nnSequential
nnConvdinchannels outchannels
kernelsize stride padding
nnReLU
nnMaxPooldkernelsize
self.conv nnSequential
nnConvd
nnReLU
nnMaxPoold
self.out nnLinear
def forwardself x:
x self.convx
x self.convx
x xviewxsize # flatten conv output to batchsize
output self.outx
return output, x # return x for visualization
cnn CNN
printcnn
lossfn nnCrossEntropyLoss
lossfn
from torch import optim
optimizer optim.Adamcnnparameters lr
optimizer
from torch.autograd import Variable
numepochs
def trainmodelmodel numepochs, cnn loader:
model.train
totalstep lenloader
for epoch in rangenumepochs:
for iimages labels in enumerateloader:
bx Variableimages
by Variablelabels
output cnnbx
loss lossfnoutput by
optimizer.zerograd
loss.backward
optimizer.step
if i:
printEpoch Step Loss: :f
formatepoch numepochs, i totalstep, loss.item
trainmodelcnn numepochs, cnn trainloader
testcorrect
def evalmodelmodel dataloader:
model.eval
tstcorr
with torch.nograd:
for iimages labels in enumeratedataloader:
testoutput, lastlayer modelimages
predicted torch.maxtestoutput, data.squeeze
tstcorr predicted labelssum
testcorrect.appendtstcorr
evalmodelcnn testloader
printfTest accuracy: testcorrectitem:f
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started