mirror of
https://github.com/mrdbourke/pytorch-deep-learning.git
synced 2026-11-27 06:07:09 +00:00
97 KiB
97 KiB
In [2]:
import torch
torch.__version__Out [2]:
'1.10.0+cu111'
In [3]:
# Scalar
scalar = torch.tensor(7)
scalarOut [3]:
tensor(7)
In [4]:
scalar.ndimOut [4]:
0
In [5]:
# Get the Python number within a tensor (only works with one-element tensors)
scalar.item()Out [5]:
7
In [6]:
# Vector
vector = torch.tensor([7, 7])
vectorOut [6]:
tensor([7, 7])
In [7]:
# Check the number of dimensions of vector
vector.ndimOut [7]:
1
In [8]:
# Check shape of vector
vector.shapeOut [8]:
torch.Size([2])
In [9]:
# Matrix
MATRIX = torch.tensor([[7, 8],
[9, 10]])
MATRIXOut [9]:
tensor([[ 7, 8],
[ 9, 10]])In [10]:
# Check number of dimensions
MATRIX.ndimOut [10]:
2
In [11]:
MATRIX.shapeOut [11]:
torch.Size([2, 2])
In [12]:
# Tensor
TENSOR = torch.tensor([[[1, 2, 3],
[3, 6, 9],
[2, 4, 5]]])
TENSOROut [12]:
tensor([[[1, 2, 3],
[3, 6, 9],
[2, 4, 5]]])In [13]:
# Check number of dimensions for TENSOR
TENSOR.ndimOut [13]:
3
In [14]:
# Check shape of TENSOR
TENSOR.shapeOut [14]:
torch.Size([1, 3, 3])
In [15]:
# Create a random tensor of size (3, 4)
random_tensor = torch.rand(size=(3, 4))
random_tensor, random_tensor.dtypeOut [15]:
(tensor([[0.7907, 0.6947, 0.0406, 0.9267],
[0.9972, 0.1773, 0.7616, 0.6983],
[0.8819, 0.8777, 0.2598, 0.8966]]), torch.float32)In [16]:
# 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 [16]:
(torch.Size([224, 224, 3]), 3)
In [17]:
# Create a tensor of all zeros
zeros = torch.zeros(size=(3, 4))
zeros, zeros.dtypeOut [17]:
(tensor([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]]), torch.float32)In [18]:
# Create a tensor of all ones
ones = torch.ones(size=(3, 4))
ones, ones.dtypeOut [18]:
(tensor([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]]), torch.float32)In [19]:
# 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 [19]:
/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.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).
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [20]:
# 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 [20]:
tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
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.deviceOut [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) # torch.half would also work
float_16_tensor.dtypeOut [22]:
torch.float16
In [23]:
# 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.8791, 0.3106, 0.3004, 0.8722],
[0.8353, 0.3828, 0.3335, 0.3006],
[0.2225, 0.1692, 0.0564, 0.3756]])
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu
In [24]:
# Create a tensor of values and add a number to it
tensor = torch.tensor([1, 2, 3])
tensor + 10Out [24]:
tensor([11, 12, 13])
In [25]:
# Multiply it by 10
tensor * 10Out [25]:
tensor([10, 20, 30])
In [26]:
# Tensors don't change unless reassigned
tensorOut [26]:
tensor([1, 2, 3])
In [27]:
# Subtract and reassign
tensor = tensor - 10
tensorOut [27]:
tensor([-9, -8, -7])
In [28]:
# Add and reassign
tensor = tensor + 10
tensorOut [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
tensorOut [30]:
tensor([1, 2, 3])
In [31]:
# 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 [32]:
import torch
tensor = torch.tensor([1, 2, 3])
tensor.shapeOut [32]:
torch.Size([3])
In [33]:
# Element-wise matrix mutlication
tensor * tensorOut [33]:
tensor([1, 4, 9])
In [34]:
# Matrix multiplication
torch.matmul(tensor, tensor)Out [34]:
tensor(14)
In [35]:
# Can also use the "@" symbol for matrix multiplication, though not recommended
tensor @ tensorOut [35]:
tensor(14)
In [36]:
%%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]
valueCPU times: user 134 µs, sys: 44 µs, total: 178 µs Wall time: 187 µs
In [37]:
%%time
torch.matmul(tensor, tensor)Out [37]:
CPU times: user 38 µs, sys: 0 ns, total: 38 µs Wall time: 41.2 µs
tensor(14)
In [38]:
# 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) [0;32m<ipython-input-38-ebd3c69b6d6c>[0m in [0;36m<module>[0;34m()[0m [1;32m 8[0m [9, 12]], dtype=torch.float32) [1;32m 9[0m [0;34m[0m[0m [0;32m---> 10[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 [39]:
# 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 [40]:
# 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 [41]:
# 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 [42]:
# torch.mm is a shortcut for matmul
torch.mm(tensor_A, tensor_B.T)Out [42]:
tensor([[ 27., 30., 33.],
[ 61., 68., 75.],
[ 95., 106., 117.]])In [50]:
# 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 mutliplcation
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 [51]:
# Create a tensor
x = torch.arange(0, 100, 10)
xOut [51]:
tensor([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90])
In [56]:
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 [53]:
torch.max(x), torch.min(x), torch.mean(x.type(torch.float32)), torch.sum(x)Out [53]:
(tensor(90), tensor(0), tensor(45.), tensor(450))
In [58]:
# 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 [ ]:
tensor = torch.arange(10., 100., 10.)
tensor.dtypetorch.float32
In [ ]:
tensor_float16 = tensor.type(torch.float16)
tensor_float16tensor([10., 20., 30., 40., 50., 60., 70., 80., 90.], dtype=torch.float16)
In [ ]:
tensor_int32 = tensor.type(torch.int32)
tensor_int32tensor([10, 20, 30, 40, 50, 60, 70, 80, 90], dtype=torch.int32)
Warning:
Output truncated. This notebook contains too many cells to display efficiently.

