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.

Loading Data, Devices, and CUDA

It is time to start converting our Numpy code to PyTorch: We’ll start with the

training data; that is, our x_train and y_train arrays.

"How do we go from Numpy’s arrays to PyTorch’s tensors?"

That’s what as_tensor() is good for (which works like from_numpy()).

This operation preserves the type of the array:

x_train_tensor = torch.as_tensor(x_train)

x_train.dtype, x_train_tensor.dtype

Output

(dtype('float64'), torch.float64)

You can also easily cast it to a different type, like a lower-precision (32-bit) float,

which will occupy less space in memory, using float():

float_tensor = x_train_tensor.float()

float_tensor.dtype

Output

torch.float32

IMPORTANT: Both as_tensor() and from_numpy() return a

tensor that shares the underlying data with the original Numpy

array. Similar to what happened when we used view() in the last

section, if you modify the original Numpy array, you’re modifying

the corresponding PyTorch tensor too, and vice-versa.

76 | Chapter 1: A Simple Regression Problem

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

Saved successfully!

Ooh no, something went wrong!