Files
pytorch-deep-learning/docs/00_pytorch_fundamentals.ipynb
T
2021-12-15 09:16:01 +10:00

73 KiB

Open In Colab

00. PyTorch Fundamentals

TK - What is PyTorch?

PyTorch is an open source machine learning and deep learning framework.

TK - What can PyTorch be used for?

PyTorch allows you to manipulate and process data and write machine learning algorithms using Python code.

TK - Who uses PyTorch?

Many of the worlds largest technology companies such as Meta (Facebook), Tesla and Microsoft as well as artificial intelligence research companies such as OpenAI use PyTorch to power research and bring machine learning to their products.

For example, Andrej Karpathy (head of AI at Tesla) has given several talks (PyTorch DevCon 2019, Tesla AI Day 2021) about how Tesla use PyTorch to power their self-driving computer vision models.

TK - Why use PyTorch?

Researchers love using PyTorch. Many of the latest machine learning research papers have some kind of PyTorch code attached.

PyTorch also helps take care of many things such as GPU acceleration (making your code run faster) behind the scenes.

So you can focus on manipulating data and writing algorithms and PyTorch will make sure it runs fast.

And if companies such as Tesla and Meta (Facebook) use it to build models they deploy to power hundreds of applications, drive thousands of cars and deliver content to billions of people, it's clearly capable on the development front too.

TK - What we're going to cover in this module...

This course is broken down into different sections (notebooks).

Each notebook covers important ideas and concepts within PyTorch.

Subsequent notebooks build upon knowledge from the previous one.

This notebook deals with the basic building block of machine learning and deep learning, the tensor.

Specifically, we're going to cover:

  • Introduction to tensors - Tensors are the basic building block of all of machine learning and deep learning.
    • Creating tensors - Tensors can represent almost any kind of data (images, words, tables of numbers).
    • Getting information from tensors - If you can put information into a tensor, you'll want to get it out too.
  • Manipulating tensors - Machine learning algorithms (like neural networks) involve manipulating tensors in many different ways such as adding, multiplying, combining.
  • Dealing with tensor shapes - One of the most common issues in machine learning is dealing with shape mismatches (trying to mixed wrong shaped tensors with other tensors).
  • Indexing on tensors - If you've indexed on a Python list or NumPy array, it's very similar with tensors, except they can have far more dimensions.
  • Mixing PyTorch tensors and NumPy - PyTorch plays with tensors (torch.Tensor), NumPy likes arrays (np.ndarray) sometimes you'll want to mix and match these.
  • Reproducibility - Machine learning is very experimental and since it uses a lot of randomness to work, sometimes you'll want that randomness to not be so random.
  • Running tensors on GPU - GPUs (Graphics Processing Units) make your code faster, PyTorch makes it easy to run your code on GPUs.

Where can can you get help?

TK - links

All of the materials for this course live on GitHub.

And if you run into trouble, you can ask a question on the Discussions page there too.

There's also the PyTorch developer forums, a very helpful place for all things PyTorch.

TK - Importing PyTorch

Note: Before running any of the code in this notebook, you should have gone through the PyTorch setup steps (TK-setup steps link). However, if you're running on Google Colab, everything should work (Google Colab comes with PyTorch and other libraries installed).

Let's start by importing PyTorch and checking the version we're using.

In [1]:
import torch
torch.__version__
Out [1]:
'1.10.0'

Wonderful, it looks like we've got PyTorch 1.10.0 (as of Decemeber 2021). This means if you're going through these materials, you'll see most compatability with PyTorch 1.10.0, however if your version number is far higher than that, you might notice some inconsistencies.

And if you do have any issues, please post on the GitHub Discussions page.

TK - Introduction to tensors

Now we've got PyTorch imported, it's time to learn about tensors.

Tensors are the fundamental building block of machine learning.

Their job is to represent data in a numerical way.

For example, you could represent an image as a tensor with shape [3, 224, 224] which would mean [colour_channels, height, width], as in the image has 3 colour channels (red, green, blue), a height of 224 pixels and a width of 224 pixels.

TK - image

In tensor-speak (the language used to describe tensors), the tensor would have three dimensions, one for colour_channels, height and width.

But we're getting ahead of ourselves.

Let's learn more about tensors by coding them.

TK - Creating tensors

PyTorch loves tensors. So much so there's a whole documentation page dedicated to the torch.Tensor class.

Your first piece of homework is to read through the documentation on torch.Tensor for 10-minutes. But you can get to that later.

Let's code.

The first thing we're going to create is a scalar.

A scalar is a single number and in tensor-speak it's a zero dimension tensor.

