mirror of
https://github.com/mrdbourke/pytorch-deep-learning.git
synced 2026-11-27 06:07:09 +00:00
[fix]: Fix a typo 'multiplcation'->'multiplication' in 00_pytorch_funamentals.ipynb
117 KiB
117 KiB
In [1]:
import torch
torch.__version__Out [1]:
'1.13.1+cu116'
In [2]:
# Scalar
scalar = torch.tensor(7)
scalarOut [2]:
tensor(7)
In [3]:
scalar.ndimOut [3]:
0
In [4]:
# Get the Python number within a tensor (only works with one-element tensors)
scalar.item()Out [4]:
7
In [5]:
# Vector
vector = torch.tensor([7, 7])
vectorOut [5]:
tensor([7, 7])
In [6]:
# Check the number of dimensions of vector
vector.ndimOut [6]:
1
In [7]:
# Check shape of vector
vector.shapeOut [7]:
torch.Size([2])
In [8]:
# Matrix
MATRIX = torch.tensor([[7, 8],
[9, 10]])
MATRIXOut [8]:
tensor([[ 7, 8],
[ 9, 10]])In [9]:
# Check number of dimensions
MATRIX.ndimOut [9]:
2
In [10]:
MATRIX.shapeOut [10]:
torch.Size([2, 2])
In [11]:
# Tensor
TENSOR = torch.tensor([[[1, 2, 3],
[3, 6, 9],
[2, 4, 5]]])
TENSOROut [11]:
tensor([[[1, 2, 3],
[3, 6, 9],
[2, 4, 5]]])In [12]:
# Check number of dimensions for TENSOR
TENSOR.ndimOut [12]:
3
In [13]:
# Check shape of TENSOR
TENSOR.shapeOut [13]:
torch.Size([1, 3, 3])
In [14]:
# Create a random tensor of size (3, 4)
random_tensor = torch.rand(size=(3, 4))
random_tensor, random_tensor.dtypeOut [14]:
(tensor([[0.6541, 0.4807, 0.2162, 0.6168],
[0.4428, 0.6608, 0.6194, 0.8620],
[0.2795, 0.6055, 0.4958, 0.5483]]),
torch.float32)In [15]:
# Create a random tensor of size (224, 224, 3)
random_image_size_tensor = torch.rand(size=(224, 224, 3))
random_image_size_tensor.shape, random_image_size_tensor.ndimOut [15]:
(torch.Size([224, 224, 3]), 3)
In [16]:
# Create a tensor of all zeros
zeros = torch.zeros(size=(3, 4))
zeros, zeros.dtypeOut [16]:
(tensor([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]]),
torch.float32)In [17]:
# Create a tensor of all ones
ones = torch.ones(size=(3, 4))
ones, ones.dtypeOut [17]:
(tensor([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]]),
torch.float32)In [18]:
# Use torch.arange(), torch.range() is deprecated
zero_to_ten_deprecated = torch.range(0, 10) # Note: this may return an error in the future
# Create a range of values 0 to 10
zero_to_ten = torch.arange(start=0, end=10, step=1)
zero_to_tenOut [18]:
/tmp/ipykernel_3695928/193451495.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) # Note: this may return an error in the future
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(input=zero_to_ten) # will have same shape
ten_zerosOut [19]:
tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
In [20]:
# 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 performed on the tensor are recorded
float_32_tensor.shape, float_32_tensor.dtype, float_32_tensor.deviceOut [20]:
(torch.Size([3]), torch.float32, device(type='cpu'))
In [21]:
float_16_tensor = torch.tensor([3.0, 6.0, 9.0],
dtype=torch.float16) # torch.half would also work
float_16_tensor.dtypeOut [21]:
torch.float16
In [22]:
# Create a tensor
some_tensor = torch.rand(3, 4)
# Find out details about it
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 CPUtensor([[0.4688, 0.0055, 0.8551, 0.0646],
[0.6538, 0.5157, 0.4071, 0.2109],
[0.9960, 0.3061, 0.9369, 0.7008]])
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu
In [23]:
# Create a tensor of values and add a number to it
tensor = torch.tensor([1, 2, 3])
tensor + 10Out [23]:
tensor([11, 12, 13])
In [24]:
# Multiply it by 10
tensor * 10Out [24]:
tensor([10, 20, 30])
In [25]:
# Tensors don't change unless reassigned
tensorOut [25]:
tensor([1, 2, 3])
In [26]:
# Subtract and reassign
tensor = tensor - 10
tensorOut [26]:
tensor([-9, -8, -7])
In [27]:
# Add and reassign
tensor = tensor + 10
tensorOut [27]:
tensor([1, 2, 3])
In [28]:
# Can also use torch functions
torch.multiply(tensor, 10)Out [28]:
tensor([10, 20, 30])
In [29]:
# Original tensor is still unchanged
tensorOut [29]:
tensor([1, 2, 3])
In [30]:
# Element-wise multiplication (each element multiplies its equivalent, index 0->0, 1->1, 2->2)
print(tensor, "*", tensor)
print("Equals:", tensor * tensor)tensor([1, 2, 3]) * tensor([1, 2, 3]) Equals: tensor([1, 4, 9])
In [31]:
import torch
tensor = torch.tensor([1, 2, 3])
tensor.shapeOut [31]:
torch.Size([3])
In [32]:
# Element-wise matrix multiplication
tensor * tensorOut [32]:
tensor([1, 4, 9])
In [33]:
# Matrix multiplication
torch.matmul(tensor, tensor)Out [33]:
tensor(14)
In [34]:
# Can also use the "@" symbol for matrix multiplication, though not recommended
tensor @ tensorOut [34]:
tensor(14)
In [35]:
%%time
# Matrix multiplication 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]
valueOut [35]:
CPU times: user 773 µs, sys: 0 ns, total: 773 µs Wall time: 499 µs
tensor(14)
In [36]:
%%time
torch.matmul(tensor, tensor)Out [36]:
CPU times: user 146 µs, sys: 83 µs, total: 229 µs Wall time: 171 µs
tensor(14)
In [37]:
# Shapes need to be in the right way
tensor_A = torch.tensor([[1, 2],
[3, 4],
[5, 6]], dtype=torch.float32)
tensor_B = torch.tensor([[7, 10],
[8, 11],
[9, 12]], dtype=torch.float32)
torch.matmul(tensor_A, tensor_B) # (this will error)[0;31m---------------------------------------------------------------------------[0m [0;31mRuntimeError[0m Traceback (most recent call last) [1;32m/home/daniel/code/pytorch/pytorch-course/pytorch-deep-learning/00_pytorch_fundamentals.ipynb Cell 75[0m in [0;36m<cell line: 10>[0;34m()[0m [1;32m <a href='vscode-notebook-cell://ssh-remote%2B7b22686f73744e616d65223a22544954414e2d525458227d/home/daniel/code/pytorch/pytorch-course/pytorch-deep-learning/00_pytorch_fundamentals.ipynb#Y134sdnNjb2RlLXJlbW90ZQ%3D%3D?line=1'>2</a>[0m tensor_A [39m=[39m torch[39m.[39mtensor([[[39m1[39m, [39m2[39m], [1;32m <a href='vscode-notebook-cell://ssh-remote%2B7b22686f73744e616d65223a22544954414e2d525458227d/home/daniel/code/pytorch/pytorch-course/pytorch-deep-learning/00_pytorch_fundamentals.ipynb#Y134sdnNjb2RlLXJlbW90ZQ%3D%3D?line=2'>3</a>[0m [[39m3[39m, [39m4[39m], [1;32m <a href='vscode-notebook-cell://ssh-remote%2B7b22686f73744e616d65223a22544954414e2d525458227d/home/daniel/code/pytorch/pytorch-course/pytorch-deep-learning/00_pytorch_fundamentals.ipynb#Y134sdnNjb2RlLXJlbW90ZQ%3D%3D?line=3'>4</a>[0m [[39m5[39m, [39m6[39m]], dtype[39m=[39mtorch[39m.[39mfloat32) [1;32m <a href='vscode-notebook-cell://ssh-remote%2B7b22686f73744e616d65223a22544954414e2d525458227d/home/daniel/code/pytorch/pytorch-course/pytorch-deep-learning/00_pytorch_fundamentals.ipynb#Y134sdnNjb2RlLXJlbW90ZQ%3D%3D?line=5'>6</a>[0m tensor_B [39m=[39m torch[39m.[39mtensor([[[39m7[39m, [39m10[39m], [1;32m <a href='vscode-notebook-cell://ssh-remote%2B7b22686f73744e616d65223a22544954414e2d525458227d/home/daniel/code/pytorch/pytorch-course/pytorch-deep-learning/00_pytorch_fundamentals.ipynb#Y134sdnNjb2RlLXJlbW90ZQ%3D%3D?line=6'>7</a>[0m [[39m8[39m, [39m11[39m], [1;32m <a href='vscode-notebook-cell://ssh-remote%2B7b22686f73744e616d65223a22544954414e2d525458227d/home/daniel/code/pytorch/pytorch-course/pytorch-deep-learning/00_pytorch_fundamentals.ipynb#Y134sdnNjb2RlLXJlbW90ZQ%3D%3D?line=7'>8</a>[0m [[39m9[39m, [39m12[39m]], dtype[39m=[39mtorch[39m.[39mfloat32) [0;32m---> <a href='vscode-notebook-cell://ssh-remote%2B7b22686f73744e616d65223a22544954414e2d525458227d/home/daniel/code/pytorch/pytorch-course/pytorch-deep-learning/00_pytorch_fundamentals.ipynb#Y134sdnNjb2RlLXJlbW90ZQ%3D%3D?line=9'>10</a>[0m torch[39m.[39;49mmatmul(tensor_A, tensor_B) [0;31mRuntimeError[0m: mat1 and mat2 shapes cannot be multiplied (3x2 and 3x2)
In [38]:
# View tensor_A and tensor_B
print(tensor_A)
print(tensor_B)tensor([[1., 2.],
[3., 4.],
[5., 6.]])
tensor([[ 7., 10.],
[ 8., 11.],
[ 9., 12.]])
In [39]:
# View tensor_A and tensor_B.T
print(tensor_A)
print(tensor_B.T)tensor([[1., 2.],
[3., 4.],
[5., 6.]])
tensor([[ 7., 8., 9.],
[10., 11., 12.]])
In [40]:
# The operation works when tensor_B is transposed
print(f"Original shapes: tensor_A = {tensor_A.shape}, tensor_B = {tensor_B.shape}\n")
print(f"New shapes: tensor_A = {tensor_A.shape} (same as above), tensor_B.T = {tensor_B.T.shape}\n")
print(f"Multiplying: {tensor_A.shape} * {tensor_B.T.shape} <- inner dimensions match\n")
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 as above), tensor_B.T = torch.Size([2, 3])
Multiplying: torch.Size([3, 2]) * torch.Size([2, 3]) <- inner dimensions match
Output:
tensor([[ 27., 30., 33.],
[ 61., 68., 75.],
[ 95., 106., 117.]])
Output shape: torch.Size([3, 3])
In [41]:
# torch.mm is a shortcut for matmul
torch.mm(tensor_A, tensor_B.T)Out [41]:
tensor([[ 27., 30., 33.],
[ 61., 68., 75.],
[ 95., 106., 117.]])In [42]:
# Since the linear layer starts with a random weights matrix, let's make it reproducible (more on this later)
torch.manual_seed(42)
# This uses matrix multiplication
linear = torch.nn.Linear(in_features=2, # in_features = matches inner dimension of input
out_features=6) # out_features = describes outer value
x = tensor_A
output = linear(x)
print(f"Input shape: {x.shape}\n")
print(f"Output:\n{output}\n\nOutput shape: {output.shape}")Input shape: torch.Size([3, 2])
Output:
tensor([[2.2368, 1.2292, 0.4714, 0.3864, 0.1309, 0.9838],
[4.4919, 2.1970, 0.4469, 0.5285, 0.3401, 2.4777],
[6.7469, 3.1648, 0.4224, 0.6705, 0.5493, 3.9716]],
grad_fn=<AddmmBackward0>)
Output shape: torch.Size([3, 6])
In [43]:
# Create a tensor
x = torch.arange(0, 100, 10)
xOut [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.mean()}") # this will error
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))
In [46]:
# Create a tensor
tensor = torch.arange(10, 100, 10)
print(f"Tensor: {tensor}")
# Returns index of max and min values
print(f"Index where max value occurs: {tensor.argmax()}")
print(f"Index where min value occurs: {tensor.argmin()}")Tensor: tensor([10, 20, 30, 40, 50, 60, 70, 80, 90]) Index where max value occurs: 8 Index where min value occurs: 0
In [47]:
# Create a tensor and check its datatype
tensor = torch.arange(10., 100., 10.)
tensor.dtypeOut [47]:
torch.float32
In [48]:
# Create a float16 tensor
tensor_float16 = tensor.type(torch.float16)
tensor_float16Out [48]:
tensor([10., 20., 30., 40., 50., 60., 70., 80., 90.], dtype=torch.float16)
In [49]:
# Create a int8 tensor
tensor_int8 = tensor.type(torch.int8)
tensor_int8Out [49]:
tensor([10, 20, 30, 40, 50, 60, 70, 80, 90], dtype=torch.int8)
Warning:
Output truncated. This notebook contains too many cells to display efficiently.






