mirror of
https://github.com/mrdbourke/pytorch-deep-learning.git
synced 2026-11-27 06:07:09 +00:00
73 KiB
73 KiB
In [1]:
import torch
torch.__version__Out [1]:
'1.10.0'
In [3]:
# Scalar
scalar = torch.tensor(7)
scalarOut [3]:
tensor(7)
In [4]:
scalar.ndimOut [4]:
0
In [4]:
# Get the Python number within a tensor (only works with one-element tensors)
scalar.item()Out [4]:
7
In [16]:
# Vector
vector = torch.tensor([7, 7])
vectorOut [16]:
tensor([7, 7])
In [17]:
# Check the number of dimensions of vector
vector.ndimOut [17]:
1
In [18]:
# Check shape of vector
vector.shapeOut [18]:
torch.Size([2])
In [21]:
# Matrix
MATRIX = torch.tensor([[7, 8],
[9, 10]])
MATRIXOut [21]:
tensor([[ 7, 8],
[ 9, 10]])In [22]:
# Check number of dimensions
MATRIX.ndimOut [22]:
2
In [23]:
MATRIX.shapeOut [23]:
torch.Size([2, 2])
In [24]:
# Tensor
TENSOR = torch.tensor([[[1, 2, 3],
[3, 6, 9],
[2, 4, 5]]])
TENSOROut [24]:
tensor([[[1, 2, 3],
[3, 6, 9],
[2, 4, 5]]])In [29]:
# Check number of dimensions for TENSOR
TENSOR.ndimOut [29]:
3
In [30]:
# Check shape of TENSOR
TENSOR.shapeOut [30]:
torch.Size([1, 3, 3])
In [31]:
# Create a random tensor of size (3, 4)
random_tensor = torch.rand(size=(3, 4))
random_tensor, random_tensor.dtypeOut [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)In [16]:
# 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]:
# 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 [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_tenOut [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_zerosOut [19]:
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)
float_16_tensor.dtypeOut [22]:
torch.float16
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 CPUtensor([[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
In [24]:
tensor = torch.tensor([1, 2, 3])
tensor + 10Out [24]:
tensor([11, 12, 13])
In [25]:
tensor * 10Out [25]:
tensor([10, 20, 30])
In [26]:
# Tensors don't change unless reassigned
tensorOut [26]:
tensor([1, 2, 3])
In [27]:
tensor = tensor - 10
tensorOut [27]:
tensor([-9, -8, -7])
In [28]:
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
tensor * tensorOut [31]:
tensor([1, 4, 9])
In [32]:
import torch
tensor = torch.tensor([1, 2, 3])
tensorOut [32]:
tensor([1, 2, 3])
In [33]:
torch.matmul(tensor, tensor)Out [33]:
tensor(14)
In [34]:
tensor @ tensorOut [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]
valueOut [36]:
tensor(14)
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)[0;31m---------------------------------------------------------------------------[0m [0;31mRuntimeError[0m Traceback (most recent call last) [0;32m/tmp/ipykernel_327633/854767186.py[0m in [0;36m<module>[0;34m[0m [1;32m 8[0m [11, 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]:
# 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.shapeOut [41]:
(tensor([[0.3035, 2.4169],
[0.8981, 2.5015]], grad_fn=<AddmmBackward0>),
torch.Size([2, 2]))In [42]:
tensor_A.T.shapeOut [42]:
torch.Size([2, 3])
In [43]:
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.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]:
# 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))
In [48]:
tensor = torch.arange(10., 100., 10.)
tensor.dtypeOut [48]:
torch.float32
In [49]:
tensor_float16 = tensor.type(torch.float16)
tensor_float16Out [49]:
tensor([10., 20., 30., 40., 50., 60., 70., 80., 90.], dtype=torch.float16)
In [50]:
tensor_int32 = tensor.type(torch.int32)
tensor_int32Out [50]:
tensor([10, 20, 30, 40, 50, 60, 70, 80, 90], dtype=torch.int32)
In [52]:
import torch
x = torch.arange(1., 8.)
xOut [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.shapeOut [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.shapeOut [54]:
(tensor([[1., 2., 3., 4., 5., 6., 7.]]), torch.Size([1, 7]))
In [55]:
# Changing z changes x
z[:, 0] = 5
z, xOut [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_stackedOut [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.shapeOut [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.shapeOut [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.shapeOut [63]:
(torch.Size([224, 224, 3]), torch.Size([3, 224, 224]))
In [ ]:
# Indexing goes outer to inner...
TENSOR[0][0]In [64]:
import torch
tensor = torch.arange(0, 9, 1).view(1, 3, 3)
tensorOut [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]])
In [ ]:
# TODO - add in example of scatter
In [130]:
# NumPy array to tensor
import numpy as np
array = np.arange(1, 8)
tensor = torch.from_numpy(array)
array, tensorOut [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, tensorOut [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_tensorOut [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.