Note: That's a trend for this course. We'll focus on writing specific code. But often I'll set exercises which involve reading and getting familiar with the PyTorch documentaiton. Because after all, once you're finished this course, you'll no doubt want to learn more. And the documentaiton is somewhere you'll be finding yourself quite often.

In [3]:
# Scalar
scalar = torch.tensor(7)
scalar
Out [3]:
tensor(7)

See how the above printed out tensor(7)?

That means although scalar is a single number, it's of type torch.Tensor.

We can check the dimensions of a tensor using the ndim attribute.

In [4]:
scalar.ndim
Out [4]:
0

What if we wanted to retrieve the number from the tensor?

As in, turn it from torch.Tensor to a Python integer?

To do we can use the item() method.

In [4]:
# Get the Python number within a tensor (only works with one-element tensors)
scalar.item()
Out [4]:
7

Okay, now let's see a vector.

A vector is a single dimension tensor but can contain many numbers.

As in, you could have a vector [3, 2] to describe [bedrooms, bathrooms] in your house. Or you could have [3, 2, 2] to describe [bedrooms, bathrooms, car_parks] in your house.

The important trend here is that a vector is flexible in what it can represent (the same with tensors).

In [16]:
# Vector
vector = torch.tensor([7, 7])
vector
Out [16]:
tensor([7, 7])

Wonderful, vector now contains two 7's, my favourite number.

How many dimensions do you think it'll have?

In [17]:
# Check the number of dimensions of vector
vector.ndim
Out [17]:
1

Hmm, that's strange, vector contains two numbers but only has a single dimension.

I'll let you in on a trick.

