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.

# Creates the train_step function for our model,

# loss function and optimizer

# Note: there are NO ARGS there! It makes use of the class

# attributes directly

self.train_step_fn = self._make_train_step_fn()

# Creates the val_step function for our model and loss

self.val_step_fn = self._make_val_step_fn()

If you have patched together the pieces of code above, your code should look like

this:

StepByStep Class

class StepByStep(object):

def __init__(self, model, loss_fn, optimizer):

# Here we define the attributes of our class

# We start by storing the arguments as attributes

# to use them later

self.model = model

self.loss_fn = loss_fn

self.optimizer = optimizer

self.device = 'cuda' if torch.cuda.is_available() else 'cpu'

# Let's send the model to the specified device right away

self.model.to(self.device)

# These attributes are defined here, but since they are

# not available at the moment of creation, we keep them None

self.train_loader = None

self.val_loader = None

self.writer = None

# These attributes are going to be computed internally

self.losses = []

self.val_losses = []

self.total_epochs = 0

# Creates the train_step function for our model,

# loss function and optimizer

# Note: there are NO ARGS there! It makes use of the class

# attributes directly

self.train_step_fn = self._make_train_step_fn()

Going Classy | 181

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

Saved successfully!

Ooh no, something went wrong!