mirror of
https://github.com/mrdbourke/pytorch-deep-learning.git
synced 2026-11-27 06:07:09 +00:00
122 KiB
122 KiB
In [1]:
import torch
print(f"PyTorch version: {torch.__version__}")PyTorch version: 1.12.1+cu113
In [2]:
# Create two tensors
tensor_1 = torch.rand(3, 4)
tensor_2 = torch.rand(3, 4)
# Check the shapes
print(tensor_1.shape)
print(tensor_2.shape)torch.Size([3, 4]) torch.Size([3, 4])
In [3]:
# Standard multiplication, the following lines perform the same operation (will work)
tensor_3 = tensor_1 * tensor_2 # can do standard multiplication with "*"
tensor_4 = torch.mul(tensor_1, tensor_2) # can also do standard multiplicaton with "torch.mul()"
# Check for equality
tensor_3 == tensor_4Out [3]:
tensor([[True, True, True, True],
[True, True, True, True],
[True, True, True, True]])In [4]:
# Try matrix multiplication (won't work)
tensor_5 = tensor_1 @ tensor_2 # could also do "torch.matmul(tensor_1, tensor_2)"[0;31m---------------------------------------------------------------------------[0m [0;31mRuntimeError[0m Traceback (most recent call last) Input [0;32mIn [4][0m, in [0;36m<cell line: 2>[0;34m()[0m [1;32m 1[0m [38;5;66;03m# Try matrix multiplication (won't work)[39;00m [0;32m----> 2[0m tensor_5 [38;5;241m=[39m [43mtensor_1[49m[43m [49m[38;5;241;43m@[39;49m[43m [49m[43mtensor_2[49m [0;31mRuntimeError[0m: mat1 and mat2 shapes cannot be multiplied (3x4 and 3x4)
In [5]:
# Perform a transpose on tensor_1 and then perform matrix multiplication
tensor_6 = tensor_1.T @ tensor_2
print(f"Shape of input tensors: {tensor_1.T.shape} and {tensor_2.shape}")
print(f"Shape of output tensor: {tensor_6.shape}")Shape of input tensors: torch.Size([4, 3]) and torch.Size([3, 4]) Shape of output tensor: torch.Size([4, 4])
In [6]:
# Perform a transpose on tensor_2 and then perform matrix multiplication
tensor_7 = tensor_1 @ tensor_2.T
print(f"Shape of input tensors: {tensor_1.shape} and {tensor_2.T.shape}")
print(f"Shape of output tensor: {tensor_7.shape}")Shape of input tensors: torch.Size([3, 4]) and torch.Size([4, 3]) Shape of output tensor: torch.Size([3, 3])
In [7]:
import torchvision
from torchvision import datasets, transforms
# Setup training data
train_data = datasets.FashionMNIST(
root="data", # where to download data to?
train=True, # get training data
download=True, # download data if it doesn't exist on disk
transform=transforms.ToTensor(), # images come as PIL format, we want to turn into Torch tensors
target_transform=None # you can transform labels as well
)
# Setup testing data
test_data = datasets.FashionMNIST(
root="data",
train=False, # get test data
download=True,
transform=transforms.ToTensor()
)Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gz Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gz to data/FashionMNIST/raw/train-images-idx3-ubyte.gz
0%| | 0/26421880 [00:00<?, ?it/s]
Extracting data/FashionMNIST/raw/train-images-idx3-ubyte.gz to data/FashionMNIST/raw Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-labels-idx1-ubyte.gz Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-labels-idx1-ubyte.gz to data/FashionMNIST/raw/train-labels-idx1-ubyte.gz
0%| | 0/29515 [00:00<?, ?it/s]
Extracting data/FashionMNIST/raw/train-labels-idx1-ubyte.gz to data/FashionMNIST/raw Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-images-idx3-ubyte.gz Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-images-idx3-ubyte.gz to data/FashionMNIST/raw/t10k-images-idx3-ubyte.gz
0%| | 0/4422102 [00:00<?, ?it/s]
Extracting data/FashionMNIST/raw/t10k-images-idx3-ubyte.gz to data/FashionMNIST/raw Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-labels-idx1-ubyte.gz Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/t10k-labels-idx1-ubyte.gz to data/FashionMNIST/raw/t10k-labels-idx1-ubyte.gz
0%| | 0/5148 [00:00<?, ?it/s]
Extracting data/FashionMNIST/raw/t10k-labels-idx1-ubyte.gz to data/FashionMNIST/raw
In [8]:
# See first training sample
image, label = train_data[0]
print(f"Image shape: {image.shape} -> [batch, height, width]")
print(f"Label: {label}") # label is an int rather than a tensor (it has no shape attribute)Image shape: torch.Size([1, 28, 28]) -> [batch, height, width] Label: 9
In [9]:
# See class names and number of classes
class_names = train_data.classes
num_classes = len(class_names)
class_names, num_classesOut [9]:
(['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'], 10)
In [10]:
# Plot a sample
import matplotlib.pyplot as plt
plt.imshow(image.squeeze(), cmap="gray") # plot image as grayscale
plt.axis(False)
plt.title(class_names[label]);In [11]:
from torch import nn
# Create a two layer neural network
model_0 = nn.Sequential(
nn.Linear(in_features=10, out_features=10),
nn.Linear(in_features=10, out_features=10)
)
# Pass the image through the model (this will error)
model_0(image)[0;31m---------------------------------------------------------------------------[0m [0;31mRuntimeError[0m Traceback (most recent call last) Input [0;32mIn [11][0m, in [0;36m<cell line: 10>[0;34m()[0m [1;32m 4[0m model_0 [38;5;241m=[39m nn[38;5;241m.[39mSequential( [1;32m 5[0m nn[38;5;241m.[39mLinear(in_features[38;5;241m=[39m[38;5;241m10[39m, out_features[38;5;241m=[39m[38;5;241m10[39m), [1;32m 6[0m nn[38;5;241m.[39mLinear(in_features[38;5;241m=[39m[38;5;241m10[39m, out_features[38;5;241m=[39m[38;5;241m10[39m) [1;32m 7[0m ) [1;32m 9[0m [38;5;66;03m# Pass the image through the model (this will error)[39;00m [0;32m---> 10[0m [43mmodel_0[49m[43m([49m[43mimage[49m[43m)[49m File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/module.py:1130[0m, in [0;36mModule._call_impl[0;34m(self, *input, **kwargs)[0m [1;32m 1126[0m [38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in[39;00m [1;32m 1127[0m [38;5;66;03m# this function, and just call forward.[39;00m [1;32m 1128[0m [38;5;28;01mif[39;00m [38;5;129;01mnot[39;00m ([38;5;28mself[39m[38;5;241m.[39m_backward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_pre_hooks [38;5;129;01mor[39;00m _global_backward_hooks [1;32m 1129[0m [38;5;129;01mor[39;00m _global_forward_hooks [38;5;129;01mor[39;00m _global_forward_pre_hooks): [0;32m-> 1130[0m [38;5;28;01mreturn[39;00m [43mforward_call[49m[43m([49m[38;5;241;43m*[39;49m[38;5;28;43minput[39;49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwargs[49m[43m)[49m [1;32m 1131[0m [38;5;66;03m# Do not call functions when jit is used[39;00m [1;32m 1132[0m full_backward_hooks, non_full_backward_hooks [38;5;241m=[39m [], [] File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/container.py:139[0m, in [0;36mSequential.forward[0;34m(self, input)[0m [1;32m 137[0m [38;5;28;01mdef[39;00m [38;5;21mforward[39m([38;5;28mself[39m, [38;5;28minput[39m): [1;32m 138[0m [38;5;28;01mfor[39;00m module [38;5;129;01min[39;00m [38;5;28mself[39m: [0;32m--> 139[0m [38;5;28minput[39m [38;5;241m=[39m [43mmodule[49m[43m([49m[38;5;28;43minput[39;49m[43m)[49m [1;32m 140[0m [38;5;28;01mreturn[39;00m [38;5;28minput[39m File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/module.py:1130[0m, in [0;36mModule._call_impl[0;34m(self, *input, **kwargs)[0m [1;32m 1126[0m [38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in[39;00m [1;32m 1127[0m [38;5;66;03m# this function, and just call forward.[39;00m [1;32m 1128[0m [38;5;28;01mif[39;00m [38;5;129;01mnot[39;00m ([38;5;28mself[39m[38;5;241m.[39m_backward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_pre_hooks [38;5;129;01mor[39;00m _global_backward_hooks [1;32m 1129[0m [38;5;129;01mor[39;00m _global_forward_hooks [38;5;129;01mor[39;00m _global_forward_pre_hooks): [0;32m-> 1130[0m [38;5;28;01mreturn[39;00m [43mforward_call[49m[43m([49m[38;5;241;43m*[39;49m[38;5;28;43minput[39;49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwargs[49m[43m)[49m [1;32m 1131[0m [38;5;66;03m# Do not call functions when jit is used[39;00m [1;32m 1132[0m full_backward_hooks, non_full_backward_hooks [38;5;241m=[39m [], [] File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/linear.py:114[0m, in [0;36mLinear.forward[0;34m(self, input)[0m [1;32m 113[0m [38;5;28;01mdef[39;00m [38;5;21mforward[39m([38;5;28mself[39m, [38;5;28minput[39m: Tensor) [38;5;241m-[39m[38;5;241m>[39m Tensor: [0;32m--> 114[0m [38;5;28;01mreturn[39;00m [43mF[49m[38;5;241;43m.[39;49m[43mlinear[49m[43m([49m[38;5;28;43minput[39;49m[43m,[49m[43m [49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mweight[49m[43m,[49m[43m [49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mbias[49m[43m)[49m [0;31mRuntimeError[0m: mat1 and mat2 shapes cannot be multiplied (28x28 and 10x10)
In [12]:
# Create a flatten layer
flatten = nn.Flatten()
# Pass the image through the flatten layer
flattened_image = flatten(image)
# Print out the image shape before and after
print(f"Before flatten shape: {image.shape} -> [batch, height, width]")
print(f"After flatten shape: {flattened_image.shape} -> [batch, height*width]")Before flatten shape: torch.Size([1, 28, 28]) -> [batch, height, width] After flatten shape: torch.Size([1, 784]) -> [batch, height*width]
In [13]:
# Replicate model_0 except add a nn.Flatten() layer to begin with
model_1 = nn.Sequential(
nn.Flatten(), # <-- NEW: add nn.Flatten() layer
nn.Linear(in_features=10, out_features=10),
nn.Linear(in_features=10, out_features=10)
)
# Pass the image through the model
model_1(image)[0;31m---------------------------------------------------------------------------[0m [0;31mRuntimeError[0m Traceback (most recent call last) Input [0;32mIn [13][0m, in [0;36m<cell line: 9>[0;34m()[0m [1;32m 2[0m model_1 [38;5;241m=[39m nn[38;5;241m.[39mSequential( [1;32m 3[0m nn[38;5;241m.[39mFlatten(), [38;5;66;03m# <-- NEW: add nn.Flatten() layer[39;00m [1;32m 4[0m nn[38;5;241m.[39mLinear(in_features[38;5;241m=[39m[38;5;241m10[39m, out_features[38;5;241m=[39m[38;5;241m10[39m), [1;32m 5[0m nn[38;5;241m.[39mLinear(in_features[38;5;241m=[39m[38;5;241m10[39m, out_features[38;5;241m=[39m[38;5;241m10[39m) [1;32m 6[0m ) [1;32m 8[0m [38;5;66;03m# Pass the image through the model[39;00m [0;32m----> 9[0m [43mmodel_1[49m[43m([49m[43mimage[49m[43m)[49m File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/module.py:1130[0m, in [0;36mModule._call_impl[0;34m(self, *input, **kwargs)[0m [1;32m 1126[0m [38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in[39;00m [1;32m 1127[0m [38;5;66;03m# this function, and just call forward.[39;00m [1;32m 1128[0m [38;5;28;01mif[39;00m [38;5;129;01mnot[39;00m ([38;5;28mself[39m[38;5;241m.[39m_backward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_pre_hooks [38;5;129;01mor[39;00m _global_backward_hooks [1;32m 1129[0m [38;5;129;01mor[39;00m _global_forward_hooks [38;5;129;01mor[39;00m _global_forward_pre_hooks): [0;32m-> 1130[0m [38;5;28;01mreturn[39;00m [43mforward_call[49m[43m([49m[38;5;241;43m*[39;49m[38;5;28;43minput[39;49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwargs[49m[43m)[49m [1;32m 1131[0m [38;5;66;03m# Do not call functions when jit is used[39;00m [1;32m 1132[0m full_backward_hooks, non_full_backward_hooks [38;5;241m=[39m [], [] File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/container.py:139[0m, in [0;36mSequential.forward[0;34m(self, input)[0m [1;32m 137[0m [38;5;28;01mdef[39;00m [38;5;21mforward[39m([38;5;28mself[39m, [38;5;28minput[39m): [1;32m 138[0m [38;5;28;01mfor[39;00m module [38;5;129;01min[39;00m [38;5;28mself[39m: [0;32m--> 139[0m [38;5;28minput[39m [38;5;241m=[39m [43mmodule[49m[43m([49m[38;5;28;43minput[39;49m[43m)[49m [1;32m 140[0m [38;5;28;01mreturn[39;00m [38;5;28minput[39m File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/module.py:1130[0m, in [0;36mModule._call_impl[0;34m(self, *input, **kwargs)[0m [1;32m 1126[0m [38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in[39;00m [1;32m 1127[0m [38;5;66;03m# this function, and just call forward.[39;00m [1;32m 1128[0m [38;5;28;01mif[39;00m [38;5;129;01mnot[39;00m ([38;5;28mself[39m[38;5;241m.[39m_backward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_pre_hooks [38;5;129;01mor[39;00m _global_backward_hooks [1;32m 1129[0m [38;5;129;01mor[39;00m _global_forward_hooks [38;5;129;01mor[39;00m _global_forward_pre_hooks): [0;32m-> 1130[0m [38;5;28;01mreturn[39;00m [43mforward_call[49m[43m([49m[38;5;241;43m*[39;49m[38;5;28;43minput[39;49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwargs[49m[43m)[49m [1;32m 1131[0m [38;5;66;03m# Do not call functions when jit is used[39;00m [1;32m 1132[0m full_backward_hooks, non_full_backward_hooks [38;5;241m=[39m [], [] File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/linear.py:114[0m, in [0;36mLinear.forward[0;34m(self, input)[0m [1;32m 113[0m [38;5;28;01mdef[39;00m [38;5;21mforward[39m([38;5;28mself[39m, [38;5;28minput[39m: Tensor) [38;5;241m-[39m[38;5;241m>[39m Tensor: [0;32m--> 114[0m [38;5;28;01mreturn[39;00m [43mF[49m[38;5;241;43m.[39;49m[43mlinear[49m[43m([49m[38;5;28;43minput[39;49m[43m,[49m[43m [49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mweight[49m[43m,[49m[43m [49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mbias[49m[43m)[49m [0;31mRuntimeError[0m: mat1 and mat2 shapes cannot be multiplied (1x784 and 10x10)
In [14]:
# Flatten the input as well as make sure the first layer can accept the flattened input shape
model_2 = nn.Sequential(
nn.Flatten(),
nn.Linear(in_features=784, out_features=10), # <-- NEW: change in_features=10 to in_features=784
nn.Linear(in_features=10, out_features=10)
)
# Pass the image through the model
model_2(image)Out [14]:
tensor([[-0.2045, 0.2677, -0.0713, -0.3096, -0.0586, 0.3153, -0.3413, 0.2031,
0.4421, 0.1715]], grad_fn=<AddmmBackward0>)In [15]:
# Create a model with incorrect input and output shapes between layers
model_3 = nn.Sequential(
nn.Flatten(),
nn.Linear(in_features=784, out_features=10), # out_features=10
nn.Linear(in_features=5, out_features=10) # <-- NEW: in_features does not match the out_features of the previous layer
)
# Pass the image through the model (this will error)
model_3(image)[0;31m---------------------------------------------------------------------------[0m [0;31mRuntimeError[0m Traceback (most recent call last) Input [0;32mIn [15][0m, in [0;36m<cell line: 9>[0;34m()[0m [1;32m 2[0m model_3 [38;5;241m=[39m nn[38;5;241m.[39mSequential( [1;32m 3[0m nn[38;5;241m.[39mFlatten(), [1;32m 4[0m nn[38;5;241m.[39mLinear(in_features[38;5;241m=[39m[38;5;241m784[39m, out_features[38;5;241m=[39m[38;5;241m10[39m), [38;5;66;03m# out_features=10 [39;00m [1;32m 5[0m nn[38;5;241m.[39mLinear(in_features[38;5;241m=[39m[38;5;241m5[39m, out_features[38;5;241m=[39m[38;5;241m10[39m) [38;5;66;03m# <-- NEW: in_features does not match the out_features of the previous layer[39;00m [1;32m 6[0m ) [1;32m 8[0m [38;5;66;03m# Pass the image through the model (this will error)[39;00m [0;32m----> 9[0m [43mmodel_3[49m[43m([49m[43mimage[49m[43m)[49m File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/module.py:1130[0m, in [0;36mModule._call_impl[0;34m(self, *input, **kwargs)[0m [1;32m 1126[0m [38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in[39;00m [1;32m 1127[0m [38;5;66;03m# this function, and just call forward.[39;00m [1;32m 1128[0m [38;5;28;01mif[39;00m [38;5;129;01mnot[39;00m ([38;5;28mself[39m[38;5;241m.[39m_backward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_pre_hooks [38;5;129;01mor[39;00m _global_backward_hooks [1;32m 1129[0m [38;5;129;01mor[39;00m _global_forward_hooks [38;5;129;01mor[39;00m _global_forward_pre_hooks): [0;32m-> 1130[0m [38;5;28;01mreturn[39;00m [43mforward_call[49m[43m([49m[38;5;241;43m*[39;49m[38;5;28;43minput[39;49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwargs[49m[43m)[49m [1;32m 1131[0m [38;5;66;03m# Do not call functions when jit is used[39;00m [1;32m 1132[0m full_backward_hooks, non_full_backward_hooks [38;5;241m=[39m [], [] File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/container.py:139[0m, in [0;36mSequential.forward[0;34m(self, input)[0m [1;32m 137[0m [38;5;28;01mdef[39;00m [38;5;21mforward[39m([38;5;28mself[39m, [38;5;28minput[39m): [1;32m 138[0m [38;5;28;01mfor[39;00m module [38;5;129;01min[39;00m [38;5;28mself[39m: [0;32m--> 139[0m [38;5;28minput[39m [38;5;241m=[39m [43mmodule[49m[43m([49m[38;5;28;43minput[39;49m[43m)[49m [1;32m 140[0m [38;5;28;01mreturn[39;00m [38;5;28minput[39m File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/module.py:1130[0m, in [0;36mModule._call_impl[0;34m(self, *input, **kwargs)[0m [1;32m 1126[0m [38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in[39;00m [1;32m 1127[0m [38;5;66;03m# this function, and just call forward.[39;00m [1;32m 1128[0m [38;5;28;01mif[39;00m [38;5;129;01mnot[39;00m ([38;5;28mself[39m[38;5;241m.[39m_backward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_pre_hooks [38;5;129;01mor[39;00m _global_backward_hooks [1;32m 1129[0m [38;5;129;01mor[39;00m _global_forward_hooks [38;5;129;01mor[39;00m _global_forward_pre_hooks): [0;32m-> 1130[0m [38;5;28;01mreturn[39;00m [43mforward_call[49m[43m([49m[38;5;241;43m*[39;49m[38;5;28;43minput[39;49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwargs[49m[43m)[49m [1;32m 1131[0m [38;5;66;03m# Do not call functions when jit is used[39;00m [1;32m 1132[0m full_backward_hooks, non_full_backward_hooks [38;5;241m=[39m [], [] File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/linear.py:114[0m, in [0;36mLinear.forward[0;34m(self, input)[0m [1;32m 113[0m [38;5;28;01mdef[39;00m [38;5;21mforward[39m([38;5;28mself[39m, [38;5;28minput[39m: Tensor) [38;5;241m-[39m[38;5;241m>[39m Tensor: [0;32m--> 114[0m [38;5;28;01mreturn[39;00m [43mF[49m[38;5;241;43m.[39;49m[43mlinear[49m[43m([49m[38;5;28;43minput[39;49m[43m,[49m[43m [49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mweight[49m[43m,[49m[43m [49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mbias[49m[43m)[49m [0;31mRuntimeError[0m: mat1 and mat2 shapes cannot be multiplied (1x10 and 5x10)
In [16]:
# Try nn.LazyLinear() as the second layer
model_4 = nn.Sequential(
nn.Flatten(),
nn.Linear(in_features=784, out_features=10),
nn.LazyLinear(out_features=10) # <-- NEW: no in_features parameter as this is inferred from the previous layer's output
)
# Pass the image through the model
model_4(image)Out [16]:
/home/daniel/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/lazy.py:178: UserWarning: Lazy modules are a new feature under heavy development so changes to the API or functionality can happen at any moment.
warnings.warn('Lazy modules are a new feature under heavy development '
tensor([[ 0.4282, 0.2492, -0.2045, -0.4943, -0.1639, 0.1166, 0.3828, -0.1283,
-0.1771, -0.2277]], grad_fn=<AddmmBackward0>)In [18]:
# Replace all nn.Linear() layers with nn.LazyLinear()
model_5 = nn.Sequential(
nn.Flatten(),
nn.LazyLinear(out_features=10),
nn.LazyLinear(out_features=10) # <-- NEW
)
# Pass the image through the model
model_5(image)Out [18]:
tensor([[ 0.1375, -0.2175, -0.1054, 0.1424, -0.1406, -0.1180, -0.0896, -0.4285,
-0.0077, -0.3188]], grad_fn=<AddmmBackward0>)In [19]:
import torch
# Set device to "cuda" if it's available otherwise default to "cpu"
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Current device: {device}")Current device: cuda
In [20]:
from torch import nn
# Create a model (similar to model_5 above)
model_6 = nn.Sequential(
nn.Flatten(),
nn.LazyLinear(out_features=10),
nn.LazyLinear(out_features=10)
)
# All models and tensors are created on the CPU by default (unless explicitly set otherwise)
print(f"Model is on device: {next(model_6.parameters()).device}")Model is on device: cpu
In [21]:
from torch.utils.data import DataLoader, RandomSampler
# Only sample 10% of the data
train_sampler = RandomSampler(train_data,
num_samples=int(0.1*len(train_data)))
test_sampler = RandomSampler(test_data,
num_samples=int(0.1*len(test_data)))
print(f"Number of random training samples selected: {len(train_sampler)}/{len(train_data)}")
print(f"Number of random testing samples selected: {len(test_sampler)}/{len(test_data)}")
# Create DataLoaders and turn data into batches
BATCH_SIZE = 32
train_dataloader = DataLoader(dataset=train_data,
batch_size=BATCH_SIZE,
sampler=train_sampler)
test_dataloader = DataLoader(dataset=test_data,
batch_size=BATCH_SIZE,
sampler=test_sampler)
print(f"Number of batches in train_dataloader: {len(train_dataloader)} batches of size {BATCH_SIZE}")
print(f"Number of batches in test_dataloader: {len(test_dataloader)} batch of size {BATCH_SIZE}")
# Create loss function
loss_fn = nn.CrossEntropyLoss()
# Create optimizer
optimizer = torch.optim.SGD(lr=0.01,
params=model_6.parameters())Number of random training samples selected: 6000/60000 Number of random testing samples selected: 1000/10000 Number of batches in train_dataloader: 188 batches of size 32 Number of batches in test_dataloader: 32 batch of size 32
In [22]:
from tqdm.auto import tqdm
# Set the number of epochs
epochs = 5
# Train the model
for epoch in tqdm(range(epochs)):
# Set loss to 0 every epoch
train_loss = 0
# Get images (X) and labels (y)
for X, y in train_dataloader:
# Forward pass
y_pred = model_6(X)
# Calculate the loss
loss = loss_fn(y_pred, y)
train_loss += loss
# Optimizer zero grad
optimizer.zero_grad()
# Loss backward
loss.backward()
# Optimizer step
optimizer.step()
# Print loss in the epoch loop only
print(f"Epoch: {epoch} | Training loss: {train_loss:.2f}")0%| | 0/5 [00:00<?, ?it/s]
Epoch: 0 | Training loss: 334.65 Epoch: 1 | Training loss: 215.44 Epoch: 2 | Training loss: 171.15 Epoch: 3 | Training loss: 154.72 Epoch: 4 | Training loss: 142.22
In [23]:
# Send model_6 to the target device ("cuda")
model_6.to(device)
# Print out what device the model is on
print(f"Model is on device: {next(model_6.parameters()).device}")Model is on device: cuda:0
In [24]:
from tqdm.auto import tqdm
# Set the number of epochs
epochs = 5
# Train the model
for epoch in tqdm(range(epochs)):
# Set loss to 0 every epoch
train_loss = 0
# Get images (X) and labels (y)
for X, y in train_dataloader:
# Forward pass
y_pred = model_6(X) # model is on GPU, data is on CPU (will error)
# Calculate the loss
loss = loss_fn(y_pred, y)
train_loss += loss
# Optimizer zero grad
optimizer.zero_grad()
# Loss backward
loss.backward()
# Optimizer step
optimizer.step()
# Print loss in the epoch loop only
print(f"Epoch: {epoch} | Training loss: {train_loss:.2f}")0%| | 0/5 [00:00<?, ?it/s]
[0;31m---------------------------------------------------------------------------[0m [0;31mRuntimeError[0m Traceback (most recent call last) Input [0;32mIn [24][0m, in [0;36m<cell line: 7>[0;34m()[0m [1;32m 12[0m [38;5;66;03m# Get images (X) and labels (y)[39;00m [1;32m 13[0m [38;5;28;01mfor[39;00m X, y [38;5;129;01min[39;00m train_dataloader: [1;32m 14[0m [1;32m 15[0m [38;5;66;03m# Forward pass[39;00m [0;32m---> 16[0m y_pred [38;5;241m=[39m [43mmodel_6[49m[43m([49m[43mX[49m[43m)[49m [38;5;66;03m# model is on GPU, data is on CPU (will error)[39;00m [1;32m 18[0m [38;5;66;03m# Calculate the loss[39;00m [1;32m 19[0m loss [38;5;241m=[39m loss_fn(y_pred, y) File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/module.py:1130[0m, in [0;36mModule._call_impl[0;34m(self, *input, **kwargs)[0m [1;32m 1126[0m [38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in[39;00m [1;32m 1127[0m [38;5;66;03m# this function, and just call forward.[39;00m [1;32m 1128[0m [38;5;28;01mif[39;00m [38;5;129;01mnot[39;00m ([38;5;28mself[39m[38;5;241m.[39m_backward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_pre_hooks [38;5;129;01mor[39;00m _global_backward_hooks [1;32m 1129[0m [38;5;129;01mor[39;00m _global_forward_hooks [38;5;129;01mor[39;00m _global_forward_pre_hooks): [0;32m-> 1130[0m [38;5;28;01mreturn[39;00m [43mforward_call[49m[43m([49m[38;5;241;43m*[39;49m[38;5;28;43minput[39;49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwargs[49m[43m)[49m [1;32m 1131[0m [38;5;66;03m# Do not call functions when jit is used[39;00m [1;32m 1132[0m full_backward_hooks, non_full_backward_hooks [38;5;241m=[39m [], [] File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/container.py:139[0m, in [0;36mSequential.forward[0;34m(self, input)[0m [1;32m 137[0m [38;5;28;01mdef[39;00m [38;5;21mforward[39m([38;5;28mself[39m, [38;5;28minput[39m): [1;32m 138[0m [38;5;28;01mfor[39;00m module [38;5;129;01min[39;00m [38;5;28mself[39m: [0;32m--> 139[0m [38;5;28minput[39m [38;5;241m=[39m [43mmodule[49m[43m([49m[38;5;28;43minput[39;49m[43m)[49m [1;32m 140[0m [38;5;28;01mreturn[39;00m [38;5;28minput[39m File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/module.py:1130[0m, in [0;36mModule._call_impl[0;34m(self, *input, **kwargs)[0m [1;32m 1126[0m [38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in[39;00m [1;32m 1127[0m [38;5;66;03m# this function, and just call forward.[39;00m [1;32m 1128[0m [38;5;28;01mif[39;00m [38;5;129;01mnot[39;00m ([38;5;28mself[39m[38;5;241m.[39m_backward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_pre_hooks [38;5;129;01mor[39;00m _global_backward_hooks [1;32m 1129[0m [38;5;129;01mor[39;00m _global_forward_hooks [38;5;129;01mor[39;00m _global_forward_pre_hooks): [0;32m-> 1130[0m [38;5;28;01mreturn[39;00m [43mforward_call[49m[43m([49m[38;5;241;43m*[39;49m[38;5;28;43minput[39;49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwargs[49m[43m)[49m [1;32m 1131[0m [38;5;66;03m# Do not call functions when jit is used[39;00m [1;32m 1132[0m full_backward_hooks, non_full_backward_hooks [38;5;241m=[39m [], [] File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/linear.py:114[0m, in [0;36mLinear.forward[0;34m(self, input)[0m [1;32m 113[0m [38;5;28;01mdef[39;00m [38;5;21mforward[39m([38;5;28mself[39m, [38;5;28minput[39m: Tensor) [38;5;241m-[39m[38;5;241m>[39m Tensor: [0;32m--> 114[0m [38;5;28;01mreturn[39;00m [43mF[49m[38;5;241;43m.[39;49m[43mlinear[49m[43m([49m[38;5;28;43minput[39;49m[43m,[49m[43m [49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mweight[49m[43m,[49m[43m [49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mbias[49m[43m)[49m [0;31mRuntimeError[0m: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! (when checking argument for argument mat1 in method wrapper_addmm)
In [25]:
# Send the model to the target device (we don't need to do this again but we will for completeness)
model_6.to(device)
# Set the number of epochs
epochs = 5
# Train the model
for epoch in tqdm(range(epochs)):
# Set loss to 0 every epoch
train_loss = 0
# Get images (X) and labels (y)
for X, y in train_dataloader:
# Put target data on target device <-- NEW
X, y = X.to(device), y.to(device) # <-- NEW: send data to target device
# Forward pass
y_pred = model_6(X)
# Calculate the loss
loss = loss_fn(y_pred, y)
train_loss += loss
# Optimizer zero grad
optimizer.zero_grad()
# Loss backward
loss.backward()
# Optimizer step
optimizer.step()
# Print loss in the epoch loop only
print(f"Epoch: {epoch} | Training loss: {train_loss:.2f}")0%| | 0/5 [00:00<?, ?it/s]
Epoch: 0 | Training loss: 134.76 Epoch: 1 | Training loss: 127.76 Epoch: 2 | Training loss: 120.85 Epoch: 3 | Training loss: 120.50 Epoch: 4 | Training loss: 116.29
In [26]:
# Get a single sample from the test dataset
test_image, test_label = test_data.data[0], test_data.targets[0]
print(f"Test image shape: {test_image.shape}")
print(f"Test image label: {test_label}")Test image shape: torch.Size([28, 28]) Test image label: 9
In [27]:
# Plot test image
import matplotlib.pyplot as plt
plt.imshow(test_image, cmap="gray")
plt.axis(False)
plt.title(class_names[test_label]);In [28]:
# Pass the test image through model_6 to make a prediction
model_6(test_image)[0;31m---------------------------------------------------------------------------[0m [0;31mRuntimeError[0m Traceback (most recent call last) Input [0;32mIn [28][0m, in [0;36m<cell line: 2>[0;34m()[0m [1;32m 1[0m [38;5;66;03m# Pass the test image through model_6 to make a prediction[39;00m [0;32m----> 2[0m [43mmodel_6[49m[43m([49m[43mtest_image[49m[43m)[49m File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/module.py:1130[0m, in [0;36mModule._call_impl[0;34m(self, *input, **kwargs)[0m [1;32m 1126[0m [38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in[39;00m [1;32m 1127[0m [38;5;66;03m# this function, and just call forward.[39;00m [1;32m 1128[0m [38;5;28;01mif[39;00m [38;5;129;01mnot[39;00m ([38;5;28mself[39m[38;5;241m.[39m_backward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_pre_hooks [38;5;129;01mor[39;00m _global_backward_hooks [1;32m 1129[0m [38;5;129;01mor[39;00m _global_forward_hooks [38;5;129;01mor[39;00m _global_forward_pre_hooks): [0;32m-> 1130[0m [38;5;28;01mreturn[39;00m [43mforward_call[49m[43m([49m[38;5;241;43m*[39;49m[38;5;28;43minput[39;49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwargs[49m[43m)[49m [1;32m 1131[0m [38;5;66;03m# Do not call functions when jit is used[39;00m [1;32m 1132[0m full_backward_hooks, non_full_backward_hooks [38;5;241m=[39m [], [] File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/container.py:139[0m, in [0;36mSequential.forward[0;34m(self, input)[0m [1;32m 137[0m [38;5;28;01mdef[39;00m [38;5;21mforward[39m([38;5;28mself[39m, [38;5;28minput[39m): [1;32m 138[0m [38;5;28;01mfor[39;00m module [38;5;129;01min[39;00m [38;5;28mself[39m: [0;32m--> 139[0m [38;5;28minput[39m [38;5;241m=[39m [43mmodule[49m[43m([49m[38;5;28;43minput[39;49m[43m)[49m [1;32m 140[0m [38;5;28;01mreturn[39;00m [38;5;28minput[39m File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/module.py:1130[0m, in [0;36mModule._call_impl[0;34m(self, *input, **kwargs)[0m [1;32m 1126[0m [38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in[39;00m [1;32m 1127[0m [38;5;66;03m# this function, and just call forward.[39;00m [1;32m 1128[0m [38;5;28;01mif[39;00m [38;5;129;01mnot[39;00m ([38;5;28mself[39m[38;5;241m.[39m_backward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_pre_hooks [38;5;129;01mor[39;00m _global_backward_hooks [1;32m 1129[0m [38;5;129;01mor[39;00m _global_forward_hooks [38;5;129;01mor[39;00m _global_forward_pre_hooks): [0;32m-> 1130[0m [38;5;28;01mreturn[39;00m [43mforward_call[49m[43m([49m[38;5;241;43m*[39;49m[38;5;28;43minput[39;49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwargs[49m[43m)[49m [1;32m 1131[0m [38;5;66;03m# Do not call functions when jit is used[39;00m [1;32m 1132[0m full_backward_hooks, non_full_backward_hooks [38;5;241m=[39m [], [] File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/linear.py:114[0m, in [0;36mLinear.forward[0;34m(self, input)[0m [1;32m 113[0m [38;5;28;01mdef[39;00m [38;5;21mforward[39m([38;5;28mself[39m, [38;5;28minput[39m: Tensor) [38;5;241m-[39m[38;5;241m>[39m Tensor: [0;32m--> 114[0m [38;5;28;01mreturn[39;00m [43mF[49m[38;5;241;43m.[39;49m[43mlinear[49m[43m([49m[38;5;28;43minput[39;49m[43m,[49m[43m [49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mweight[49m[43m,[49m[43m [49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mbias[49m[43m)[49m [0;31mRuntimeError[0m: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! (when checking argument for argument mat1 in method wrapper_addmm)
In [30]:
# Send test_image to target device
model_6(test_image.to(device))[0;31m---------------------------------------------------------------------------[0m [0;31mRuntimeError[0m Traceback (most recent call last) Input [0;32mIn [30][0m, in [0;36m<cell line: 2>[0;34m()[0m [1;32m 1[0m [38;5;66;03m# Send test_image to target device[39;00m [0;32m----> 2[0m [43mmodel_6[49m[43m([49m[43mtest_image[49m[38;5;241;43m.[39;49m[43mto[49m[43m([49m[43mdevice[49m[43m)[49m[43m)[49m File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/module.py:1130[0m, in [0;36mModule._call_impl[0;34m(self, *input, **kwargs)[0m [1;32m 1126[0m [38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in[39;00m [1;32m 1127[0m [38;5;66;03m# this function, and just call forward.[39;00m [1;32m 1128[0m [38;5;28;01mif[39;00m [38;5;129;01mnot[39;00m ([38;5;28mself[39m[38;5;241m.[39m_backward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_pre_hooks [38;5;129;01mor[39;00m _global_backward_hooks [1;32m 1129[0m [38;5;129;01mor[39;00m _global_forward_hooks [38;5;129;01mor[39;00m _global_forward_pre_hooks): [0;32m-> 1130[0m [38;5;28;01mreturn[39;00m [43mforward_call[49m[43m([49m[38;5;241;43m*[39;49m[38;5;28;43minput[39;49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwargs[49m[43m)[49m [1;32m 1131[0m [38;5;66;03m# Do not call functions when jit is used[39;00m [1;32m 1132[0m full_backward_hooks, non_full_backward_hooks [38;5;241m=[39m [], [] File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/container.py:139[0m, in [0;36mSequential.forward[0;34m(self, input)[0m [1;32m 137[0m [38;5;28;01mdef[39;00m [38;5;21mforward[39m([38;5;28mself[39m, [38;5;28minput[39m): [1;32m 138[0m [38;5;28;01mfor[39;00m module [38;5;129;01min[39;00m [38;5;28mself[39m: [0;32m--> 139[0m [38;5;28minput[39m [38;5;241m=[39m [43mmodule[49m[43m([49m[38;5;28;43minput[39;49m[43m)[49m [1;32m 140[0m [38;5;28;01mreturn[39;00m [38;5;28minput[39m File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/module.py:1130[0m, in [0;36mModule._call_impl[0;34m(self, *input, **kwargs)[0m [1;32m 1126[0m [38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in[39;00m [1;32m 1127[0m [38;5;66;03m# this function, and just call forward.[39;00m [1;32m 1128[0m [38;5;28;01mif[39;00m [38;5;129;01mnot[39;00m ([38;5;28mself[39m[38;5;241m.[39m_backward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_pre_hooks [38;5;129;01mor[39;00m _global_backward_hooks [1;32m 1129[0m [38;5;129;01mor[39;00m _global_forward_hooks [38;5;129;01mor[39;00m _global_forward_pre_hooks): [0;32m-> 1130[0m [38;5;28;01mreturn[39;00m [43mforward_call[49m[43m([49m[38;5;241;43m*[39;49m[38;5;28;43minput[39;49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwargs[49m[43m)[49m [1;32m 1131[0m [38;5;66;03m# Do not call functions when jit is used[39;00m [1;32m 1132[0m full_backward_hooks, non_full_backward_hooks [38;5;241m=[39m [], [] File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/linear.py:114[0m, in [0;36mLinear.forward[0;34m(self, input)[0m [1;32m 113[0m [38;5;28;01mdef[39;00m [38;5;21mforward[39m([38;5;28mself[39m, [38;5;28minput[39m: Tensor) [38;5;241m-[39m[38;5;241m>[39m Tensor: [0;32m--> 114[0m [38;5;28;01mreturn[39;00m [43mF[49m[38;5;241;43m.[39;49m[43mlinear[49m[43m([49m[38;5;28;43minput[39;49m[43m,[49m[43m [49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mweight[49m[43m,[49m[43m [49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mbias[49m[43m)[49m [0;31mRuntimeError[0m: mat1 and mat2 shapes cannot be multiplied (28x28 and 784x10)
In [31]:
# Changing the input size to be the same as what the model was trained on
original_input_shape = test_image.shape
updated_input_shape = test_image.unsqueeze(dim=0).shape # adding a batch dimension on the "0th" dimension
# Print out shapes of original tensor and updated tensor
print(f"Original input data shape: {original_input_shape} -> [height, width]")
print(f"Updated input data shape (with added batch dimension): {updated_input_shape} -> [batch, height, width]")Original input data shape: torch.Size([28, 28]) -> [height, width] Updated input data shape (with added batch dimension): torch.Size([1, 28, 28]) -> [batch, height, width]
In [32]:
# Make prediction on test image with additional batch size dimension and with it on the target device
model_6(test_image.unsqueeze(dim=0).to(device))[0;31m---------------------------------------------------------------------------[0m [0;31mRuntimeError[0m Traceback (most recent call last) Input [0;32mIn [32][0m, in [0;36m<cell line: 2>[0;34m()[0m [1;32m 1[0m [38;5;66;03m# Make prediction on test image with additional batch size dimension and with it on the target device[39;00m [0;32m----> 2[0m [43mmodel_6[49m[43m([49m[43mtest_image[49m[38;5;241;43m.[39;49m[43munsqueeze[49m[43m([49m[43mdim[49m[38;5;241;43m=[39;49m[38;5;241;43m0[39;49m[43m)[49m[38;5;241;43m.[39;49m[43mto[49m[43m([49m[43mdevice[49m[43m)[49m[43m)[49m File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/module.py:1130[0m, in [0;36mModule._call_impl[0;34m(self, *input, **kwargs)[0m [1;32m 1126[0m [38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in[39;00m [1;32m 1127[0m [38;5;66;03m# this function, and just call forward.[39;00m [1;32m 1128[0m [38;5;28;01mif[39;00m [38;5;129;01mnot[39;00m ([38;5;28mself[39m[38;5;241m.[39m_backward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_pre_hooks [38;5;129;01mor[39;00m _global_backward_hooks [1;32m 1129[0m [38;5;129;01mor[39;00m _global_forward_hooks [38;5;129;01mor[39;00m _global_forward_pre_hooks): [0;32m-> 1130[0m [38;5;28;01mreturn[39;00m [43mforward_call[49m[43m([49m[38;5;241;43m*[39;49m[38;5;28;43minput[39;49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwargs[49m[43m)[49m [1;32m 1131[0m [38;5;66;03m# Do not call functions when jit is used[39;00m [1;32m 1132[0m full_backward_hooks, non_full_backward_hooks [38;5;241m=[39m [], [] File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/container.py:139[0m, in [0;36mSequential.forward[0;34m(self, input)[0m [1;32m 137[0m [38;5;28;01mdef[39;00m [38;5;21mforward[39m([38;5;28mself[39m, [38;5;28minput[39m): [1;32m 138[0m [38;5;28;01mfor[39;00m module [38;5;129;01min[39;00m [38;5;28mself[39m: [0;32m--> 139[0m [38;5;28minput[39m [38;5;241m=[39m [43mmodule[49m[43m([49m[38;5;28;43minput[39;49m[43m)[49m [1;32m 140[0m [38;5;28;01mreturn[39;00m [38;5;28minput[39m File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/module.py:1130[0m, in [0;36mModule._call_impl[0;34m(self, *input, **kwargs)[0m [1;32m 1126[0m [38;5;66;03m# If we don't have any hooks, we want to skip the rest of the logic in[39;00m [1;32m 1127[0m [38;5;66;03m# this function, and just call forward.[39;00m [1;32m 1128[0m [38;5;28;01mif[39;00m [38;5;129;01mnot[39;00m ([38;5;28mself[39m[38;5;241m.[39m_backward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_hooks [38;5;129;01mor[39;00m [38;5;28mself[39m[38;5;241m.[39m_forward_pre_hooks [38;5;129;01mor[39;00m _global_backward_hooks [1;32m 1129[0m [38;5;129;01mor[39;00m _global_forward_hooks [38;5;129;01mor[39;00m _global_forward_pre_hooks): [0;32m-> 1130[0m [38;5;28;01mreturn[39;00m [43mforward_call[49m[43m([49m[38;5;241;43m*[39;49m[38;5;28;43minput[39;49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwargs[49m[43m)[49m [1;32m 1131[0m [38;5;66;03m# Do not call functions when jit is used[39;00m [1;32m 1132[0m full_backward_hooks, non_full_backward_hooks [38;5;241m=[39m [], [] File [0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/linear.py:114[0m, in [0;36mLinear.forward[0;34m(self, input)[0m [1;32m 113[0m [38;5;28;01mdef[39;00m [38;5;21mforward[39m([38;5;28mself[39m, [38;5;28minput[39m: Tensor) [38;5;241m-[39m[38;5;241m>[39m Tensor: [0;32m--> 114[0m [38;5;28;01mreturn[39;00m [43mF[49m[38;5;241;43m.[39;49m[43mlinear[49m[43m([49m[38;5;28;43minput[39;49m[43m,[49m[43m [49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mweight[49m[43m,[49m[43m [49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mbias[49m[43m)[49m [0;31mRuntimeError[0m: expected scalar type Float but found Byte
In [33]:
# Get a single sample from the train_dataloader and print the dtype
train_image_batch, train_label_batch = next(iter(train_dataloader))
train_image_single, train_label_single = train_image_batch[0], train_label_batch[0]
# Print the datatype of the train_image_single
print(f"Datatype of training data: {train_image_single.dtype}")Datatype of training data: torch.float32
In [34]:
# Print out the original datatype of test_image
print(f"Original datatype: {test_image.unsqueeze(dim=0).dtype}")
# Change the datatype of test_image and see the change
print(f"Changing the datatype: {test_image.unsqueeze(dim=0).type(torch.float32).dtype}")Original datatype: torch.uint8 Changing the datatype: torch.float32
In [35]:
# Make a prediction with model_6 on the transformed test_image
pred_on_gpu = model_6(test_image.unsqueeze(dim=0) # add a batch dimension
.type(torch.float32) # convert the datatype to torch.float32
.to(device)) # send the tensor to the target device
pred_on_gpuOut [35]:
tensor([[ -963.8352, -1658.8182, -735.9952, -1285.2964, -550.3845, 949.4190,
-538.1960, 1123.0616, 552.7371, 1413.8110]], device='cuda:0',
grad_fn=<AddmmBackward0>)In [36]:
# Put model back on CPU
model_6.cpu()
# Make a prediction on the CPU device (no need to put test_image on the CPU as it's already there)
pred_on_cpu = model_6(test_image.unsqueeze(dim=0) # add a batch dimension
.type(torch.float32)) # convert the datatype to torch.float32
pred_on_cpuOut [36]:
tensor([[ -963.8351, -1658.8182, -735.9953, -1285.2964, -550.3845, 949.4189,
-538.1960, 1123.0615, 552.7371, 1413.8110]],
grad_fn=<AddmmBackward0>)In [37]:
# Convert raw logits to prediction probabilities
pred_probs = torch.softmax(pred_on_cpu, dim=1)
# Convert prediction probabilities to prediction label
pred_label = torch.argmax(pred_probs, dim=1)
# Check if it's correct
print(f"Test label: {test_label}")
print(f"Pred label: {pred_label}")
print(f"Is the prediction correct? {pred_label.item() == test_label}")Test label: 9 Pred label: tensor([9]) Is the prediction correct? True

