mirror of
https://github.com/mrdbourke/pytorch-deep-learning.git
synced 2026-11-27 06:07:09 +00:00
79 KiB
79 KiB
In [ ]:
import torch
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
print(torch.__version__)1.10.0+cu111
In [ ]:
# scalar
scalar = torch.tensor(7)
scalartensor(7)
In [ ]:
scalar.ndim0
In [ ]:
# Get tensor back as Python int
scalar.item()7
In [ ]:
# Vector
vector = torch.tensor([7, 7])
vectortensor([7, 7])
In [ ]:
vector.ndim1
In [ ]:
vector.shapetorch.Size([2])
In [ ]:
# MATRIX
MATRIX = torch.tensor([[7, 8],
[9, 10]])
MATRIXtensor([[ 7, 8],
[ 9, 10]])In [ ]:
MATRIX.ndim2
In [ ]:
MATRIX[1]tensor([ 9, 10])
In [ ]:
MATRIX.shapetorch.Size([2, 2])
In [ ]:
# TENSOR
TENSOR = torch.tensor([[[1, 2, 3],
[3, 6, 9],
[2, 4, 5]]])
TENSORtensor([[[1, 2, 3],
[3, 6, 9],
[2, 4, 5]]])In [ ]:
TENSOR.ndim3
In [ ]:
TENSOR.shapetorch.Size([1, 3, 3])
In [ ]:
TENSOR[0]tensor([[1, 2, 3],
[3, 6, 9],
[2, 4, 5]])In [ ]:
# Create a random tensor of size (3, 4)
random_tensor = torch.rand(3, 4)
random_tensortensor([[0.4433, 0.7119, 0.4170, 0.4409],
[0.8014, 0.2050, 0.3547, 0.6358],
[0.3007, 0.1659, 0.3462, 0.7317]])In [ ]:
# Create a random tensor with similar shape to an image tensor
random_image_size_tensor = torch.rand(size=(3, 224, 224)) # height, width, colour channels (R, G, B)
random_image_size_tensor.shape, random_image_size_tensor.ndim(torch.Size([3, 224, 224]), 3)
In [ ]:
# Create a tensor of all zeros
zeros = torch.zeros(size=(3, 4))
zerostensor([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])In [ ]:
# Create a tensor of all ones
ones = torch.ones(size=(3, 4))
onestensor([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]])In [ ]:
ones.dtypetorch.float32
In [ ]:
random_tensor.dtypetorch.float32
In [ ]:
# Use torch.range() and get deprecated message, use torch.arange()
one_to_ten = torch.arange(start=1, end=11, step=1)
one_to_tentensor([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
In [ ]:
# Creating tensors like
ten_zeros = torch.zeros_like(input=one_to_ten)
ten_zerostensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
In [ ]:
# Float 32 tensor
float_32_tensor = torch.tensor([3.0, 6.0, 9.0],
dtype=None, # what datatype is the tensor (e.g. float32 or float16)
device=None, # What device is your tensor on
requires_grad=False) # whether or not to track gradients with this tensors operations
float_32_tensortensor([3., 6., 9.])
In [ ]:
float_32_tensor.dtypetorch.float32
In [ ]:
float_16_tensor = float_32_tensor.type(torch.float16)
float_16_tensortensor([3., 6., 9.], dtype=torch.float16)
In [ ]:
float_16_tensor * float_32_tensortensor([ 9., 36., 81.])
In [ ]:
int_32_tensor = torch.tensor([3, 6, 9], dtype=torch.long)
int_32_tensortensor([3, 6, 9])
In [ ]:
float_32_tensor * int_32_tensortensor([ 9., 36., 81.])
In [ ]:
# Create a tensor
some_tensor = torch.rand(3, 4)
some_tensortensor([[0.7151, 0.9288, 0.0464, 0.2910],
[0.7281, 0.5272, 0.9098, 0.3145],
[0.9641, 0.4652, 0.8553, 0.0232]])In [ ]:
# Find out details about some tensor
print(some_tensor)
print(f"Datatype of tensor: {some_tensor.dtype}")
print(f"Shape of tensor: {some_tensor.shape}")
print(f"Device tensor is on: {some_tensor.device}")tensor([[0.7151, 0.9288, 0.0464, 0.2910],
[0.7281, 0.5272, 0.9098, 0.3145],
[0.9641, 0.4652, 0.8553, 0.0232]])
Datatype of tensor: torch.float32
Shape of tensor: torch.Size([3, 4])
Device tensor is on: cpu
In [ ]:
# Create a tensor and add 10 to it
tensor = torch.tensor([1, 2, 3])
tensor + 10tensor([11, 12, 13])
In [ ]:
# Multiply tensor by 10
tensor * 10tensor([10, 20, 30])
In [ ]:
tensortensor([1, 2, 3])
In [ ]:
# Substract 10
tensor - 10tensor([-9, -8, -7])
In [ ]:
# Try out PyTorch in-built functions
torch.mul(tensor, 10)tensor([10, 20, 30])
In [ ]:
torch.add(tensor, 10)tensor([11, 12, 13])
In [ ]:
# Element wise multiplication
print(tensor, "*", tensor)
print(f"Equals: {tensor * tensor}")tensor([1, 2, 3]) * tensor([1, 2, 3]) Equals: tensor([1, 4, 9])
In [ ]:
# Matrix multiplication
torch.matmul(tensor, tensor)tensor(14)
In [ ]:
tensortensor([1, 2, 3])
In [ ]:
# Matrix multiplication by hand
1*1 + 2*2 + 3*314
In [ ]:
%%time
value = 0
for i in range(len(tensor)):
value += tensor[i] * tensor[i]
print(value)tensor(14) CPU times: user 661 µs, sys: 876 µs, total: 1.54 ms Wall time: 1.55 ms
In [ ]:
%%time
torch.matmul(tensor, tensor)CPU times: user 67 µs, sys: 29 µs, total: 96 µs Wall time: 101 µs
tensor(14)
In [ ]:
# Shapes for matrix multiplication
tensor_A = torch.tensor([[1, 2],
[3, 4],
[5, 6]])
tensor_B = torch.tensor([[7, 10],
[8, 11],
[9, 12]])
# torch.mm(tensor_A, tensor_B) # torch.mm is the same as torch.matmul (it's an alias for writing less code)
torch.matmul(tensor_A, tensor_B)[0;31m---------------------------------------------------------------------------[0m [0;31mRuntimeError[0m Traceback (most recent call last) [0;32m<ipython-input-46-281a2d72c2ec>[0m in [0;36m<module>[0;34m()[0m [1;32m 9[0m [0;34m[0m[0m [1;32m 10[0m [0;31m# torch.mm(tensor_A, tensor_B) # torch.mm is the same as torch.matmul (it's an alias for writing less code)[0m[0;34m[0m[0;34m[0m[0;34m[0m[0m [0;32m---> 11[0;31m [0mtorch[0m[0;34m.[0m[0mmatmul[0m[0;34m([0m[0mtensor_A[0m[0;34m,[0m [0mtensor_B[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0m [0;31mRuntimeError[0m: mat1 and mat2 shapes cannot be multiplied (3x2 and 3x2)
In [ ]:
tensor_B.Ttensor([[ 7, 8, 9],
[10, 11, 12]])In [ ]:
tensor_A.shape, tensor_B.shape(torch.Size([3, 2]), torch.Size([3, 2]))
In [ ]:
tensor_B, tensor_B.shape(tensor([[ 7, 10],
[ 8, 11],
[ 9, 12]]), torch.Size([3, 2]))In [ ]:
tensor_B.T, tensor_B.T.shape(tensor([[ 7, 8, 9],
[10, 11, 12]]), torch.Size([2, 3]))In [ ]:
# The matrix multiplication operation works when tensor_B is transposed
print(f"Original shapes: tensor_A = {tensor_A.shape}, tensor_B = {tensor_B.shape}")
print(f"New shapes: tensor_A = {tensor_A.shape} (same shape as above), tensor_B.T = {tensor_B.T.shape}")
print(f"Multiplying: {tensor_A.shape} @ {tensor_B.T.shape} <- inner dimensions must match")
print("Output:\n")
output = torch.matmul(tensor_A, tensor_B.T)
print(output)
print(f"\nOutput shape: {output.shape}")Original shapes: tensor_A = torch.Size([3, 2]), tensor_B = torch.Size([3, 2])
New shapes: tensor_A = torch.Size([3, 2]) (same shape as above), tensor_B.T = torch.Size([2, 3])
Multiplying: torch.Size([3, 2]) @ torch.Size([2, 3]) <- inner dimensions must match
Output:
tensor([[ 27, 30, 33],
[ 61, 68, 75],
[ 95, 106, 117]])
Output shape: torch.Size([3, 3])
In [ ]:
# Create a tensor
x = torch.arange(1, 100, 10)
x, x.dtype(tensor([ 1, 11, 21, 31, 41, 51, 61, 71, 81, 91]), torch.int64)
In [ ]:
# Find the min
torch.min(x), x.min()(tensor(1), tensor(1))
In [ ]:
# Find the max
torch.max(x), x.max()(tensor(91), tensor(91))
In [ ]:
# Find the mean - note: the torch.mean() function requires a tensor of float32 datatype to work
torch.mean(x.type(torch.float32)), x.type(torch.float32).mean()(tensor(46.), tensor(46.))
In [ ]:
# Find the sum
torch.sum(x), x.sum()(tensor(460), tensor(460))
In [ ]:
xtensor([ 1, 11, 21, 31, 41, 51, 61, 71, 81, 91])
In [ ]:
# Find the position in tensor that has the minimum value with argmin() -> returns index position of targt tensor where the minimum value occurs
x.argmin()tensor(0)
In [ ]:
x[0]tensor(1)
In [ ]:
# Find the position in tensor that has the maximum value with argmax()
x.argmax()tensor(9)
In [ ]:
x[9]tensor(91)
In [ ]:
# Let's create a tensor
import torch
x = torch.arange(1., 10.)
x, x.shape(tensor([1., 2., 3., 4., 5., 6., 7., 8., 9.]), torch.Size([9]))
In [ ]:
# Add an extra dimension
x_reshaped = x.reshape(1, 9)
x_reshaped, x_reshaped.shape(tensor([[1., 2., 3., 4., 5., 6., 7., 8., 9.]]), torch.Size([1, 9]))
In [ ]:
# Change the view
z = x.view(1, 9)
z, z.shape(tensor([[1., 2., 3., 4., 5., 6., 7., 8., 9.]]), torch.Size([1, 9]))
In [ ]:
# Changing z changes x (because a view of a tensor shares the same memory as the original input)
z[:, 0] = 5
z, x(tensor([[5., 2., 3., 4., 5., 6., 7., 8., 9.]]), tensor([5., 2., 3., 4., 5., 6., 7., 8., 9.]))
In [ ]:
# Stack tensors on top of each other
x_stacked = torch.stack([x, x, x, x], dim=0)
x_stackedtensor([[5., 2., 3., 4., 5., 6., 7., 8., 9.],
[5., 2., 3., 4., 5., 6., 7., 8., 9.],
[5., 2., 3., 4., 5., 6., 7., 8., 9.],
[5., 2., 3., 4., 5., 6., 7., 8., 9.]])In [ ]:
# torch.squeeze() - removes all single dimensions from a target tensor
print(f"Previous tensor: {x_reshaped}")
print(f"Previous shape: {x_reshaped.shape}")
# Remove extra dimensions from x_reshaped
x_squeezed = x_reshaped.squeeze()
print(f"\nNew tensor: {x_squeezed}")
print(f"New shape: {x_squeezed.shape}")Previous tensor: tensor([[5., 2., 3., 4., 5., 6., 7., 8., 9.]]) Previous shape: torch.Size([1, 9]) New tensor: tensor([5., 2., 3., 4., 5., 6., 7., 8., 9.]) New shape: torch.Size([9])
In [ ]:
# torch.unsqueeze() - adds a single dimension to a target tensor at a specific dim (dimension)
print(f"Previous target: {x_squeezed}")
print(f"Previous shape: {x_squeezed.shape}")
# Add an extra dimension with unsqueeze
x_unsqueezed = x_squeezed.unsqueeze(dim=0)
print(f"\nNew tensor: {x_unsqueezed}")
print(f"New shape: {x_unsqueezed.shape}")Previous target: tensor([5., 2., 3., 4., 5., 6., 7., 8., 9.]) Previous shape: torch.Size([9]) New tensor: tensor([[5., 2., 3., 4., 5., 6., 7., 8., 9.]]) New shape: torch.Size([1, 9])
In [ ]:
# torch.permute - rearranges the dimensions of a target tensor in a specified order
x_original = torch.rand(size=(224, 224, 3)) # [height, width, colour_channels]
# Permute the original tensor to rearrange the axis (or dim) order
x_permuted = x_original.permute(2, 0, 1) # shifts axis 0->1, 1->2, 2->0
print(f"Previous shape: {x_original.shape}")
print(f"New shape: {x_permuted.shape}") # [colour_channels, height, width]Previous shape: torch.Size([224, 224, 3]) New shape: torch.Size([3, 224, 224])
In [ ]:
x_original[0, 0, 0] = 728218
x_original[0, 0, 0], x_permuted[0, 0, 0](tensor(728218.), tensor(728218.))
In [ ]:
# Create a tensor
import torch
x = torch.arange(1, 10).reshape(1, 3, 3)
x, x.shape(tensor([[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]]), torch.Size([1, 3, 3]))In [ ]:
# Let's index on our new tensor
x[0]tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])In [ ]:
# Let's index on the middle bracket (dim=1)
x[0][0]tensor([1, 2, 3])
In [ ]:
# Let's index on the most inner bracket (last dimension)
x[0][1][1]tensor(5)
In [ ]:
# You can also use ":" to select "all" of a target dimension
x[:, 0]tensor([[1, 2, 3]])
In [ ]:
# Get all values of 0th and 1st dimensions but only index 1 of 2nd dimension
x[:, :, 1]tensor([[2, 5, 8]])
In [ ]:
# Get all values of the 0 dimension but only the 1 index value of 1st and 2nd dimension
x[:, 1, 1]tensor([5])
In [ ]:
# Get index 0 of 0th and 1st dimension and all values of 2nd dimension
x[0, 0, :]tensor([1, 2, 3])
In [ ]:
# Index on x to return 9
print(x[0][2][2])
# Index on x to return 3, 6, 9
print(x[:, :, 2])tensor(9) tensor([[3, 6, 9]])
In [ ]:
# NumPy array to tensor
import torch
import numpy as np
array = np.arange(1.0, 8.0)
tensor = torch.from_numpy(array) # warning: when converting from numpy -> pytorch, pytorch reflects numpy's default datatype of float64 unless specified otherwise
array, tensor(array([1., 2., 3., 4., 5., 6., 7.]), tensor([1., 2., 3., 4., 5., 6., 7.], dtype=torch.float64))
In [ ]:
# Change the value of array, what will this do to `tensor`?
array = array + 1
array, tensor(array([2., 3., 4., 5., 6., 7., 8.]), tensor([1., 2., 3., 4., 5., 6., 7.], dtype=torch.float64))
In [ ]:
# Tensor to NumPy array
tensor = torch.ones(7)
numpy_tensor = tensor.numpy()
tensor, numpy_tensor(tensor([1., 1., 1., 1., 1., 1., 1.]), array([1., 1., 1., 1., 1., 1., 1.], dtype=float32))
In [ ]:
# Change the tesnor, what happens to `numpy_tensor`?
tensor = tensor + 1
tensor, numpy_tensor (tensor([2., 2., 2., 2., 2., 2., 2.]), array([1., 1., 1., 1., 1., 1., 1.], dtype=float32))
In [ ]:
import torch
# Create two random tensors
random_tensor_A = torch.rand(3, 4)
random_tensor_B = torch.rand(3, 4)
print(random_tensor_A)
print(random_tensor_B)
print(random_tensor_A == random_tensor_B)tensor([[0.3675, 0.8410, 0.0507, 0.3165],
[0.7275, 0.9676, 0.3901, 0.8840],
[0.5177, 0.2239, 0.4362, 0.3602]])
tensor([[0.5229, 0.6719, 0.2790, 0.8198],
[0.6689, 0.8659, 0.7849, 0.4268],
[0.2076, 0.8076, 0.4377, 0.2555]])
tensor([[False, False, False, False],
[False, False, False, False],
[False, False, False, False]])
Warning:
Output truncated. This notebook contains too many cells to display efficiently.