mirror of
https://github.com/mrdbourke/pytorch-deep-learning.git
synced 2026-11-27 06:07:09 +00:00
57 KiB
57 KiB
In [1]:
import torch
print(torch.__version__)1.9.1
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]:
vector.ndimOut [6]:
1
In [7]:
# Matrix
matrix = torch.tensor([[7, 8],
[9, 10]])
matrixOut [7]:
tensor([[ 7, 8],
[ 9, 10]])In [8]:
matrix.ndimOut [8]:
2
In [9]:
# Tensor
tensor = torch.tensor([[[3, 6, 9],
[3, 6, 9],
[3, 6, 9]]])
tensorOut [9]:
tensor([[[3, 6, 9],
[3, 6, 9],
[3, 6, 9]]])In [10]:
tensor.ndimOut [10]:
3
In [19]:
# Note: torch.tensor() always makes a copy
tensor_A = torch.tensor([1, 2, 3])
tensor_B = torch.tensor(tensor_A) # Creating a tensor like this produces a warning
tensor_A, tensor_BOut [19]:
/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:3: UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor). This is separate from the ipykernel package so we can avoid doing imports until
(tensor([1, 2, 3]), tensor([1, 2, 3]))
In [20]:
# Change tensor_B, doesn't change tensor_A
tensor_B[0] = 4
tensor_A, tensor_BOut [20]:
(tensor([1, 2, 3]), tensor([4, 2, 3]))
In [21]:
# Change tensor_A, doesn't change tensor_B
tensor_A[1] = 4
tensor_A, tensor_BOut [21]:
(tensor([1, 4, 3]), tensor([4, 2, 3]))
In [27]:
# Random
random_tensor = torch.rand(size=(3, 4))
random_tensor, random_tensor.dtypeOut [27]:
(tensor([[0.6109, 0.1709, 0.9683, 0.5726],
[0.6924, 0.6208, 0.8857, 0.1900],
[0.7239, 0.4225, 0.0904, 0.8145]]), torch.float32)In [29]:
# Zeros
zeros = torch.zeros(size=(3, 4))
zeros, zeros.dtypeOut [29]:
(tensor([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]]), torch.float32)In [30]:
# torch.arange(), torch.range() is deprecated
zero_to_ten = torch.arange(0, 10)
zero_to_tenOut [30]:
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [32]:
# 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 [32]:
tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
In [23]:
# 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 [23]:
(torch.Size([3]), torch.float32, device(type='cpu'))
In [24]:
float_16_tensor = torch.tensor([3.0, 6.0, 9.0],
dtype=torch.float16)
float_16_tensor.dtypeOut [24]:
torch.float16
In [34]:
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.7211, 0.2743, 0.2621, 0.0821],
[0.0890, 0.7967, 0.8323, 0.2623],
[0.8343, 0.2572, 0.4677, 0.1218]])
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu
In [94]:
tensor = torch.tensor([1, 2, 3])
tensor + 10Out [94]:
tensor([11, 12, 13])
In [44]:
tensor * 10Out [44]:
tensor([10, 20, 30])
In [45]:
# Tensors don't change unless reassigned
tensorOut [45]:
tensor([1, 2, 3])
In [46]:
tensor = tensor - 10
tensorOut [46]:
tensor([-9, -8, -7])
In [47]:
tensor = tensor + 10
tensorOut [47]:
tensor([1, 2, 3])
In [48]:
# Can also use torch functions
torch.multiply(tensor, 10)Out [48]:
tensor([10, 20, 30])
In [49]:
# Original tensor is still unchanged
tensorOut [49]:
tensor([1, 2, 3])
In [55]:
# Element-wise multiplication
tensor * tensorOut [55]:
tensor([1, 4, 9])
In [2]:
import torch
tensor = torch.tensor([1, 2, 3])
tensorOut [2]:
tensor([1, 2, 3])
In [3]:
torch.matmul(tensor, tensor)Out [3]:
tensor(14)
In [4]:
tensor @ tensorOut [4]:
tensor(14)
In [5]:
sum(tensor * tensor.T)Out [5]:
tensor(14)
In [6]:
# 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 [6]:
tensor(14)
In [7]:
# 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_34033/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 [8]:
torch.matmul(tensor_A, tensor_B.T)Out [8]:
tensor([[ 23., 29., 35.],
[ 53., 67., 81.],
[ 83., 105., 127.]])In [9]:
# torch.mm is a shortcut for matmul
torch.mm(tensor_A, tensor_B.T)Out [9]:
tensor([[ 23., 29., 35.],
[ 53., 67., 81.],
[ 83., 105., 127.]])In [79]:
# This uses matrix mutliplcation...
linear = torch.nn.Linear(in_features=3, out_features=2)
input = tensor_A
output = linear(input.T)
output, output.shapeOut [79]:
(tensor([[ 1.4391, -1.4383],
[ 1.5400, -1.5229]], grad_fn=<AddmmBackward>), torch.Size([2, 2]))In [80]:
tensor_A.T.shapeOut [80]:
torch.Size([2, 3])
In [103]:
x = torch.arange(0, 100, 10)
xOut [103]:
tensor([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90])
In [104]:
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 [106]:
torch.max(x), torch.min(x), torch.mean(x.type(torch.float32)), torch.sum(x)Out [106]:
(tensor(90), tensor(0), tensor(45.), tensor(450))
In [83]:
# Returns index of max value
tensor = torch.arange(10, 100, 10)
tensor, tensor.argmax()Out [83]:
(tensor([10, 20, 30, 40, 50, 60, 70, 80, 90]), tensor(8))
In [86]:
# Returns index of min value
tensor = torch.arange(10, 100, 10)
tensor, tensor.argmin()Out [86]:
(tensor([10, 20, 30, 40, 50, 60, 70, 80, 90]), tensor(0))
In [87]:
tensor = torch.arange(10., 100., 10.)
tensor.dtypeOut [87]:
torch.float32
In [92]:
tensor_float16 = tensor.type(torch.float16)
tensor_float16Out [92]:
tensor([10., 20., 30., 40., 50., 60., 70., 80., 90.], dtype=torch.float16)
In [93]:
tensor_int32 = tensor.type(torch.int32)
tensor_int32Out [93]:
tensor([10, 20, 30, 40, 50, 60, 70, 80, 90], dtype=torch.int32)
In [16]:
import torch
x = torch.arange(1., 8.)
xOut [16]:
tensor([1., 2., 3., 4., 5., 6., 7.])
In [17]:
# Add an extra dimension
x_reshaped = x.reshape(1, 7)
x_reshaped, x_reshaped.shapeOut [17]:
(tensor([[1., 2., 3., 4., 5., 6., 7.]]), torch.Size([1, 7]))
In [18]:
# 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 [18]:
(tensor([[1., 2., 3., 4., 5., 6., 7.]]), torch.Size([1, 7]))
In [19]:
# Changing z changes x
z[:, 0] = 5
z, xOut [19]:
(tensor([[5., 2., 3., 4., 5., 6., 7.]]), tensor([5., 2., 3., 4., 5., 6., 7.]))
In [20]:
# Stack tensors on top of each other
x_stacked = torch.stack([x, x, x, x], dim=0)
x_stackedOut [20]:
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 [116]:
# Remove extra dimension from x_reshaped
x_squeezed = x_reshaped.squeeze()
x_squeezed, x_squeezed.shapeOut [116]:
(tensor([1., 2., 3., 4., 5., 6., 7.]), torch.Size([7]))
In [120]:
# Add an extra dimension with unsqueeze
x_unsqueezed = x_squeezed.unsqueeze(dim=0)
x_unsqueezed, x_unsqueezed.shapeOut [120]:
(tensor([[1., 2., 3., 4., 5., 6., 7.]]), torch.Size([1, 7]))
In [23]:
import torch
tensor = torch.arange(0, 9, 1).view(1, 3, 3)
tensorOut [23]:
tensor([[[0, 1, 2],
[3, 4, 5],
[6, 7, 8]]])In [24]:
tensor[0]Out [24]:
tensor([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])In [25]:
tensor[:, 0]Out [25]:
tensor([[0, 1, 2]])
In [26]:
tensor[:, :, 1]Out [26]:
tensor([[1, 4, 7]])
In [28]:
tensor[:, 1, 1]Out [28]:
tensor([4])
In [31]:
tensor[:, :, 0]Out [31]:
tensor([[0, 3, 6]])
In [ ]:
# TODO - add in example of scatterIn [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))
In [135]:
# Change the tensor, keep the array the same
tensor = tensor + 1
tensor, numpy_tensorOut [135]:
(tensor([2., 2., 2., 2., 2., 2., 2.]), array([1., 1., 1., 1., 1., 1., 1.], dtype=float32))
In [32]:
# No seed
import torch
random_tensor_A = torch.rand(3, 4)
random_tensor_B = torch.rand(3, 4)
random_tensor_A == random_tensor_BOut [32]:
tensor([[False, False, False, False],
[False, False, False, False],
[False, False, False, False]])In [40]:
# With seed
import torch
# Set the random seed
torch.random.manual_seed(42)
random_tensor_C = torch.rand(3, 4)
# Have to reset the seed every time a new rand() is called
torch.random.manual_seed(42) # Without this, tensor_D would be different to tensor_C
random_tesnor_D = torch.rand(3, 4)
random_tensor_C == random_tesnor_D
Out [40]:
tensor([[True, True, True, True],
[True, True, True, True],
[True, True, True, True]])In [42]:
# Check for GPU
import torch
torch.cuda.is_available()Out [42]:
True
In [14]:
# Set device type
device = "cuda" if torch.cuda.is_available() else "cpu"
deviceOut [14]:
'cuda'
In [41]:
# Count number of devices
torch.cuda.device_count()Out [41]:
1
In [21]:
# Create tensor (default on CPU)
tensor = torch.tensor([1, 2, 3])
# Tensor not on GPU
print(tensor, tensor.device)
# Move tensor to GPU
tensor_on_gpu = tensor.to(device)
tensor_on_gpuOut [21]:
tensor([1, 2, 3]) cpu
tensor([1, 2, 3], device='cuda:0')
In [25]:
# If tensor is on GPU, can't transform it to NumPy (this will error)
tensor_on_gpu.numpy()[0;31m---------------------------------------------------------------------------[0m [0;31mTypeError[0m Traceback (most recent call last) [0;32m/tmp/ipykernel_7994/1481451780.py[0m in [0;36m<module>[0;34m[0m [1;32m 1[0m [0;31m# If tensor is on GPU, can't transform it to NumPy[0m[0;34m[0m[0;34m[0m[0m [0;32m----> 2[0;31m [0mtensor_on_gpu[0m[0;34m.[0m[0mnumpy[0m[0;34m([0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0m [0;31mTypeError[0m: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.
In [29]:
# Instead, copy the tensor back to cpu
tensor_back_on_cpu = tensor_on_gpu.cpu().numpy()
tensor_back_on_cpuOut [29]:
array([1, 2, 3])
In [30]:
tensor_on_gpuOut [30]:
tensor([1, 2, 3], device='cuda:0')