22.02.2024 Views

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

import numpy as np

import datetime

import torch

import torch.optim as optim

import torch.nn as nn

import torch.functional as F

from torch.utils.data import DataLoader, TensorDataset, random_split

from torch.utils.tensorboard import SummaryWriter

import matplotlib.pyplot as plt

%matplotlib inline

plt.style.use('fivethirtyeight')

Going Classy

So far, the %%writefile magic has helped us to organize the code into three distinct

parts: data preparation, model configuration, and model training. At the end of

Chapter 2, though, we bumped into some of its limitations, like being unable to

choose a different number of epochs without having to edit the model training

code.

Clearly, this situation is not ideal. We need to do better. We need to go classy; that

is, we need to build a class to handle the model training part.

I am assuming you have a working knowledge of object-oriented

programming (OOP) in order to benefit the most from this

chapter. If that’s not the case, and if you didn’t do it in Chapter 1,

now is the time to follow tutorials like Real Python’s "Object-

Oriented Programming (OOP) in Python 3" [63] and "Supercharge

Your Classes With Python super()." [64]

The Class

Let’s start by defining our class with a rather unoriginal name: StepByStep. We’re

starting it from scratch: Either we don’t specify a parent class, or we inherit it from

the fundamental object class. I personally prefer the latter, so our class definition

looks like this:

176 | Chapter 2.1: Going Classy

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

Saved successfully!

Ooh no, something went wrong!