22.02.2024 Views

Daniel Voigt Godoy - Deep Learning with PyTorch Step-by-Step A Beginner’s Guide-leanpub

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

StepByStep Method

@staticmethod

def loader_apply(loader, func, reduce='sum'):

results = [func(x, y) for i, (x, y) in enumerate(loader)]

results = torch.stack(results, axis=0)

if reduce == 'sum':

results = results.sum(axis=0)

elif reduce == 'mean':

results = results.float().mean(axis=0)

return results

setattr(StepByStep, 'loader_apply', loader_apply)

Since it is a static method, we can call it from the class itself, passing the loader as

its first argument, and a function (or method, in this case) as its second argument. It

will call the correct() method for each mini-batch (as in the example above), and

sum all the results up:

StepByStep.loader_apply(sbs_cnn1.val_loader, sbs_cnn1.correct)

Output

tensor([[59, 67],

[55, 62],

[71, 71]])

Quite simple, right? This method will be very useful for us in the next chapter when

we normalize the images and thus need to compute the mean and standard

deviation over all images in the training loader.

From the results above, we see that our model got 185 out of 200 images correctly

classified in the validation set, an accuracy of 92.5%! Not bad, not bad at all :-)

Putting It All Together

In this chapter, we focused mostly on the model configuration part, adding

410 | Chapter 5: Convolutions

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!