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.

How does this change our code so far? Let’s check it out!

First, we need to add both Dataset and DataLoader elements into our data

preparation part of the code. Also, notice that we do not send our tensors to the

device just yet (just like we did in Notebook Cell 2.1). It should look like this:

Define - Data Preparation V1

1 %%writefile data_preparation/v1.py

2

3 # Our data was in Numpy arrays, but we need to transform them

4 # into PyTorch's Tensors

5 x_train_tensor = torch.as_tensor(x_train).float()

6 y_train_tensor = torch.as_tensor(y_train).float()

7

8 # Builds Dataset

9 train_data = TensorDataset(x_train_tensor, y_train_tensor) 1

10

11 # Builds DataLoader

12 train_loader = DataLoader( 2

13 dataset=train_data,

14 batch_size=16,

15 shuffle=True,

16 )

1 Building a dataset of tensors

2 Building a data loader that yields mini-batches of size 16

Run - Data Preparation V1

%run -i data_preparation/v1.py

Next, we need to incorporate the mini-batch gradient descent logic into our model

training part of the code. But we need to run the model configuration first.

Run - Model Configuration V1

%run -i model_configuration/v1.py

DataLoader | 139

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

Saved successfully!

Ooh no, something went wrong!