You can tell the number of dimensions a tensor in PyTorch has by the number of square brackets on the outside ([) and you only need to count one side.

How many square brackets does vector have?

Another important concept for tensors is their shape attribute. The shape tells you how the elements inside them are arranged.

Let's check out the shape of vector.

In [18]:
# Check shape of vector
vector.shape
Out [18]:
torch.Size([2])

The above returns torch.Size([2]) which means our vector has a shape of [2]. This is because of the two elements we placed inside the square brackets ([7, 7]).

Let's now see a matrix.

In [21]:
# Matrix
MATRIX = torch.tensor([[7, 8], 
                       [9, 10]])
MATRIX
Out [21]:
tensor([[ 7,  8],
        [ 9, 10]])

Wow! More numbers! Matrices are as flexible as vectors, except they've got an extra dimension.

In [22]:
# Check number of dimensions
MATRIX.ndim
Out [22]:
2

MATRIX has two dimensions (did you count the number of square brakcets on the outside of one side?).

What shape do you think it will have?

In [23]:
MATRIX.shape
Out [23]:
torch.Size([2, 2])

We get the output torch.Size([2, 2]) because MATRIX is two elements deep and two elements wide.

How about we create a tensor?

In [24]:
# Tensor
TENSOR = torch.tensor([[[1, 2, 3],
                        [3, 6, 9],
                        [2, 4, 5]]])
TENSOR
Out [24]:
tensor([[[1, 2, 3],
         [3, 6, 9],
         [2, 4, 5]]])

Woah! What a nice looking tensor.

I want to stress that tensors can represent almost anything.

The one we just created could be the sales numbers for a steak and almond butter store (two of my favourite foods).

TK - image: 00_simple_tensor

How many dimensions do you think it has? (hint: use the square bracket counting trick)

In [29]:
# Check number of dimensions for TENSOR
TENSOR.ndim
Out [29]:
3

And what about its shape?

In [30]:
# Check shape of TENSOR
TENSOR.shape
Out [30]:
torch.Size([1, 3, 3])

Alright, it outputs torch.Size([1, 3, 3]).

The dimensions go outer to inner.

That means there's 1 dimension of 3 by 3.

TK - image: 00_pytorch_fundamentals_tensor_shape (keynote 00)

Note: You might've noticed me using lowercase letters for scalar and vector and uppercase letters for MATRIX and TENSOR. This was on purpose. In practice, you'll often see scalars and vectors denoted as lowercase letters such as y or a. And matrices and tensors denoted as uppercase letters such as X or W.

You also might notice the names martrix and tensor used interchangably. This is common. Since in PyTorch you're often dealing with torch.Tensor's (hence the tensor name), however, the shape and dimensions of what's inside will dictate what it actually is.

Let's summarise.

Name What is it? Number of dimensions Lower or upper (usually/example)
scalar a single number 0 Lower (a)
vector a number with direction (e.g. wind speed with direction) but can also have many other numbers 1 Lower (y)
matrix a 2-dimensional array of numbers 2 Upper (Q)
tensor an n-dimensional array of numbers can be any number, a 0-dimension tensor is a scalar, a 1-dimension tensor is a vector Upper (X)

TK - image: scalar, vector, matrix, tensor

Random tensors

We've established tensors represent some form of data.

And machine learning models such as neural networks manipulate and seek patterns within tensors.

But when building machine learning models with PyTorch, it's rare you'll create tenors by hand (like what we've being doing).

Instead, a machine learning model often starts out with large random tensors of numbers and adjusts these random numbers as it works through data to better represent it.

In essence:

Start with random numbers -> look at data -> update random numbers -> look at data -> update random numbers...

As a data scientist, you can define how the machine learning model starts (initialization), looks at data (representation) and updates (optimization) its random numbers.

We'll get hands on with these steps later on.

For now, let's see how to create a tensor of random numbers.

We can do so using torch.rand() and passing in the size parameter.

In [31]:
# Create a random tensor of size (3, 4)
random_tensor = torch.rand(size=(3, 4))
random_tensor, random_tensor.dtype
Out [31]:
(tensor([[0.4043, 0.9331, 0.4070, 0.2407],
         [0.9738, 0.4960, 0.6324, 0.0604],
         [0.5516, 0.3168, 0.9767, 0.2678]]),
 torch.float32)

UPTOHERE... "we can adjust the size to be whatever we want...

Zeros and ones

In [16]:
# Zeros
zeros = torch.zeros(size=(3, 4))
zeros, zeros.dtype
Out [16]:
(tensor([[0., 0., 0., 0.],
         [0., 0., 0., 0.],
         [0., 0., 0., 0.]]),
 torch.float32)
In [17]:
# Ones
ones = torch.ones(size=(3, 4))
ones, ones.dtype
Out [17]:
(tensor([[1., 1., 1., 1.],
         [1., 1., 1., 1.],
         [1., 1., 1., 1.]]),
 torch.float32)
In [20]:
# Use torch.arange(), torch.range() is deprecated 
zero_to_ten_deprecated = torch.range(0, 10) # Note: this may return an error in the future
zero_to_ten = torch.arange(0, 10)
zero_to_ten
Out [20]:
/tmp/ipykernel_327633/58302902.py:2: UserWarning: torch.range is deprecated and will be removed in a future release because its behavior is inconsistent with Python's range builtin. Instead, use torch.arange, which produces values in [start, end).
  zero_to_ten_deprecated = torch.range(0, 10)
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [19]:
# Can also create a tensor of zeros similar to another tensor
ten_zeros = torch.zeros_like(zero_to_ten) # will have same shape
ten_zeros
Out [19]:
tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

Tensor datatypes

In [21]:
# Default datatype for tensors is float32
float_32_tensor = torch.tensor([3.0, 6.0, 9.0],
                               dtype=None, # defaults to None, which is torch.float32 or whatever datatype is passed
                               device=None, # defaults to None, which uses the default tensor type
                               requires_grad=False) # if True, operations perfromed on the tensor are recorded 

float_32_tensor.shape, float_32_tensor.dtype, float_32_tensor.device
Out [21]:
(torch.Size([3]), torch.float32, device(type='cpu'))
In [22]:
float_16_tensor = torch.tensor([3.0, 6.0, 9.0],
                               dtype=torch.float16)

float_16_tensor.dtype
Out [22]:
torch.float16

TK - Getting information from tensors

In [23]:
some_tensor = torch.rand(3, 4)

print(some_tensor)
print(f"Shape of tensor: {some_tensor.shape}")
print(f"Datatype of tensor: {some_tensor.dtype}")
print(f"Device tensor is stored on: {some_tensor.device}") # will default to CPU
tensor([[0.0026, 0.9400, 0.5669, 0.7157],
        [0.7173, 0.2704, 0.3400, 0.6617],
        [0.4410, 0.5464, 0.1685, 0.7501]])
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu

TK - Manipulating tensors (tensor operations)

Basic operations

In [24]:
tensor = torch.tensor([1, 2, 3])
tensor + 10
Out [24]:
tensor([11, 12, 13])
In [25]:
tensor * 10
Out [25]:
tensor([10, 20, 30])
In [26]:
# Tensors don't change unless reassigned
tensor
Out [26]:
tensor([1, 2, 3])
In [27]:
tensor = tensor - 10
tensor
Out [27]:
tensor([-9, -8, -7])
In [28]:
tensor = tensor + 10
tensor
Out [28]:
tensor([1, 2, 3])
In [29]:
# Can also use torch functions
torch.multiply(tensor, 10)
Out [29]:
tensor([10, 20, 30])
In [30]:
# Original tensor is still unchanged 
tensor
Out [30]:
tensor([1, 2, 3])
In [31]:
# Element-wise multiplication
tensor * tensor
Out [31]:
tensor([1, 4, 9])

Matrix multiplcation

Neural networks are mostly matrix multiplcation - https://marksaroufim.substack.com/p/working-class-deep-learner

In [32]:
import torch
tensor = torch.tensor([1, 2, 3])
tensor
Out [32]:
tensor([1, 2, 3])
In [33]:
torch.matmul(tensor, tensor)
Out [33]:
tensor(14)
In [34]:
tensor @ tensor
Out [34]:
tensor(14)
In [35]:
sum(tensor * tensor.T)
Out [35]:
tensor(14)
In [36]:
# By hand (avoid doing operations with for loops at all cost, they are computationally expensive)
value = 0
for i in range(len(tensor)):
  value += tensor[i] * tensor[i]
value
Out [36]:
tensor(14)

One of the most common errors in deep learning

Because much of deep learning is multiplying and performing operations on matrices and matrices have a strict rule about what shapes and sizes can be combined, one of the most common errors you'll run into in deep learning is shape mismatches.

In [37]:
# Shapes need to be in the right way (this will error) 
tensor_A = torch.tensor([[1, 2],
                         [3, 4],
                         [5, 6]], dtype=torch.float32)

tensor_B = torch.tensor([[7, 8],
                         [9, 10], 
                         [11, 12]], dtype=torch.float32)

torch.matmul(tensor_A, tensor_B)
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
/tmp/ipykernel_327633/854767186.py in <module>
      8                          [11, 12]], dtype=torch.float32)
      9 
