PyTorch Tensors

code
ML
This project serves as an introduction to PyTorch and tensors.
Author

Matthias Quinn

Published

November 20, 2022

GOAL

Learn more about the Machine Learning framework known as PyTorch.

RESULT

A better understanding of PyTorch and what tensors are.

This walkthrough is my interpretation of the official PyTorch tutorial on tensors.

Tensors

Tensors are a data structure similar to arrays and matrices. PyTorch uses tensors to encode both the inputs and outputs of a model as well as model parameters.

Tensors are like NumPy arrays, but tensors can be run on GPUs and are also optimized for automatic differentiation.

Load in the libraries

Code
import numpy as np
import torch

Initializing a Tensor

Tensors can be initialized in various ways, like so:

Directly from data:

Code
data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)

From a NumPy array:

Code
np_array = np.array(data)
x_np = torch.from_numpy(np_array)

From another tensor:

Code
x_ones = torch.ones_like(x_data) # retains the properties of x_data
print(f"Ones Tensor: \n {x_ones} \n")

x_rand = torch.rand_like(x_data, dtype=torch.float) # overrides the datatype of x_data
print(f"Random Tensor: \n {x_rand} \n")
Ones Tensor: 
 tensor([[1, 1],
        [1, 1]]) 

Random Tensor: 
 tensor([[0.4359, 0.1517],
        [0.9181, 0.1814]])