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 val_step function for our model and loss

self.val_step_fn = self._make_val_step_fn()

def to(self, device):

# This method allows the user to specify a different device

# It sets the corresponding attribute (to be used later in

# the mini-batches) and sends the model to the device

try:

self.device = device

self.model.to(self.device)

except RuntimeError:

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

else 'cpu')

print(f"Couldn't send it to {device}, \

sending it to {self.device} instead.")

self.model.to(self.device)

def set_loaders(self, train_loader, val_loader=None):

# This method allows the user to define which train_loader

# (and val_loader, optionally) to use

# Both loaders are then assigned to attributes of the class

# So they can be referred to later

self.train_loader = train_loader

self.val_loader = val_loader

def set_tensorboard(self, name, folder='runs'):

# This method allows the user to create a SummaryWriter to

# interface with TensorBoard

suffix = datetime.datetime.now().strftime('%Y%m%d%H%M%S')

self.writer = SummaryWriter(f'{folder}/{name}_{suffix}')

Sure, we are still missing both _make_train_step_fn() and _make_val_step_fn()

functions. Both are pretty much the same as before, except that they refer to the

class attributes self.model, self.loss_fn, and self.optimizer, instead of taking

them as arguments. They look like this now:

Step Methods

def _make_train_step_fn(self):

# This method does not need ARGS... it can use directly

# the attributes: self.model, self.loss_fn and self.optimizer

182 | Chapter 2.1: Going Classy

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

Saved successfully!

Ooh no, something went wrong!