---> 10 torch.matmul(tensor_A, tensor_B)

RuntimeError: mat1 and mat2 shapes cannot be multiplied (3x2 and 3x2)
In [39]:
# The operation works when tensor_B is transposed
torch.matmul(tensor_A, tensor_B.T)
Out [39]:
tensor([[ 23.,  29.,  35.],
        [ 53.,  67.,  81.],
        [ 83., 105., 127.]])
In [40]:
# torch.mm is a shortcut for matmul
torch.mm(tensor_A, tensor_B.T)
Out [40]:
tensor([[ 23.,  29.,  35.],
        [ 53.,  67.,  81.],
        [ 83., 105., 127.]])
In [41]:
# This uses matrix mutliplcation...
linear = torch.nn.Linear(in_features=3, out_features=2)
input = tensor_A
output = linear(input.T)
output, output.shape
Out [41]:
(tensor([[0.3035, 2.4169],
         [0.8981, 2.5015]], grad_fn=<AddmmBackward0>),
 torch.Size([2, 2]))
In [42]:
tensor_A.T.shape
Out [42]:
torch.Size([2, 3])

TK - Finding the min, max, mean, sum, etc (aggregation)

See here for more operations - https://pytorch.org/docs/stable/tensors.html

In [43]:
x = torch.arange(0, 100, 10)
x
Out [43]:
tensor([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90])
In [44]:
print(f"Minimum: {x.min()}")
print(f"Maximum: {x.max()}")
print(f"Mean: {x.type(torch.float32).mean()}") # won't work without float datatype
print(f"Sum: {x.sum()}")
Minimum: 0
Maximum: 90
Mean: 45.0
Sum: 450
In [45]:
torch.max(x), torch.min(x), torch.mean(x.type(torch.float32)), torch.sum(x)
Out [45]:
(tensor(90), tensor(0), tensor(45.), tensor(450))

TK - Positional min/max

In [46]:
# Returns index of max value
tensor = torch.arange(10, 100, 10)
tensor, tensor.argmax()
Out [46]:
(tensor([10, 20, 30, 40, 50, 60, 70, 80, 90]), tensor(8))
In [47]:
# Returns index of min value
tensor = torch.arange(10, 100, 10)
tensor, tensor.argmin()
Out [47]:
(tensor([10, 20, 30, 40, 50, 60, 70, 80, 90]), tensor(0))

TK - Change tensor datatype

See torch datatypes here - https://pytorch.org/docs/stable/tensors.html

In [48]:
tensor = torch.arange(10., 100., 10.)
tensor.dtype
Out [48]:
torch.float32
In [49]:
tensor_float16 = tensor.type(torch.float16)
tensor_float16
Out [49]:
tensor([10., 20., 30., 40., 50., 60., 70., 80., 90.], dtype=torch.float16)
In [50]:
tensor_int32 = tensor.type(torch.int32)
tensor_int32
Out [50]:
tensor([10, 20, 30, 40, 50, 60, 70, 80, 90], dtype=torch.int32)

