Answered step by step
Verified Expert Solution
Question
1 Approved Answer
I use this model: # Load the datasets train _ data = datasets.MNIST ( root = 'data', train = True, transform = transforms.Compose ( [
I use this model: # Load the datasets
traindata datasets.MNIST
root 'data',
train True,
transform transforms.ComposetransformsToTensor
download True
testdata datasets.MNIST
root 'data',
train False,
transform transforms.ComposetransformsToTensor
download True trainloader torch.utils.data.DataLoadertraindata,
batchsize
numworkers
testloader torch.utils.data.DataLoadertestdata,
batchsize
numworkers
class CNNnnModule:
def initself:
superCNN selfinit
self.conv nnSequential
nnConvd
inchannels
outchannels
kernelsize
stride
padding
nnReLU
nnMaxPooldkernelsize
self.conv nnSequential
nnConvd
nnReLU
nnMaxPoold
self.out nnLinear
def forwardself x:
x self.convx
x self.convx
# flatten the output of conv to batchsize,
x xviewxsize
output self.outx
return output # Instantiate the model, define the loss function and the optimizer
cnn CNN
lossfunc nnCrossEntropyLoss
optimizer torch.optim.Adamcnnparameters lr # Training the model
numepochs
# Make sure cnn is in training mode
cnntrain
# Setting up the empty errors array
errors
# How many batches are there in our training set?
totalstep lentrainloader
for epoch in rangenumepochs:
for iimages labels in enumeratetrainloader:
output cnnimages # Forward pass: Compute predicted y by passing x to the model
currerror lossfuncoutput labels # Compute loss
errors.appendcurrerror.item # Append the current error to the errors list
optimizer.zerograd # Clear gradients for this training step
currerror.backward # Backpropagation: compute gradients
optimizer.step # Apply gradients update weights
# Print training status every batches
if i:
print Epoch Step Loss: :f
formatepoch numepochs, i totalstep, currerror.item cnneval
numcorrect
for images, labels in testloader:
testoutput cnnimages
predy torch.maxtestoutput, data.squeeze
numcorrect predy labelssumitem # count the correct number
idxmask predy labels Falsenonzero
accuracynumcorrectlentestdata
printTest Accuracy of the model on the MNIST test images: f accuracy to Train a CNN to classify digits in the MNIST dataset and calculate the test accuracy. Now I want to Create a new
version of the dataset that has smoothedfiltered the images by applying a median filter twice, then use
the same model to calculate a new test accuracy. Create one more version of the dataset where the
images are smoothed in the same way and then sharpened, again use the same model to calculate a
new test accuracy. Hint: Use transforms!
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