mirror of
https://github.com/mrdbourke/pytorch-deep-learning.git
synced 2026-11-27 06:07:09 +00:00
129 KiB
129 KiB
In [ ]:
import torch
torch.__version__'1.10.0+cu111'
In [ ]:
# Scalar
scalar = torch.tensor(7)
scalartensor(7)
In [ ]:
scalar.ndim0
In [ ]:
# Get the Python number within a tensor (only works with one-element tensors)
scalar.item()7
In [ ]:
# Vector
vector = torch.tensor([7, 7])
vectortensor([7, 7])
In [ ]:
# Check the number of dimensions of vector
vector.ndim1
In [ ]:
# Check shape of vector
vector.shapetorch.Size([2])
In [ ]:
# Matrix
MATRIX = torch.tensor([[7, 8],
[9, 10]])
MATRIXtensor([[ 7, 8],
[ 9, 10]])In [ ]:
# Check number of dimensions
MATRIX.ndim2
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 [ ]:
# Check number of dimensions for TENSOR
TENSOR.ndim3
In [ ]:
# Check shape of TENSOR
TENSOR.shapetorch.Size([1, 3, 3])
In [ ]:
# Create a random tensor of size (3, 4)
random_tensor = torch.rand(size=(3, 4))
random_tensor, random_tensor.dtype(tensor([[0.4090, 0.2527, 0.8699, 0.2002],
[0.8421, 0.1428, 0.1431, 0.0111],
[0.2281, 0.0345, 0.6734, 0.3866]]), torch.float32)In [ ]:
# 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.ndim(torch.Size([224, 224, 3]), 3)
In [ ]:
# Create a tensor of all zeros
zeros = torch.zeros(size=(3, 4))
zeros, zeros.dtype(tensor([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]]), torch.float32)In [ ]:
# Create a tensor of all ones
ones = torch.ones(size=(3, 4))
ones, ones.dtype(tensor([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]]), torch.float32)In [ ]:
# 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_ten/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 [ ]:
# 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_zerostensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
In [ ]:
# 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(torch.Size([3]), torch.float32, device(type='cpu'))
In [ ]:
float_16_tensor = torch.tensor([3.0, 6.0, 9.0],
dtype=torch.float16) # torch.half would also work
float_16_tensor.dtypetorch.float16
In [ ]:
# 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.7799, 0.8140, 0.0893, 0.2062],
[0.7525, 0.3845, 0.8207, 0.4587],
[0.9277, 0.8166, 0.9052, 0.0953]])
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu
In [ ]:
# Create a tensor of values and add a number to it
tensor = torch.tensor([1, 2, 3])
tensor + 10tensor([11, 12, 13])
In [ ]:
# Multiply it by 10
tensor * 10tensor([10, 20, 30])
In [ ]:
# Tensors don't change unless reassigned
tensortensor([1, 2, 3])
In [ ]:
# Subtract and reassign
tensor = tensor - 10
tensortensor([-9, -8, -7])
In [ ]:
# Add and reassign
tensor = tensor + 10
tensortensor([1, 2, 3])
In [ ]:
# Can also use torch functions
torch.multiply(tensor, 10)tensor([10, 20, 30])
In [ ]:
# Original tensor is still unchanged
tensortensor([1, 2, 3])
In [ ]:
# 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 [ ]:
import torch
tensor = torch.tensor([1, 2, 3])
tensor.shapetorch.Size([3])
In [ ]:
# Element-wise matrix mutlication
tensor * tensortensor([1, 4, 9])
In [ ]:
# Matrix multiplication
torch.matmul(tensor, tensor)tensor(14)
In [ ]:
# Can also use the "@" symbol for matrix multiplication, though not recommended
tensor @ tensortensor(14)
In [ ]:
%%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 146 µs, sys: 38 µs, total: 184 µs Wall time: 227 µs
In [ ]:
%%time
torch.matmul(tensor, tensor)CPU times: user 27 µs, sys: 7 µs, total: 34 µs Wall time: 36.7 µs
tensor(14)
In [ ]:
# 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-37-aceec990e652>[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;31m# (this will error)[0m[0;34m[0m[0;34m[0m[0m [0m [0;31mRuntimeError[0m: mat1 and mat2 shapes cannot be multiplied (3x2 and 3x2)
In [ ]:
# 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 [ ]:
# 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 [ ]:
# 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 [ ]:
# torch.mm is a shortcut for matmul
torch.mm(tensor_A, tensor_B.T)tensor([[ 27., 30., 33.],
[ 61., 68., 75.],
[ 95., 106., 117.]])In [ ]:
# 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 [ ]:
# Create a tensor
x = torch.arange(0, 100, 10)
xtensor([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90])
In [ ]:
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 [ ]:
torch.max(x), torch.min(x), torch.mean(x.type(torch.float32)), torch.sum(x)(tensor(90), tensor(0), tensor(45.), tensor(450))
In [ ]:
# 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 [ ]:
# Create a tensor and check its datatype
tensor = torch.arange(10., 100., 10.)
tensor.dtypetorch.float32
In [ ]:
# Create a float16 tensor
tensor_float16 = tensor.type(torch.float16)
tensor_float16tensor([10., 20., 30., 40., 50., 60., 70., 80., 90.], dtype=torch.float16)
In [ ]:
# Create a int8 tensor
tensor_int8 = tensor.type(torch.int8)
tensor_int8tensor([10, 20, 30, 40, 50, 60, 70, 80, 90], dtype=torch.int8)
Warning:
Output truncated. This notebook contains too many cells to display efficiently.