TK - Reshaping, stacking, squeezing and unsqueezing

Why do any of these?

Avoid for loops in your tensor code.

For loops slow things down.

In [52]:
import torch
x = torch.arange(1., 8.)
x
Out [52]:
tensor([1., 2., 3., 4., 5., 6., 7.])
In [53]:
# Add an extra dimension
x_reshaped = x.reshape(1, 7)
x_reshaped, x_reshaped.shape
Out [53]:
(tensor([[1., 2., 3., 4., 5., 6., 7.]]), torch.Size([1, 7]))
In [54]:
# Change view (keeps same data as original but changes view)
# See more: https://stackoverflow.com/a/54507446/7900723
z = x.view(1, 7)
z, z.shape
Out [54]:
(tensor([[1., 2., 3., 4., 5., 6., 7.]]), torch.Size([1, 7]))
In [55]:
# Changing z changes x
z[:, 0] = 5
z, x
Out [55]:
(tensor([[5., 2., 3., 4., 5., 6., 7.]]), tensor([5., 2., 3., 4., 5., 6., 7.]))
In [56]:
# Stack tensors on top of each other
x_stacked = torch.stack([x, x, x, x], dim=0)
x_stacked
Out [56]:
tensor([[5., 2., 3., 4., 5., 6., 7.],
        [5., 2., 3., 4., 5., 6., 7.],
        [5., 2., 3., 4., 5., 6., 7.],
        [5., 2., 3., 4., 5., 6., 7.]])
In [57]:
# Remove extra dimension from x_reshaped
x_squeezed = x_reshaped.squeeze()
x_squeezed, x_squeezed.shape
Out [57]:
(tensor([5., 2., 3., 4., 5., 6., 7.]), torch.Size([7]))
In [58]:
# Add an extra dimension with unsqueeze
x_unsqueezed = x_squeezed.unsqueeze(dim=0)
x_unsqueezed, x_unsqueezed.shape
Out [58]:
(tensor([[5., 2., 3., 4., 5., 6., 7.]]), torch.Size([1, 7]))
In [63]:
# Change different axes
x_original = torch.rand(size=(224, 224, 3))
x_permuted = x_original.permute(2, 0, 1) # shifts axis 0->1, 1->2, 2->0
x_original.shape, x_permuted.shape
Out [63]:
(torch.Size([224, 224, 3]), torch.Size([3, 224, 224]))

TK - Indexing (selecting data from tensors)

In [ ]:
# Indexing goes outer to inner...
TENSOR[0][0]
In [64]:
import torch
tensor = torch.arange(0, 9, 1).view(1, 3, 3)
tensor
Out [64]:
tensor([[[0, 1, 2],
         [3, 4, 5],
         [6, 7, 8]]])
In [65]:
tensor[0]
Out [65]:
tensor([[0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]])
In [66]:
tensor[:, 0]
Out [66]:
tensor([[0, 1, 2]])
In [67]:
tensor[:, :, 1]
Out [67]:
tensor([[1, 4, 7]])
In [68]:
tensor[:, 1, 1]
Out [68]:
tensor([4])
In [69]:
tensor[:, :, 0]
Out [69]:
tensor([[0, 3, 6]])

TK - Changing values

Use scatter() to change values for things like one-hot encoding.

https://pytorch.org/docs/stable/generated/torch.Tensor.scatter_.html#torch.Tensor.scatter_

In [ ]:
# TODO - add in example of scatter

TK - PyTorch tensors & NumPy

In [130]:
# NumPy array to tensor
import numpy as np
array = np.arange(1, 8)
tensor = torch.from_numpy(array)
array, tensor
Out [130]:
(array([1, 2, 3, 4, 5, 6, 7]), tensor([1, 2, 3, 4, 5, 6, 7]))
In [131]:
# Change the array, keep the tensor
array = array + 1
array, tensor
Out [131]:
(array([2, 3, 4, 5, 6, 7, 8]), tensor([1, 2, 3, 4, 5, 6, 7]))
In [134]:
# Tensor to NumPy array
tensor = torch.ones(7)
numpy_tensor = tensor.numpy()
tensor, numpy_tensor
Out [134]:
(tensor([1., 1., 1., 1., 1., 1., 1.]),
 array([1., 1., 1., 1., 1., 1., 1.], dtype=float32))
Warning:
Output truncated. This notebook contains too many cells to display efficiently.