"
- ]
- },
- "metadata": {
- "needs_background": "light"
- },
- "output_type": "display_data"
- }
- ],
- "source": [
- "# Plot more images\n",
- "torch.manual_seed(42)\n",
- "fig = plt.figure(figsize=(9, 9))\n",
- "rows, cols = 4, 4\n",
- "for i in range(1, rows * cols + 1):\n",
- " random_idx = torch.randint(0, len(train_data), size=[1]).item()\n",
- " img, label = train_data[random_idx]\n",
- " fig.add_subplot(rows, cols, i)\n",
- " plt.imshow(img.squeeze(), cmap=\"gray\")\n",
- " plt.title(class_names[label])\n",
- " plt.axis(False);"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "zXeju8HKn2zR"
- },
- "source": [
- "Hmmm, this dataset doesn't look too aesthetic.\n",
- "\n",
- "But the principles we're going to learn on how to build a model for it will be similar across a wide range of computer vision problems.\n",
- "\n",
- "In essence, taking pixel values and building a model to find patterns in them to use on future pixel values.\n",
- "\n",
- "Plus, even for this small dataset (yes, even 60,000 images in deep learning is considered quite small), could you write a program to classify each one of them?\n",
- "\n",
- "You probably could.\n",
- "\n",
- "But I think coding a model in PyTorch would be faster.\n",
- "\n",
- "> **Question:** Do you think the above data can be model with only straight (linear) lines? Or do you think you'd also need non-straight (non-linear) lines?"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "Iz4RBQdSn7KI"
- },
- "source": [
- "## TK - 2. Prepare DataLoader\n",
- "\n",
- "Now we've got a dataset ready to go.\n",
- "\n",
- "The next step is to prepare it with a [`torch.utils.data.DataLoader`](https://pytorch.org/docs/stable/data.html#torch.utils.data.Dataset) or `DataLoader` for short.\n",
- "\n",
- "The `DataLoader` does what you think it might do.\n",
- "\n",
- "It helps load data into a model.\n",
- "\n",
- "For training and for inference.\n",
- "\n",
- "It turns a large `Dataset` into a Python iterable of smaller chunks.\n",
- "\n",
- "These smaller chunks are called **batches** or **mini-batches** and can be set by the `batch_size` parameter.\n",
- "\n",
- "Why do this?\n",
- "\n",
- "Because it's more computationally efficient.\n",
- "\n",
- "In an ideal world you could do the forward pass and backward pass across all of your data at once.\n",
- "\n",
- "But once you start using really large datasets, unless you've got infinite computing power, it's easier to break them up into batches.\n",
- "\n",
- "What's a good batch size?\n",
- "\n",
- "[32 is a good place to start](https://twitter.com/ylecun/status/989610208497360896?s=20&t=N96J_jotN--PYuJk2WcjMw) for a fair amount of problems.\n",
- "\n",
- "But since this is a value you can set (a **hyperparameter**) you can try all different kinds of values, though generally powers of 2 are used most often (e.g. 32, 64, 128, 256, 512).\n",
- "\n",
- "\n",
- "*Batching FashionMNIST with a batch size of 32 and shuffle turned on. A similar batching process will occur for other datasets but will differ depending on the batch size.*\n",
- "\n",
- "Let's create `DataLoader`'s for our training and test sets. "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 11,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "sBuS99vwn1Zj",
- "outputId": "2d3ebf65-f5b6-49fd-bfaa-d5ad59b65241"
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Dataloaders: (, )\n",
- "Length of train dataloader: 1875 batches of 32\n",
- "Length of test dataloader: 313 batches of 32\n"
- ]
- }
- ],
- "source": [
- "from torch.utils.data import DataLoader\n",
- "\n",
- "# Setup the batch size hyperparameter\n",
- "BATCH_SIZE = 32\n",
- "\n",
- "# Turn datasets into iterables (batches)\n",
- "train_dataloader = DataLoader(train_data, # dataset to turn into iterable\n",
- " batch_size=BATCH_SIZE, # how many samples per batch? \n",
- " shuffle=True # shuffle data every epoch?\n",
- ")\n",
- "\n",
- "test_dataloader = DataLoader(test_data,\n",
- " batch_size=BATCH_SIZE,\n",
- " shuffle=False # don't necessarily have to shuffle the testing data\n",
- ")\n",
- "\n",
- "# Let's check out what we've created\n",
- "print(f\"Dataloaders: {train_dataloader, test_dataloader}\") \n",
- "print(f\"Length of train dataloader: {len(train_dataloader)} batches of {BATCH_SIZE}\")\n",
- "print(f\"Length of test dataloader: {len(test_dataloader)} batches of {BATCH_SIZE}\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "Cs5cbkBCn-9r"
- },
- "source": [
- "Since the `DataLoader`'s are Python iterables, we can check out what's inside using `next(iter(dataloader))`."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 12,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "5n_avEfdn95y",
- "outputId": "51f80005-37eb-4a1d-a4e9-72f329d4d491"
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "(torch.Size([32, 1, 28, 28]), torch.Size([32]))"
- ]
- },
- "execution_count": 12,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "# Check out what's inside the training dataloader\n",
- "train_features_batch, train_labels_batch = next(iter(train_dataloader))\n",
- "train_features_batch.shape, train_labels_batch.shape"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "cjYDKpxSoDW3"
- },
- "source": [
- "And we can see that the data remains unchanged by checking a single sample. "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 13,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/",
- "height": 299
- },
- "id": "TEDUXasFoB8g",
- "outputId": "0bb8e593-0d83-4f3c-91cf-29613d45081f"
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Image size: torch.Size([1, 28, 28])\n",
- "Label: 6, label size: torch.Size([])\n"
- ]
- },
- {
- "data": {
- "image/png": "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",
- "text/plain": [
- "
"
- ]
- },
- "metadata": {
- "needs_background": "light"
- },
- "output_type": "display_data"
- }
- ],
- "source": [
- "# Show a sample\n",
- "torch.manual_seed(42)\n",
- "random_idx = torch.randint(0, len(train_features_batch), size=[1]).item()\n",
- "img, label = train_features_batch[random_idx], train_labels_batch[random_idx]\n",
- "plt.imshow(img.squeeze(), cmap=\"gray\")\n",
- "plt.title(class_names[label])\n",
- "plt.axis(\"Off\");\n",
- "print(f\"Image size: {img.shape}\")\n",
- "print(f\"Label: {label}, label size: {label.shape}\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "ZFE2uFRDoHTB"
- },
- "source": [
- "## TK - 3. Model 0: Build a baseline model\n",
- "\n",
- "Data loaded and prepared!\n",
- "\n",
- "Time to build a **baseline model** by subclassing `nn.Module`.\n",
- "\n",
- "A **baseline model** is one of the simplest models you can imagine.\n",
- "\n",
- "You use the baseline as a starting point and try to improve upon it with subsequent, more complicated models.\n",
- "\n",
- "Our baseline will consist of two [`nn.Linear()`](https://pytorch.org/docs/stable/generated/torch.nn.Linear.html) layers.\n",
- "\n",
- "We've done this in a previous section but there's going to one slight difference.\n",
- "\n",
- "Because we're working with image data, we're going to use a different layer to start things off.\n",
- "\n",
- "And that's the [`nn.Flatten()`](https://pytorch.org/docs/stable/generated/torch.nn.Flatten.html) layer.\n",
- "\n",
- "`nn.Flatten()` compresses the dimensions of a tensor into a single vector.\n",
- "\n",
- "This is easier to understand when you see it."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 14,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "jJNgcNnpoEqg",
- "outputId": "a4559d51-511c-45e5-a866-eb05e74cd39f"
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Shape before flattening: torch.Size([1, 28, 28]) -> [color_channels, height, width]\n",
- "Shape after flattening: torch.Size([1, 784]) -> [color_channels, height*width]\n"
- ]
- }
- ],
- "source": [
- "# Create a flatten layer\n",
- "flatten_model = nn.Flatten() # all nn modules function as a model (can do a forward pass)\n",
- "\n",
- "# Get a single sample\n",
- "x = train_features_batch[0]\n",
- "\n",
- "# Flatten the sample\n",
- "output = flatten_model(x) # perform forward pass\n",
- "\n",
- "# Print out what happened\n",
- "print(f\"Shape before flattening: {x.shape} -> [color_channels, height, width]\")\n",
- "print(f\"Shape after flattening: {output.shape} -> [color_channels, height*width]\")\n",
- "\n",
- "# Try uncommenting below and see what happened\n",
- "#print(x)\n",
- "#print(output)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "3gJ4ptg0oLjn"
- },
- "source": [
- "The `nn.Flatten()` layer took our shape from `[color_channels, height, width]` to `[color_channels, height*width]`.\n",
- "\n",
- "Why do this?\n",
- "\n",
- "Because we've now turned our pixel data from height and width dimensions into one long **feature vector** (`[1, 28, 28]` -> `[1, 784]`).\n",
- "\n",
- "And `nn.Linear()` layers like their inputs to be in the form of feature vectors.\n",
- "\n",
- "Let's create our first model using `nn.Flatten()` as the first layer. "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 15,
- "metadata": {
- "id": "OuLZTUTXoJeu"
- },
- "outputs": [],
- "source": [
- "from torch import nn\n",
- "class FashionMNISTModelV0(nn.Module):\n",
- " def __init__(self, input_shape, hidden_units, output_shape):\n",
- " super().__init__()\n",
- " self.layer_stack = nn.Sequential(\n",
- " nn.Flatten(), # neural networks like their inputs in vector form\n",
- " nn.Linear(in_features=input_shape, out_features=hidden_units), # in_features = number of features in a data sample (784 pixels)\n",
- " nn.Linear(in_features=hidden_units, out_features=output_shape)\n",
- " )\n",
- " \n",
- " def forward(self, x):\n",
- " return self.layer_stack(x)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "a9vELss1odle"
- },
- "source": [
- "Wonderful!\n",
- "\n",
- "We've got a baseline model class we can use, now let's instantiate a model.\n",
- "\n",
- "We'll need to set the following parameters:\n",
- "* `input_shape=784` - this is how many features you've got going in the model, in our case, it's one for every pixel in the target image (28 pixels high by 28 pixels wide = 784 features).\n",
- "* `hidden_units=10` - number of units/neurons in the hidden layer(s), this number could be whatever you want but to keep the model small we'll start with `10`.\n",
- "* `output_shape=len(class_names)` - since we're working with a multi-class classification problem, we need an output neuron per class in our dataset.\n",
- "\n",
- "Let's create an instance of our model and send to the CPU for now (we'll run a small test for CPU vs. GPU soon)."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 16,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "2qqwt2C7obmp",
- "outputId": "eb7fe716-577a-4ee3-9b39-c56aa1a7358d"
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "FashionMNISTModelV0(\n",
- " (layer_stack): Sequential(\n",
- " (0): Flatten(start_dim=1, end_dim=-1)\n",
- " (1): Linear(in_features=784, out_features=10, bias=True)\n",
- " (2): Linear(in_features=10, out_features=10, bias=True)\n",
- " )\n",
- ")"
- ]
- },
- "execution_count": 16,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "torch.manual_seed(42)\n",
- "\n",
- "# Need to setup model with input parameters\n",
- "model_0 = FashionMNISTModelV0(input_shape=784, # one for every pixel (28x28)\n",
- " hidden_units=10, # how many units in the hiden layer\n",
- " output_shape=len(class_names) # one for every class\n",
- ")\n",
- "model_0.to(\"cpu\") # keep model on CPU to begin wtih "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "ilMTlyoFog6_"
- },
- "source": [
- "### TK - 3.1 Setup loss, optimizer and evaluation metrics for Model 1\n",
- "\n",
- "Since we're working on a classification problem, let's bring in our [`helper_functions.py` script](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/helper_functions.py) and subsequently the `accuracy_fn()` we defined in [notebook 02](https://www.learnpytorch.io/02_pytorch_classification/).\n",
- "\n",
- "> **Note:** Rather than importing and using our own accuracy function or evaluation metric(s), you could import various evaluation metrics from the [TorchMetrics package](https://torchmetrics.readthedocs.io/en/latest/)."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 17,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "PDa-azArogUc",
- "outputId": "be7c4d74-a187-40a1-cb01-0c462a876775"
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Downloading helper_functions.py\n"
- ]
- }
- ],
- "source": [
- "import requests\n",
- "from pathlib import Path \n",
- "\n",
- "# Download helper functions from Learn PyTorch repo (if not already downloaded)\n",
- "if Path(\"helper_functions.py\").is_file():\n",
- " print(\"helper_functions.py already exists, skipping download\")\n",
- "else:\n",
- " print(\"Downloading helper_functions.py\")\n",
- " # Note: you need the \"raw\" GitHub URL for this to work\n",
- " request = requests.get(\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/helper_functions.py\")\n",
- " with open(\"helper_functions.py\", \"wb\") as f:\n",
- " f.write(request.content)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "LsRrsIiookNN"
- },
- "source": [
- "Now we've got the `helper_functions.py` file, let's import `accuracy_fn()` as well as setup a loss function and an optimizer.\n",
- "\n",
- "Since we're working with a multi-class classification problem, we'll use [`nn.CrossEntropyLoss()`](https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html) as the loss function.\n",
- "\n",
- "And we'll setup [`torch.optim.SGD()`](https://pytorch.org/docs/stable/generated/torch.optim.SGD.html) as the optimizer with a learning rate of `0.1`."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 18,
- "metadata": {
- "id": "tHDZiLcYofOp"
- },
- "outputs": [],
- "source": [
- "# Import accuracy metric\n",
- "from helper_functions import accuracy_fn # Note: could also use torchmetrics.Accuracy()\n",
- "\n",
- "# Setup loss function and optimizer\n",
- "loss_fn = nn.CrossEntropyLoss() # this is also called \"criterion\"/\"cost function\" in some places\n",
- "optimizer = torch.optim.SGD(params=model_0.parameters(), lr=0.1)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "YkpUE9azonry"
- },
- "source": [
- "### 3.2 Creating a function to time our experiments\n",
- "\n",
- "Loss function and optimizer ready!\n",
- "\n",
- "It's time to start training a model.\n",
- "\n",
- "But how about we do a little experiment while we train.\n",
- "\n",
- "I mean, let's make a timing function to measure the time it takes our model to train on CPU versus using a GPU.\n",
- "\n",
- "We'll train this model on the CPU but the next one on the CPU and see what happens.\n",
- "\n",
- "Our timing function will import the [`timeit.default_timer()` function](https://docs.python.org/3/library/timeit.html#timeit.default_timer) from the Python [`timeit` module](https://docs.python.org/3/library/timeit.html)."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 19,
- "metadata": {
- "id": "7SyTluBRomV6"
- },
- "outputs": [],
- "source": [
- "from timeit import default_timer as timer \n",
- "def print_train_time(start, end, device=None):\n",
- " \"\"\"Prints difference between start and end time.\n",
- "\n",
- " Args:\n",
- " start (float): Start time of computation (preferred in timeit format). \n",
- " end (float): End time of computation.\n",
- " device ([type], optional): Device that compute is running on. Defaults to None.\n",
- "\n",
- " Returns:\n",
- " float: time between start and end in seconds (higher is longer).\n",
- " \"\"\"\n",
- " total_time = end - start\n",
- " print(f\"Train time on {device}: {total_time:.3f} seconds\")\n",
- " return total_time"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "JcEtQjvJor6o"
- },
- "source": [
- "### 3.3 Creating a training loop and training a model on batches of data\n",
- "\n",
- "Beautiful!\n",
- "\n",
- "Looks like we've got all of the pieces of the puzzle ready to go, a timer, a loss function, an optimizer, a model and most importantly, some data.\n",
- "\n",
- "Let's now create a training loop and a testing loop to train and evaluate our model.\n",
- "\n",
- "We'll be using the same steps as the previous notebook(s), though since our data is now in batch form, we'll add another loop to loop through our data batches.\n",
- "\n",
- "Our data batches are contained within our `DataLoader`s, `train_dataloader` and `test_dataloader` for the training and test data splits respectively.\n",
- "\n",
- "A batch is `BATCH_SIZE` samples of `X` (features) and `y` (labels), since we're using `BATCH_SIZE=32`, our batches have 32 samples of images and targets.\n",
- "\n",
- "And since we're computing on batches of data, our loss and evaluation metrics will be calculated **per batch** rather than across the whole dataset.\n",
- "\n",
- "This means we'll have to divide our loss and accuracy values by the number of batches in each dataset's respective dataloader. \n",
- "\n",
- "Let's step through it: \n",
- "1. Loop through epochs.\n",
- "2. Loop through training batches, perform training steps, calculate the train loss *per batch*.\n",
- "3. Loop through testing batches, perform testing steps, calculate the test loss *per batch*.\n",
- "4. Print out what's happening.\n",
- "5. Time it all (for fun).\n",
- "\n",
- "A fair few steps but...\n",
- "\n",
- "...if in doubt, code it out. "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 20,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "naT1ATbQoqFV",
- "outputId": "8357d701-f824-49d1-ec69-8d22fe715491"
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Epoch: 0\n",
- "-------\n",
- "Looked at 0/60000 samples\n",
- "Looked at 12800/60000 samples\n",
- "Looked at 25600/60000 samples\n",
- "Looked at 38400/60000 samples\n",
- "Looked at 51200/60000 samples\n",
- "\n",
- "Train loss: 0.59039 | Test loss: 0.50954, Test acc: 82.04%\n",
- "\n",
- "Epoch: 1\n",
- "-------\n",
- "Looked at 0/60000 samples\n",
- "Looked at 12800/60000 samples\n",
- "Looked at 25600/60000 samples\n",
- "Looked at 38400/60000 samples\n",
- "Looked at 51200/60000 samples\n",
- "\n",
- "Train loss: 0.47633 | Test loss: 0.47989, Test acc: 83.20%\n",
- "\n",
- "Epoch: 2\n",
- "-------\n",
- "Looked at 0/60000 samples\n",
- "Looked at 12800/60000 samples\n",
- "Looked at 25600/60000 samples\n",
- "Looked at 38400/60000 samples\n",
- "Looked at 51200/60000 samples\n",
- "\n",
- "Train loss: 0.45503 | Test loss: 0.47664, Test acc: 83.43%\n",
- "\n",
- "Train time on cpu: 34.323 seconds\n"
- ]
- }
- ],
- "source": [
- "# Set the seed and start the timer\n",
- "torch.manual_seed(42)\n",
- "train_time_start_on_cpu = timer()\n",
- "\n",
- "# Set the number of epochs (we'll keep this small for faster training times)\n",
- "epochs = 3\n",
- "\n",
- "# Create training and testing loop\n",
- "for epoch in range(epochs):\n",
- " print(f\"Epoch: {epoch}\\n-------\")\n",
- " ### Training\n",
- " train_loss = 0\n",
- " # Add a loop to loop through training batches\n",
- " for batch, (X, y) in enumerate(train_dataloader):\n",
- " model_0.train() \n",
- " # 1. Forward pass\n",
- " y_pred = model_0(X)\n",
- "\n",
- " # 2. Calculate loss (per batch)\n",
- " loss = loss_fn(y_pred, y)\n",
- " train_loss += loss # accumulatively add up the loss per epoch \n",
- "\n",
- " # 3. Optimizer zero grad\n",
- " optimizer.zero_grad()\n",
- "\n",
- " # 4. Loss backward\n",
- " loss.backward()\n",
- "\n",
- " # 5. Optimizer step\n",
- " optimizer.step()\n",
- "\n",
- " # Print out how many samples have been seen\n",
- " if batch % 400 == 0:\n",
- " print(f\"Looked at {batch * len(X)}/{len(train_dataloader.dataset)} samples\")\n",
- "\n",
- " # Divide total train loss by length of train dataloader (average loss per batch per epoch)\n",
- " train_loss /= len(train_dataloader)\n",
- " \n",
- " ### Testing\n",
- " # Setup variables for accumulatively adding up loss and accuracy \n",
- " test_loss, test_acc = 0, 0 \n",
- " model_0.eval()\n",
- " with torch.inference_mode():\n",
- " for X, y in test_dataloader:\n",
- " # 1. Forward pass\n",
- " test_pred = model_0(X)\n",
- " \n",
- " # 2. Calculate loss (accumatively)\n",
- " test_loss += loss_fn(test_pred, y) # accumulatively add up the loss per epoch\n",
- "\n",
- " # 3. Calculate accuracy (preds need to be same as y_true)\n",
- " test_acc += accuracy_fn(y_true=y, y_pred=test_pred.argmax(dim=1))\n",
- " \n",
- " # Calculations on test metrics need to happen inside torch.inference_mode()\n",
- " # Divide total test loss by length of test dataloader (per batch)\n",
- " test_loss /= len(test_dataloader)\n",
- "\n",
- " # Divide total accuracy by length of test dataloader (per batch)\n",
- " test_acc /= len(test_dataloader)\n",
- "\n",
- " ## Print out what's happening\n",
- " print(f\"\\nTrain loss: {train_loss:.5f} | Test loss: {test_loss:.5f}, Test acc: {test_acc:.2f}%\\n\")\n",
- "\n",
- "# Calculate training time \n",
- "train_time_end_on_cpu = timer()\n",
- "total_train_time_model_0 = print_train_time(start=train_time_start_on_cpu, \n",
- " end=train_time_end_on_cpu,\n",
- " device=str(next(model_0.parameters()).device))"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "WME-Yocxowgs"
- },
- "source": [
- "Nice! Looks like our baseline model did fairly well.\n",
- "\n",
- "It didn't take too long to train either, even just on the CPU, I wonder if it'll speed up on the GPU?\n",
- "\n",
- "Let's write some code to evaluate our model."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "OzmgukBnoyqJ"
- },
- "source": [
- "## TK - 4. Make predictions and get Model 0 results\n",
- "\n",
- "Since we're going to be building a few models, it's a good idea to write some code to evaluate them all in similar ways.\n",
- "\n",
- "Namely, let's create a function that takes in a trained model, a `DataLoader`, a loss function and an accuracy function.\n",
- "\n",
- "The function will use the model to make predictions on the data in the `DataLoader` and then we can evaluate those predictions using the loss function and accuracy function."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 21,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "BXESm9YWouCH",
- "outputId": "f0e552b4-1280-41e5-adfe-6795b0c386de"
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "{'model_acc': 83.42651757188499,\n",
- " 'model_loss': 0.47663888335227966,\n",
- " 'model_name': 'FashionMNISTModelV0'}"
- ]
- },
- "execution_count": 21,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "torch.manual_seed(42)\n",
- "def eval_model(model: torch.nn.Module, \n",
- " data_loader: torch.utils.data.DataLoader, \n",
- " loss_fn: torch.nn.Module, \n",
- " accuracy_fn):\n",
- " \"\"\"Returns a dictionary containing the results of model predicting on data_loader.\n",
- "\n",
- " Args:\n",
- " model (torch.nn.Module): A PyTorch model capable of making predictions on data_loader.\n",
- " data_loader (torch.utils.data.DataLoader): The target dataset to predict on.\n",
- " loss_fn (torch.nn.Module): The loss function of model.\n",
- " accuracy_fn: An accuracy function to compare the models predictions to the truth labels.\n",
- "\n",
- " Returns:\n",
- " (dict): Results of model making predictions on data_loader.\n",
- " \"\"\"\n",
- " loss, acc = 0, 0\n",
- " model.eval()\n",
- " with torch.inference_mode():\n",
- " for X, y in data_loader:\n",
- " # Make predictions with the model\n",
- " y_pred = model(X)\n",
- " \n",
- " # Accumulate the loss and accuracy values per batch\n",
- " loss += loss_fn(y_pred, y)\n",
- " acc += accuracy_fn(y_true=y, \n",
- " y_pred=y_pred.argmax(dim=1)) # For accuracy, need the prediction labels (logits -> pred_prob -> pred_labels)\n",
- " \n",
- " # Scale loss and acc to find the average loss/acc per batch\n",
- " loss /= len(data_loader)\n",
- " acc /= len(data_loader)\n",
- " \n",
- " return {\"model_name\": model.__class__.__name__, # only works when model was created with a class\n",
- " \"model_loss\": loss.item(),\n",
- " \"model_acc\": acc}\n",
- "\n",
- "# Calculate model 0 results on test dataset\n",
- "model_0_results = eval_model(model=model_0, data_loader=test_dataloader,\n",
- " loss_fn=loss_fn, accuracy_fn=accuracy_fn\n",
- ")\n",
- "model_0_results"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "ro5n7EMMo3Am"
- },
- "source": [
- "Looking good!\n",
- "\n",
- "We can use this dictionary to compare the baseline model results to other models later on."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "RFFkETpoo45M"
- },
- "source": [
- "## TK 5. Setup device agnostic-code (for using a GPU if there is one)\n",
- "We've seen how long it takes to train ma PyTorch model on 60,000 samples on CPU.\n",
- "\n",
- "> **Note:** Model training time is dependent on hardware used. Generally, more processors means faster training and smaller models on smaller datasets will often train faster than large models and large datasets.\n",
- "\n",
- "Now let's setup some [device-agnostic code](https://pytorch.org/docs/stable/notes/cuda.html#best-practices) for our models and data to run on GPU if it's available.\n",
- "\n",
- "If you're running this notebook on Google Colab, and you don't a GPU turned on yet, it's now time to turn one on via `Runtime -> Change runtime type -> Hardware accelerator -> GPU`. If you do this, your runtime will likely reset and you'll have to run all of the cells above by going `Runtime -> Run before`."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 22,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/",
- "height": 35
- },
- "id": "g5yss0Dvo1JA",
- "outputId": "3a890b1e-a6d4-43f0-a25f-399de45aa463"
- },
- "outputs": [
- {
- "data": {
- "application/vnd.google.colaboratory.intrinsic+json": {
- "type": "string"
- },
- "text/plain": [
- "'cpu'"
- ]
- },
- "execution_count": 22,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "# Setup device agnostic code\n",
- "import torch\n",
- "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
- "device"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "qAhkMuvdo8T1"
- },
- "source": [
- "Beautiful!\n",
- "\n",
- "Let's build another model."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "23Oy8YbSo9G_"
- },
- "source": [
- "## TK - 6. Model 1: Building a better model with non-linearity\n",
- "\n",
- "We learned about [the power of non-linearity in notebook 02](https://www.learnpytorch.io/02_pytorch_classification/#6-the-missing-piece-non-linearity).\n",
- "\n",
- "Seeing the data we've been working with, do you think it needs non-linear functions?\n",
- "\n",
- "And remember, linear means straight and non-linear means non-straight.\n",
- "\n",
- "Let's find out.\n",
- "\n",
- "We'll do so by recreating a similar model to before, except this time we'll put non-linear functions (`nn.ReLU()`) in between each linear layer."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 23,
- "metadata": {
- "id": "YuGtaWSSo6XV"
- },
- "outputs": [],
- "source": [
- "# Create a model with non-linear and linear layers\n",
- "class FashionMNISTModelV1(nn.Module):\n",
- " def __init__(self, input_shape, hidden_units, output_shape):\n",
- " super().__init__()\n",
- " self.layer_stack = nn.Sequential(\n",
- " nn.Flatten(), # flatten inputs into single vector\n",
- " nn.Linear(in_features=input_shape, out_features=hidden_units),\n",
- " nn.ReLU(),\n",
- " nn.Linear(in_features=hidden_units, out_features=output_shape),\n",
- " nn.ReLU()\n",
- " )\n",
- " \n",
- " def forward(self, x):\n",
- " return self.layer_stack(x)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "568fkJc-pBQN"
- },
- "source": [
- "That looks good.\n",
- "\n",
- "Now let's instantiate it with the same settings we used before.\n",
- "\n",
- "We'll need `input_shape=784` (equal to the number of features of our image data), `hidden_units=10` (starting small and the same as our baseline model) and `output_shape=len(class_names)` (one output unit per class).\n",
- "\n",
- "> **Note:** Notice how we kept most of the settings of our model the same except for one change: adding non-linear layers. This is a standard practice for running a series of machine learning experiments, change one thing and see what happens, then do it again, again, again."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 24,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "IJ0kDOc5pDLk",
- "outputId": "4a673d47-0f5f-417c-ed6b-d9e610164d1a"
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "device(type='cpu')"
- ]
- },
- "execution_count": 24,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "torch.manual_seed(42)\n",
- "model_1 = FashionMNISTModelV1(input_shape=784, # number of input features\n",
- " hidden_units=10,\n",
- " output_shape=len(class_names) # number of output classes desired\n",
- ").to(device) # send model to GPU if it's available\n",
- "next(model_1.parameters()).device # check model device"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "RWhlOf3PpF7D"
- },
- "source": [
- "### TK - 6.1 Setup loss, optimizer and evaluation metrics\n",
- "\n",
- "As usual, we'll setup a loss function, an optimizer and an evaluation metric (we could do multiple evaluation metrics but we'll stick with accuracy for now)."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 25,
- "metadata": {
- "id": "J5sLGFqJpElO"
- },
- "outputs": [],
- "source": [
- "from helper_functions import accuracy_fn\n",
- "loss_fn = nn.CrossEntropyLoss()\n",
- "optimizer = torch.optim.SGD(params=model_1.parameters(), \n",
- " lr=0.1)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "9jIQEcdXpINg"
- },
- "source": [
- "### TK - 6.2 Functionizing training and test loops\n",
- "\n",
- "So far we've been writing train and test loops over and over. \n",
- "\n",
- "Let's write them again but this time we'll put them in functions so they can be called again and again.\n",
- "\n",
- "And because we're using device-agnostic code now, we'll be sure to call `.to(device)` on our feature (`X`) and target (`y`) tensors.\n",
- "\n",
- "For the training loop we'll create a function called `train_step()` which takes in a model, a `DataLoader` a loss function and an optimizer.\n",
- "\n",
- "The testing loop will be similar but it'll be called `test_step()` and it'll take in a model, a `DataLoader`, a loss function and an evaluation function.\n",
- "\n",
- "> **Note:** Since these are functions, you can customize them in any way you like. What we're making here can be considered barebones training and testing functions for our specific classification use case."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 26,
- "metadata": {
- "id": "ztWoQzdLpHGn"
- },
- "outputs": [],
- "source": [
- "def train_step(model, data_loader, loss_fn, optimizer, accuracy_fn, device=device):\n",
- " train_loss, train_acc = 0, 0\n",
- " for batch, (X, y) in enumerate(data_loader):\n",
- " # Send data to GPU\n",
- " X, y = X.to(device), y.to(device)\n",
- "\n",
- " # 1. Forward pass\n",
- " y_pred = model(X)\n",
- "\n",
- " # 2. Calculate loss\n",
- " loss = loss_fn(y_pred, y)\n",
- " train_loss += loss\n",
- " train_acc += accuracy_fn(y_true=y,\n",
- " y_pred=y_pred.argmax(dim=1)) # Go from logits -> pred labels\n",
- "\n",
- " # 3. Optimizer zero grad\n",
- " optimizer.zero_grad()\n",
- "\n",
- " # 4. Loss backward\n",
- " loss.backward()\n",
- "\n",
- " # 5. Optimizer step\n",
- " optimizer.step()\n",
- "\n",
- " # Calculate loss and accuracy per epoch and print out what's happening\n",
- " train_loss /= len(data_loader)\n",
- " train_acc /= len(data_loader)\n",
- " print(f\"Train loss: {test_loss:.5f} | Train accuracy: {test_acc:.2f}%\")\n",
- "\n",
- "def test_step(data_loader, model, loss_fn, accuracy_fn, device=device):\n",
- " test_loss, test_acc = 0, 0\n",
- " model.eval() # put model in eval mode\n",
- " # Turn on inference context manager\n",
- " with torch.inference_mode(): \n",
- " for X, y in data_loader:\n",
- " # Send data to GPU\n",
- " X, y = X.to(device), y.to(device)\n",
- " \n",
- " # 1. Forward pass\n",
- " test_pred = model(X)\n",
- " \n",
- " # 2. Calculate loss and accuracy\n",
- " test_loss += loss_fn(test_pred, y)\n",
- " test_acc += accuracy_fn(y_true=y,\n",
- " y_pred=test_pred.argmax(dim=1) # Go from logits -> pred labels\n",
- " )\n",
- " \n",
- " # Adjust metrics and print out\n",
- " test_loss /= len(data_loader)\n",
- " test_acc /= len(data_loader)\n",
- " print(f\"Test loss: {test_loss:.5f} | Test accuracy: {test_acc:.2f}%\\n\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "mAX25W6LpLRg"
- },
- "source": [
- "Woohoo!\n",
- "\n",
- "Now we've got some functions for training and testing our model, let's run them.\n",
- "\n",
- "We'll do so inside another loop for each epoch.\n",
- "\n",
- "That way for each epoch we're going a training and a testing step.\n",
- "\n",
- "> **Note:** You can customize how often you do a testing step. Sometimes people do them every five epochs or 10 epochs or in our case, every epoch.\n",
- "\n",
- "Let's also time things to see how long our code takes to run on the GPU."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 27,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "9dGWNmL1pJ08",
- "outputId": "717fb13d-b6c6-48da-eb81-fbb845316b49"
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Epoch: 0\n",
- "---------\n",
- "Train loss: 0.47664 | Train accuracy: 83.43%\n",
- "Test loss: 0.95636 | Test accuracy: 65.00%\n",
- "\n",
- "Epoch: 1\n",
- "---------\n",
- "Train loss: 0.47664 | Train accuracy: 83.43%\n",
- "Test loss: 0.72227 | Test accuracy: 73.91%\n",
- "\n",
- "Epoch: 2\n",
- "---------\n",
- "Train loss: 0.47664 | Train accuracy: 83.43%\n",
- "Test loss: 0.68500 | Test accuracy: 75.02%\n",
- "\n",
- "Train time on cpu: 33.530 seconds\n"
- ]
- }
- ],
- "source": [
- "torch.manual_seed(42)\n",
- "\n",
- "# Measure time\n",
- "from timeit import default_timer as timer\n",
- "train_time_start_on_gpu = timer()\n",
- "\n",
- "epochs = 3\n",
- "for epoch in range(epochs):\n",
- " print(f\"Epoch: {epoch}\\n---------\")\n",
- " train_step(data_loader=train_dataloader, \n",
- " model=model_1, \n",
- " loss_fn=loss_fn,\n",
- " optimizer=optimizer,\n",
- " accuracy_fn=accuracy_fn\n",
- " )\n",
- " test_step(data_loader=test_dataloader,\n",
- " model=model_1,\n",
- " loss_fn=loss_fn,\n",
- " accuracy_fn=accuracy_fn\n",
- " )\n",
- "\n",
- "train_time_end_on_gpu = timer()\n",
- "total_train_time_model_1 = print_train_time(start=train_time_start_on_gpu,\n",
- " end=train_time_end_on_gpu,\n",
- " device=device)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "S7R0_49spOFI"
- },
- "source": [
- "Excellent!\n",
- "\n",
- "Our model trained but the training time took longer?\n",
- "\n",
- "> **Note:** The training time on CUDA vs CPU will depend largely on the quality of the CPU/GPU you're using. Read on for a more explained answer.\n",
- "\n",
- "> **Question:** \"I used a a GPU but my model didn't train faster, why might that be?\"\n",
- ">\n",
- "> **Answer:** Well, one reason could be because your dataset and model are both so small (like the dataset and model we're working with) the benefits of using a GPU are outweighed by the time it actually takes to transfer the data there.\n",
- "> \n",
- "> There's a small bottleneck between copying data from the CPU memory (default) to the GPU memory.\n",
- ">\n",
- "> So for smaller models and datasets, the CPU might actually be the optimal place to compute on.\n",
- ">\n",
- "> But for larger datasets and models, the speed of computing the GPU can offer usually far outweighs the cost of getting the data there.\n",
- ">\n",
- "> However, this is largely dependant on the hardware you're using. With practice, you will get used to where the best place to train your models is. \n",
- "\n",
- "Let's evaluate our trained `model_1` using our `eval_model()` function and see how it went."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 28,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "hl90HIyrpMmf",
- "outputId": "d74522f5-2efa-40a8-c64c-80e61f3b8e25"
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "{'model_acc': 75.01996805111821,\n",
- " 'model_loss': 0.6850008368492126,\n",
- " 'model_name': 'FashionMNISTModelV1'}"
- ]
- },
- "execution_count": 28,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "torch.manual_seed(42)\n",
- "\n",
- "# Make sure model eval code can run on CPU...\n",
- "model_1_results = eval_model(model=model_1, \n",
- " data_loader=test_dataloader,\n",
- " loss_fn=loss_fn, \n",
- " accuracy_fn=accuracy_fn) # will error due to `eval_model()` not using device agnostic code \n",
- "model_1_results "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "1sOHeJmkpRPP"
- },
- "source": [
- "Oh no! \n",
- "\n",
- "It looks like our `eval_model()` function errors out with:\n",
- "\n",
- "```\n",
- "RuntimeError: 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)\n",
- "```\n",
- "\n",
- "It's because we've setup our data and model to use device-agnostic code but not our evaluation function.\n",
- "\n",
- "How about we fix that by passing a target `device` parameter to our `eval_model()` function?\n",
- "\n",
- "Then we'll try calculating the results again."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 29,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "unnWF9IGpSSQ",
- "outputId": "ecae61f0-f186-4cca-a0bc-c2c2e67921b3"
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "{'model_acc': 75.01996805111821,\n",
- " 'model_loss': 0.6850008368492126,\n",
- " 'model_name': 'FashionMNISTModelV1'}"
- ]
- },
- "execution_count": 29,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "# Move values to device\n",
- "torch.manual_seed(42)\n",
- "def eval_model(model: torch.nn.Module, \n",
- " data_loader: torch.utils.data.DataLoader, \n",
- " loss_fn: torch.nn.Module, \n",
- " accuracy_fn, \n",
- " device: str = device):\n",
- " \"\"\"Evaluates a given model on a given dataset.\n",
- "\n",
- " Args:\n",
- " model (torch.nn.Module): A PyTorch model capable of making predictions on data_loader.\n",
- " data_loader (torch.utils.data.DataLoader): The target dataset to predict on.\n",
- " loss_fn (torch.nn.Module): The loss function of model.\n",
- " accuracy_fn: An accuracy function to compare the models predictions to the truth labels.\n",
- " device (str, optional): Target device to compute on. Defaults to device.\n",
- "\n",
- " Returns:\n",
- " (dict): Results of model making predictions on data_loader.\n",
- " \"\"\"\n",
- " loss, acc = 0, 0\n",
- " model.eval()\n",
- " with torch.inference_mode():\n",
- " for X, y in data_loader:\n",
- " # Send data to the target device\n",
- " X, y = X.to(device), y.to(device)\n",
- " y_pred = model(X)\n",
- " loss += loss_fn(y_pred, y)\n",
- " acc += accuracy_fn(y_true=y, y_pred=y_pred.argmax(dim=1))\n",
- " \n",
- " # Scale loss and acc\n",
- " loss /= len(data_loader)\n",
- " acc /= len(data_loader)\n",
- " return {\"model_name\": model.__class__.__name__, # only works when model was created with a class\n",
- " \"model_loss\": loss.item(),\n",
- " \"model_acc\": acc}\n",
- "\n",
- "# Calculate model 1 results with device-agnostic code \n",
- "model_1_results = eval_model(model=model_1, data_loader=test_dataloader,\n",
- " loss_fn=loss_fn, accuracy_fn=accuracy_fn,\n",
- " device=device\n",
- ")\n",
- "model_1_results"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 30,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "mwjHSiPYpUIR",
- "outputId": "b55eab45-728b-4b50-b5a0-8db5ccd1e1f5"
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "{'model_acc': 83.42651757188499,\n",
- " 'model_loss': 0.47663888335227966,\n",
- " 'model_name': 'FashionMNISTModelV0'}"
- ]
- },
- "execution_count": 30,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "# Check baseline results\n",
- "model_0_results"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "3rOnUnhSpVyX"
- },
- "source": [
- "Woah, in this case, it looks like adding non-linearities to our model made it perform worse than the baseline.\n",
- "\n",
- "That's a thing to note in machine learning, sometimes the thing you thought should work doesn't. \n",
- "\n",
- "And then the thing you thought might not work does.\n",
- "\n",
- "It's part science, part art.\n",
- "\n",
- "From the looks of things, it seems like our model is **overfitting** on the training data.\n",
- "\n",
- "Overfitting means it's learning the training well but those patterns aren't generalizing to the testing data.\n",
- "\n",
- "Two of the main to fix overfitting include:\n",
- "1. Using a smaller or different model (some models fit certain kinds of data better than others).\n",
- "2. Using a larger dataset (the more data, the more chance a model has to learn generalizable patterns).\n",
- "\n",
- "There are more, but I'm going to leave that as a challenge for you to explore.\n",
- "\n",
- "Try searching online, \"ways to prevent overfitting in machine learning\" and see what comes up.\n",
- "\n",
- "In the meantime, let's take a look at number 1: using a different model."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "x-45n65jpaYp"
- },
- "source": [
- "## TK - 7. Model 2: Building a Convolutional Neural Network (CNN)\n",
- "\n",
- "Alright, time to step things up a notch.\n",
- "\n",
- "It's time to create a [Convolutional Neural Network](https://en.wikipedia.org/wiki/Convolutional_neural_network) (CNN or ConvNet).\n",
- "\n",
- "CNN's are known for their capabilities to find patterns in visual data.\n",
- "\n",
- "And since we're dealing with visual data, let's see if using a CNN model can improve upon our baseline.\n",
- "\n",
- "The CNN model we're going to be using is known as TinyVGG from the [CNN Explainer](https://poloclub.github.io/cnn-explainer/) website.\n",
- "\n",
- "It follows the typical structure of a convolutional neural network:\n",
- "\n",
- "```\n",
- "Input layer -> [Convolutional layer -> activation layer -> pooling layer] -> Output layer\n",
- "```\n",
- "\n",
- "Where the contents of `[Convolutional layer -> activation layer -> pooling layer]` can be upscaled and repeated multiple times, depending on requirements. \n",
- "\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "VivPp6Gupc6J"
- },
- "source": [
- "\n",
- "\n",
- "### What model should I use?\n",
- "\n",
- "> **Question:** Wait, you say CNN's are good for images, are there any other model types I should be aware of?\n",
- "\n",
- "Good question.\n",
- "\n",
- "This table is a good general guide for which model to use (though there are exceptions).\n",
- "\n",
- "| **Problem type** | **Model to use (generally)** | **Code example** |\n",
- "| ----- | ----- | ----- |\n",
- "| Structured data (Excel spreadsheets, row and column data) | Gradient boosted models, Random Forests, XGBoost | [`sklearn.ensemble`](https://scikit-learn.org/stable/modules/classes.html#module-sklearn.ensemble), [XGBoost library](https://xgboost.readthedocs.io/en/stable/) |\n",
- "| Unstructured data (images, audio, language) | Convolutional Neural Networks, Transformers | [`torchvision.models`](https://pytorch.org/vision/stable/models.html), [HuggingFace Transformers](https://huggingface.co/docs/transformers/index) | \n",
- "\n",
- "> **Note:** The table above is only for reference, the model you end up using will be highly dependant on the problem you're working on and the constraints you have (amount of data, latency requirements).\n",
- "\n",
- "Enough talking about models, let's now build a CNN that replicates the model on the [CNN Explainer website](https://poloclub.github.io/cnn-explainer/).\n",
- "\n",
- "\n",
- "\n",
- "To do so, we'll leverage the [`nn.Conv2d()`](https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html) and [`nn.MaxPool2d()`](https://pytorch.org/docs/stable/generated/torch.nn.MaxPool2d.html) layers from `torch.nn`.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 31,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "ppiMfmjVpX1h",
- "outputId": "e7c8f503-78c7-4e8c-97f4-00dd257b85a4"
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "FashionMNISTModelV2(\n",
- " (block_1): Sequential(\n",
- " (0): Conv2d(1, 10, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
- " (1): ReLU()\n",
- " (2): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
- " (3): ReLU()\n",
- " (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n",
- " )\n",
- " (block_2): Sequential(\n",
- " (0): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
- " (1): ReLU()\n",
- " (2): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
- " (3): ReLU()\n",
- " (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n",
- " )\n",
- " (classifier): Sequential(\n",
- " (0): Flatten(start_dim=1, end_dim=-1)\n",
- " (1): Linear(in_features=490, out_features=10, bias=True)\n",
- " )\n",
- ")"
- ]
- },
- "execution_count": 31,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "# Create a convolutional neural network \n",
- "class FashionMNISTModelV2(nn.Module):\n",
- " \"\"\"\n",
- " Model architecture copying TinyVGG from: \n",
- " https://poloclub.github.io/cnn-explainer/\n",
- " \"\"\"\n",
- " def __init__(self, input_shape, hidden_units, output_shape):\n",
- " super().__init__()\n",
- " self.block_1 = nn.Sequential(\n",
- " nn.Conv2d(in_channels=input_shape, \n",
- " out_channels=hidden_units, \n",
- " kernel_size=3, # how big is the square that's going over the image?\n",
- " stride=1, # default\n",
- " padding=1),# options = \"valid\" (no padding) or \"same\" (output has same shape as input) or int for specific number \n",
- " nn.ReLU(),\n",
- " nn.Conv2d(in_channels=hidden_units, \n",
- " out_channels=hidden_units,\n",
- " kernel_size=3,\n",
- " stride=1,\n",
- " padding=1),\n",
- " nn.ReLU(),\n",
- " nn.MaxPool2d(kernel_size=2,\n",
- " stride=2) # default stride value is same as kernel_size\n",
- " )\n",
- " self.block_2 = nn.Sequential(\n",
- " nn.Conv2d(hidden_units, hidden_units, 3, padding=1),\n",
- " nn.ReLU(),\n",
- " nn.Conv2d(hidden_units, hidden_units, 3, padding=1),\n",
- " nn.ReLU(),\n",
- " nn.MaxPool2d(2)\n",
- " )\n",
- " self.classifier = nn.Sequential(\n",
- " nn.Flatten(),\n",
- " # Where did this in_features shape come from? \n",
- " # It's because each layer of our network compresses and changes the shape of our inputs data.\n",
- " nn.Linear(in_features=hidden_units*7*7, \n",
- " out_features=output_shape)\n",
- " )\n",
- " \n",
- " def forward(self, x):\n",
- " x = self.block_1(x)\n",
- " # print(x.shape)\n",
- " x = self.block_2(x)\n",
- " # print(x.shape)\n",
- " x = self.classifier(x)\n",
- " # print(x.shape)\n",
- " return x\n",
- "\n",
- "torch.manual_seed(42)\n",
- "model_2 = FashionMNISTModelV2(input_shape=1, \n",
- " hidden_units=10, \n",
- " output_shape=len(class_names)).to(device)\n",
- "model_2"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "1kGENaszpee9"
- },
- "source": [
- "Nice!\n",
- "\n",
- "Our biggest model yet!\n",
- "\n",
- "This is a common practice in machine learning.\n",
- "\n",
- "Find a model architecture somewhere and replicate it with code. "
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "Rm0GTj-Vpi6D"
- },
- "source": [
- "### TK - 7.1 Stepping through `nn.Conv2d()` and `nn.MaxPool2d()` layers\n",
- "\n",
- "We could start using our model above and see what happens but let's first step through the two new layers we've added:\n",
- "* [`nn.Conv2d()`](https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html), also known as a convolutional layer.\n",
- "* [`nn.MaxPool2d()`](https://pytorch.org/docs/stable/generated/torch.nn.MaxPool2d.html), also known as a max pooling layer.\n",
- "\n",
- "> **Question:** What does the \"2d\" in `nn.Conv2d()` stand for?\n",
- ">\n",
- "> The 2d is for 2-dimensional data. As in, our images have two dimensions: height and width. Yes, there's color channel dimension but each of the color channel dimensions have two dimensions too: height and width.\n",
- ">\n",
- "> For other dimensional data (such as 1D for text or 3D for 3D objects) there's also `nn.Conv1d()` and `nn.Conv3d()`. \n",
- "\n",
- "To test the layers out, let's create some toy data just like the data used on CNN Explainer."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 32,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "Ojg2kFSMphQY",
- "outputId": "f14dc6be-2cfa-424a-b6dd-0df735ce19db"
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Image batch shape: torch.Size([32, 3, 64, 64]) -> [batch_size, color_channels, height, width]\n",
- "Single image shape: torch.Size([3, 64, 64]) -> [color_channels, height, width]\n",
- "Single image pixel values:\n",
- "tensor([[[ 1.9269, 1.4873, 0.9007, ..., 1.8446, -1.1845, 1.3835],\n",
- " [ 1.4451, 0.8564, 2.2181, ..., 0.3399, 0.7200, 0.4114],\n",
- " [ 1.9312, 1.0119, -1.4364, ..., -0.5558, 0.7043, 0.7099],\n",
- " ...,\n",
- " [-0.5610, -0.4830, 0.4770, ..., -0.2713, -0.9537, -0.6737],\n",
- " [ 0.3076, -0.1277, 0.0366, ..., -2.0060, 0.2824, -0.8111],\n",
- " [-1.5486, 0.0485, -0.7712, ..., -0.1403, 0.9416, -0.0118]],\n",
- "\n",
- " [[-0.5197, 1.8524, 1.8365, ..., 0.8935, -1.5114, -0.8515],\n",
- " [ 2.0818, 1.0677, -1.4277, ..., 1.6612, -2.6223, -0.4319],\n",
- " [-0.1010, -0.4388, -1.9775, ..., 0.2106, 0.2536, -0.7318],\n",
- " ...,\n",
- " [ 0.2779, 0.7342, -0.3736, ..., -0.4601, 0.1815, 0.1850],\n",
- " [ 0.7205, -0.2833, 0.0937, ..., -0.1002, -2.3609, 2.2465],\n",
- " [-1.3242, -0.1973, 0.2920, ..., 0.5409, 0.6940, 1.8563]],\n",
- "\n",
- " [[-0.7978, 1.0261, 1.1465, ..., 1.2134, 0.9354, -0.0780],\n",
- " [-1.4647, -1.9571, 0.1017, ..., -1.9986, -0.7409, 0.7011],\n",
- " [-1.3938, 0.8466, -1.7191, ..., -1.1867, 0.1320, 0.3407],\n",
- " ...,\n",
- " [ 0.8206, -0.3745, 1.2499, ..., -0.0676, 0.0385, 0.6335],\n",
- " [-0.5589, -0.3393, 0.2347, ..., 2.1181, 2.4569, 1.3083],\n",
- " [-0.4092, 1.5199, 0.2401, ..., -0.2558, 0.7870, 0.9924]]])\n"
- ]
- }
- ],
- "source": [
- "torch.manual_seed(42)\n",
- "\n",
- "# Create sample batch of random numbers with same size as image batch\n",
- "images = torch.randn(size=(32, 3, 64, 64)) # [batch_size, color_channels, height, width]\n",
- "test_image = images[0] # get a single image for testing\n",
- "print(f\"Image batch shape: {images.shape} -> [batch_size, color_channels, height, width]\")\n",
- "print(f\"Single image shape: {test_image.shape} -> [color_channels, height, width]\") \n",
- "print(f\"Single image pixel values:\\n{test_image}\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "J_2Ux_i1po2W"
- },
- "source": [
- "Let's create an example `nn.Conv2d()` with various parameters:\n",
- "* `in_channels` (int) - Number of channels in the input image.\n",
- "* `out_channels` (int) - Number of channels produced by the convolution.\n",
- "* `kernel_size` (int or tuple) - Size of the convolving kernel/filter.\n",
- "* `stride` (int or tuple, optional) - How big of a step the convolving kernel takes at a time. Default: 1.\n",
- "* `padding` (int, tuple, str) - Padding added to all four sides of input. Default: 0.\n",
- "\n",
- "\n",
- "\n",
- "*Example of what happens when you change the hyperparameters of a `nn.Conv2d()` layer.*"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 33,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/",
- "height": 407
- },
- "id": "eYjuOOi6pnHd",
- "outputId": "453a6444-7732-4af9-d2be-43d27ba20385"
- },
- "outputs": [
- {
- "ename": "RuntimeError",
- "evalue": "ignored",
- "output_type": "error",
- "traceback": [
- "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
- "\u001b[0;31mRuntimeError\u001b[0m Traceback (most recent call last)",
- "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 10\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 11\u001b[0m \u001b[0;31m# Pass the data through the convolutional layer\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 12\u001b[0;31m \u001b[0mconv_layer\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtest_image\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# note: this will error because of shape issues (nn.Conv.2d() expects a 4d tensor as input)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
- "\u001b[0;32m/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py\u001b[0m in \u001b[0;36m_call_impl\u001b[0;34m(self, *input, **kwargs)\u001b[0m\n\u001b[1;32m 1100\u001b[0m if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks\n\u001b[1;32m 1101\u001b[0m or _global_forward_hooks or _global_forward_pre_hooks):\n\u001b[0;32m-> 1102\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mforward_call\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0minput\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 1103\u001b[0m \u001b[0;31m# Do not call functions when jit is used\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1104\u001b[0m \u001b[0mfull_backward_hooks\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mnon_full_backward_hooks\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
- "\u001b[0;32m/usr/local/lib/python3.7/dist-packages/torch/nn/modules/conv.py\u001b[0m in \u001b[0;36mforward\u001b[0;34m(self, input)\u001b[0m\n\u001b[1;32m 444\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 445\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mforward\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0minput\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0mTensor\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m->\u001b[0m \u001b[0mTensor\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 446\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_conv_forward\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minput\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mweight\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mbias\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 447\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 448\u001b[0m \u001b[0;32mclass\u001b[0m \u001b[0mConv3d\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0m_ConvNd\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
- "\u001b[0;32m/usr/local/lib/python3.7/dist-packages/torch/nn/modules/conv.py\u001b[0m in \u001b[0;36m_conv_forward\u001b[0;34m(self, input, weight, bias)\u001b[0m\n\u001b[1;32m 441\u001b[0m _pair(0), self.dilation, self.groups)\n\u001b[1;32m 442\u001b[0m return F.conv2d(input, weight, bias, self.stride,\n\u001b[0;32m--> 443\u001b[0;31m self.padding, self.dilation, self.groups)\n\u001b[0m\u001b[1;32m 444\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 445\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mforward\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0minput\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0mTensor\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m->\u001b[0m \u001b[0mTensor\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
- "\u001b[0;31mRuntimeError\u001b[0m: Expected 4-dimensional input for 4-dimensional weight [10, 3, 3, 3], but got 3-dimensional input of size [3, 64, 64] instead"
- ]
- }
- ],
- "source": [
- "torch.manual_seed(42)\n",
- "\n",
- "# Create a convolutional layer with same dimensions as TinyVGG \n",
- "# (try changing any of the parameters and see what happens)\n",
- "conv_layer = nn.Conv2d(in_channels=3,\n",
- " out_channels=10,\n",
- " kernel_size=3,\n",
- " stride=1,\n",
- " padding=0) # also try using \"valid\" or \"same\" here \n",
- "\n",
- "# Pass the data through the convolutional layer\n",
- "conv_layer(test_image) # note: this will error because of shape issues (nn.Conv.2d() expects a 4d tensor as input)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "Mu0GFI_3psJH"
- },
- "source": [
- "Oh no! Another error.\n",
- "\n",
- "If we try to pass a single image in, we get a shape mismatch error:\n",
- "\n",
- "```\n",
- "RuntimeError: Expected 4-dimensional input for 4-dimensional weight [10, 3, 3, 3], but got 3-dimensional input of size [3, 64, 64] instead\n",
- "```\n",
- "\n",
- "This is because our `nn.Conv2d()` layer expects a 4-dimensional tensor as input with size `(N, C, H, W)` or `[batch_size, color_channels, height, width]`.\n",
- "\n",
- "Right now our single image `test_image` only has a shape of `[color_channels, height, width]` or `[3, 64, 64]`.\n",
- "\n",
- "We can fix this for a single image using `test_image.unsqueeze(dim=0)` to add an extra dimension for `N`."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 35,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "cRjHf25spwa-",
- "outputId": "f4042218-ce4f-4493-b9fc-9e48d44fcc1d"
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "torch.Size([1, 3, 64, 64])"
- ]
- },
- "execution_count": 35,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "# Add extra dimension to test image\n",
- "test_image.unsqueeze(dim=0).shape"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 36,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "vOe4FE8epydx",
- "outputId": "bfaaeac1-0b3e-4093-e9f2-0beb69a21e67"
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "torch.Size([1, 10, 62, 62])"
- ]
- },
- "execution_count": 36,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "# Pass test image with extra dimension through conv_layer\n",
- "conv_layer(test_image.unsqueeze(dim=0)).shape"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "gAUUPP4Up1T8"
- },
- "source": [
- "Hmm, notice what happens to our shape (the same shape as the first layer of TinyVGG on [CNN Explainer](https://poloclub.github.io/cnn-explainer/)), we get different channel sizes as well as different pixel sizes.\n",
- "\n",
- "What if we changed the values of `conv_layer`?"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 37,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "CPdcLPpnp4XT",
- "outputId": "ec74b9d6-9044-41ec-cb25-1d991bdeab3d"
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "torch.Size([1, 10, 30, 30])"
- ]
- },
- "execution_count": 37,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "torch.manual_seed(42)\n",
- "# Create a new conv_layer with different values (try setting these to whatever you like)\n",
- "conv_layer_2 = nn.Conv2d(in_channels=3, # same number of color channels as our input image\n",
- " out_channels=10,\n",
- " kernel_size=(5, 5), # kernel is usually a square so a tuple also works\n",
- " stride=2,\n",
- " padding=0)\n",
- "\n",
- "# Pass single image through new conv_layer_2 (this calls nn.Conv2d()'s forward() method on the input)\n",
- "conv_layer_2(test_image.unsqueeze(dim=0)).shape"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "dROW8Kwbp5gz"
- },
- "source": [
- "Woah, we get another shape change.\n",
- "\n",
- "Now our image is of shape `[1, 10, 30, 30]` (it will be different if you use different values) or `[batch_size=1, color_channels=10, height=30, width=30]`.\n",
- "\n",
- "What's going on here?\n",
- "\n",
- "Behind the scenes, our `nn.Conv2d()` is compressing the information stored in the image.\n",
- "\n",
- "It does this by performing operations on the input (our test image) against its internal parameters.\n",
- "\n",
- "The goal of this is similar to all of the other neural networks we've been building.\n",
- "\n",
- "Data goes in and the layers try to update their internal parameters (patterns) to lower the loss function thanks to some help of the optimizer.\n",
- "\n",
- "The only difference is *how* the different layers calculate their parameter updates or in PyTorch terms, the operation present in the layer `forward()` method.\n",
- "\n",
- "If we check out our `conv_layer_2.state_dict()` we'll find a similar weight and bias setup as we've seen before."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 38,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "3e4TSzmpp7Aa",
- "outputId": "258feba1-f19f-47fa-f447-0d69a570db8f"
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "OrderedDict([('weight', tensor([[[[ 0.0883, 0.0958, -0.0271, 0.1061, -0.0253],\n",
- " [ 0.0233, -0.0562, 0.0678, 0.1018, -0.0847],\n",
- " [ 0.1004, 0.0216, 0.0853, 0.0156, 0.0557],\n",
- " [-0.0163, 0.0890, 0.0171, -0.0539, 0.0294],\n",
- " [-0.0532, -0.0135, -0.0469, 0.0766, -0.0911]],\n",
- "\n",
- " [[-0.0532, -0.0326, -0.0694, 0.0109, -0.1140],\n",
- " [ 0.1043, -0.0981, 0.0891, 0.0192, -0.0375],\n",
- " [ 0.0714, 0.0180, 0.0933, 0.0126, -0.0364],\n",
- " [ 0.0310, -0.0313, 0.0486, 0.1031, 0.0667],\n",
- " [-0.0505, 0.0667, 0.0207, 0.0586, -0.0704]],\n",
- "\n",
- " [[-0.1143, -0.0446, -0.0886, 0.0947, 0.0333],\n",
- " [ 0.0478, 0.0365, -0.0020, 0.0904, -0.0820],\n",
- " [ 0.0073, -0.0788, 0.0356, -0.0398, 0.0354],\n",
- " [-0.0241, 0.0958, -0.0684, -0.0689, -0.0689],\n",
- " [ 0.1039, 0.0385, 0.1111, -0.0953, -0.1145]]],\n",
- "\n",
- "\n",
- " [[[-0.0903, -0.0777, 0.0468, 0.0413, 0.0959],\n",
- " [-0.0596, -0.0787, 0.0613, -0.0467, 0.0701],\n",
- " [-0.0274, 0.0661, -0.0897, -0.0583, 0.0352],\n",
- " [ 0.0244, -0.0294, 0.0688, 0.0785, -0.0837],\n",
- " [-0.0616, 0.1057, -0.0390, -0.0409, -0.1117]],\n",
- "\n",
- " [[-0.0661, 0.0288, -0.0152, -0.0838, 0.0027],\n",
- " [-0.0789, -0.0980, -0.0636, -0.1011, -0.0735],\n",
- " [ 0.1154, 0.0218, 0.0356, -0.1077, -0.0758],\n",
- " [-0.0384, 0.0181, -0.1016, -0.0498, -0.0691],\n",
- " [ 0.0003, -0.0430, -0.0080, -0.0782, -0.0793]],\n",
- "\n",
- " [[-0.0674, -0.0395, -0.0911, 0.0968, -0.0229],\n",
- " [ 0.0994, 0.0360, -0.0978, 0.0799, -0.0318],\n",
- " [-0.0443, -0.0958, -0.1148, 0.0330, -0.0252],\n",
- " [ 0.0450, -0.0948, 0.0857, -0.0848, -0.0199],\n",
- " [ 0.0241, 0.0596, 0.0932, 0.1052, -0.0916]]],\n",
- "\n",
- "\n",
- " [[[ 0.0291, -0.0497, -0.0127, -0.0864, 0.1052],\n",
- " [-0.0847, 0.0617, 0.0406, 0.0375, -0.0624],\n",
- " [ 0.1050, 0.0254, 0.0149, -0.1018, 0.0485],\n",
- " [-0.0173, -0.0529, 0.0992, 0.0257, -0.0639],\n",
- " [-0.0584, -0.0055, 0.0645, -0.0295, -0.0659]],\n",
- "\n",
- " [[-0.0395, -0.0863, 0.0412, 0.0894, -0.1087],\n",
- " [ 0.0268, 0.0597, 0.0209, -0.0411, 0.0603],\n",
- " [ 0.0607, 0.0432, -0.0203, -0.0306, 0.0124],\n",
- " [-0.0204, -0.0344, 0.0738, 0.0992, -0.0114],\n",
- " [-0.0259, 0.0017, -0.0069, 0.0278, 0.0324]],\n",
- "\n",
- " [[-0.1049, -0.0426, 0.0972, 0.0450, -0.0057],\n",
- " [-0.0696, -0.0706, -0.1034, -0.0376, 0.0390],\n",
- " [ 0.0736, 0.0533, -0.1021, -0.0694, -0.0182],\n",
- " [ 0.1117, 0.0167, -0.0299, 0.0478, -0.0440],\n",
- " [-0.0747, 0.0843, -0.0525, -0.0231, -0.1149]]],\n",
- "\n",
- "\n",
- " [[[ 0.0773, 0.0875, 0.0421, -0.0805, -0.1140],\n",
- " [-0.0938, 0.0861, 0.0554, 0.0972, 0.0605],\n",
- " [ 0.0292, -0.0011, -0.0878, -0.0989, -0.1080],\n",
- " [ 0.0473, -0.0567, -0.0232, -0.0665, -0.0210],\n",
- " [-0.0813, -0.0754, 0.0383, -0.0343, 0.0713]],\n",
- "\n",
- " [[-0.0370, -0.0847, -0.0204, -0.0560, -0.0353],\n",
- " [-0.1099, 0.0646, -0.0804, 0.0580, 0.0524],\n",
- " [ 0.0825, -0.0886, 0.0830, -0.0546, 0.0428],\n",
- " [ 0.1084, -0.0163, -0.0009, -0.0266, -0.0964],\n",
- " [ 0.0554, -0.1146, 0.0717, 0.0864, 0.1092]],\n",
- "\n",
- " [[-0.0272, -0.0949, 0.0260, 0.0638, -0.1149],\n",
- " [-0.0262, -0.0692, -0.0101, -0.0568, -0.0472],\n",
- " [-0.0367, -0.1097, 0.0947, 0.0968, -0.0181],\n",
- " [-0.0131, -0.0471, -0.1043, -0.1124, 0.0429],\n",
- " [-0.0634, -0.0742, -0.0090, -0.0385, -0.0374]]],\n",
- "\n",
- "\n",
- " [[[ 0.0037, -0.0245, -0.0398, -0.0553, -0.0940],\n",
- " [ 0.0968, -0.0462, 0.0306, -0.0401, 0.0094],\n",
- " [ 0.1077, 0.0532, -0.1001, 0.0458, 0.1096],\n",
- " [ 0.0304, 0.0774, 0.1138, -0.0177, 0.0240],\n",
- " [-0.0803, -0.0238, 0.0855, 0.0592, -0.0731]],\n",
- "\n",
- " [[-0.0926, -0.0789, -0.1140, -0.0891, -0.0286],\n",
- " [ 0.0779, 0.0193, -0.0878, -0.0926, 0.0574],\n",
- " [-0.0859, -0.0142, 0.0554, -0.0534, -0.0126],\n",
- " [-0.0101, -0.0273, -0.0585, -0.1029, -0.0933],\n",
- " [-0.0618, 0.1115, -0.0558, -0.0775, 0.0280]],\n",
- "\n",
- " [[ 0.0318, 0.0633, 0.0878, 0.0643, -0.1145],\n",
- " [ 0.0102, 0.0699, -0.0107, -0.0680, 0.1101],\n",
- " [-0.0432, -0.0657, -0.1041, 0.0052, 0.0512],\n",
- " [ 0.0256, 0.0228, -0.0876, -0.1078, 0.0020],\n",
- " [ 0.1053, 0.0666, -0.0672, -0.0150, -0.0851]]],\n",
- "\n",
- "\n",
- " [[[-0.0557, 0.0209, 0.0629, 0.0957, -0.1060],\n",
- " [ 0.0772, -0.0814, 0.0432, 0.0977, 0.0016],\n",
- " [ 0.1051, -0.0984, -0.0441, 0.0673, -0.0252],\n",
- " [-0.0236, -0.0481, 0.0796, 0.0566, 0.0370],\n",
- " [-0.0649, -0.0937, 0.0125, 0.0342, -0.0533]],\n",
- "\n",
- " [[-0.0323, 0.0780, 0.0092, 0.0052, -0.0284],\n",
- " [-0.1046, -0.1086, -0.0552, -0.0587, 0.0360],\n",
- " [-0.0336, -0.0452, 0.1101, 0.0402, 0.0823],\n",
- " [-0.0559, -0.0472, 0.0424, -0.0769, -0.0755],\n",
- " [-0.0056, -0.0422, -0.0866, 0.0685, 0.0929]],\n",
- "\n",
- " [[ 0.0187, -0.0201, -0.1070, -0.0421, 0.0294],\n",
- " [ 0.0544, -0.0146, -0.0457, 0.0643, -0.0920],\n",
- " [ 0.0730, -0.0448, 0.0018, -0.0228, 0.0140],\n",
- " [-0.0349, 0.0840, -0.0030, 0.0901, 0.1110],\n",
- " [-0.0563, -0.0842, 0.0926, 0.0905, -0.0882]]],\n",
- "\n",
- "\n",
- " [[[-0.0089, -0.1139, -0.0945, 0.0223, 0.0307],\n",
- " [ 0.0245, -0.0314, 0.1065, 0.0165, -0.0681],\n",
- " [-0.0065, 0.0277, 0.0404, -0.0816, 0.0433],\n",
- " [-0.0590, -0.0959, -0.0631, 0.1114, 0.0987],\n",
- " [ 0.1034, 0.0678, 0.0872, -0.0155, -0.0635]],\n",
- "\n",
- " [[ 0.0577, -0.0598, -0.0779, -0.0369, 0.0242],\n",
- " [ 0.0594, -0.0448, -0.0680, 0.0156, -0.0681],\n",
- " [-0.0752, 0.0602, -0.0194, 0.1055, 0.1123],\n",
- " [ 0.0345, 0.0397, 0.0266, 0.0018, -0.0084],\n",
- " [ 0.0016, 0.0431, 0.1074, -0.0299, -0.0488]],\n",
- "\n",
- " [[-0.0280, -0.0558, 0.0196, 0.0862, 0.0903],\n",
- " [ 0.0530, -0.0850, -0.0620, -0.0254, -0.0213],\n",
- " [ 0.0095, -0.1060, 0.0359, -0.0881, -0.0731],\n",
- " [-0.0960, 0.1006, -0.1093, 0.0871, -0.0039],\n",
- " [-0.0134, 0.0722, -0.0107, 0.0724, 0.0835]]],\n",
- "\n",
- "\n",
- " [[[-0.1003, 0.0444, 0.0218, 0.0248, 0.0169],\n",
- " [ 0.0316, -0.0555, -0.0148, 0.1097, 0.0776],\n",
- " [-0.0043, -0.1086, 0.0051, -0.0786, 0.0939],\n",
- " [-0.0701, -0.0083, -0.0256, 0.0205, 0.1087],\n",
- " [ 0.0110, 0.0669, 0.0896, 0.0932, -0.0399]],\n",
- "\n",
- " [[-0.0258, 0.0556, -0.0315, 0.0541, -0.0252],\n",
- " [-0.0783, 0.0470, 0.0177, 0.0515, 0.1147],\n",
- " [ 0.0788, 0.1095, 0.0062, -0.0993, -0.0810],\n",
- " [-0.0717, -0.1018, -0.0579, -0.1063, -0.1065],\n",
- " [-0.0690, -0.1138, -0.0709, 0.0440, 0.0963]],\n",
- "\n",
- " [[-0.0343, -0.0336, 0.0617, -0.0570, -0.0546],\n",
- " [ 0.0711, -0.1006, 0.0141, 0.1020, 0.0198],\n",
- " [ 0.0314, -0.0672, -0.0016, 0.0063, 0.0283],\n",
- " [ 0.0449, 0.1003, -0.0881, 0.0035, -0.0577],\n",
- " [-0.0913, -0.0092, -0.1016, 0.0806, 0.0134]]],\n",
- "\n",
- "\n",
- " [[[-0.0622, 0.0603, -0.1093, -0.0447, -0.0225],\n",
- " [-0.0981, -0.0734, -0.0188, 0.0876, 0.1115],\n",
- " [ 0.0735, -0.0689, -0.0755, 0.1008, 0.0408],\n",
- " [ 0.0031, 0.0156, -0.0928, -0.0386, 0.1112],\n",
- " [-0.0285, -0.0058, -0.0959, -0.0646, -0.0024]],\n",
- "\n",
- " [[-0.0717, -0.0143, 0.0470, -0.1130, 0.0343],\n",
- " [-0.0763, -0.0564, 0.0443, 0.0918, -0.0316],\n",
- " [-0.0474, -0.1044, -0.0595, -0.1011, -0.0264],\n",
- " [ 0.0236, -0.1082, 0.1008, 0.0724, -0.1130],\n",
- " [-0.0552, 0.0377, -0.0237, -0.0126, -0.0521]],\n",
- "\n",
- " [[ 0.0927, -0.0645, 0.0958, 0.0075, 0.0232],\n",
- " [ 0.0901, -0.0190, -0.0657, -0.0187, 0.0937],\n",
- " [-0.0857, 0.0262, -0.1135, 0.0605, 0.0427],\n",
- " [ 0.0049, 0.0496, 0.0001, 0.0639, -0.0914],\n",
- " [-0.0170, 0.0512, 0.1150, 0.0588, -0.0840]]],\n",
- "\n",
- "\n",
- " [[[ 0.0888, -0.0257, -0.0247, -0.1050, -0.0182],\n",
- " [ 0.0817, 0.0161, -0.0673, 0.0355, -0.0370],\n",
- " [ 0.1054, -0.1002, -0.0365, -0.1115, -0.0455],\n",
- " [ 0.0364, 0.1112, 0.0194, 0.1132, 0.0226],\n",
- " [ 0.0667, 0.0926, 0.0965, -0.0646, 0.1062]],\n",
- "\n",
- " [[ 0.0699, -0.0540, -0.0551, -0.0969, 0.0290],\n",
- " [-0.0936, 0.0488, 0.0365, -0.1003, 0.0315],\n",
- " [-0.0094, 0.0527, 0.0663, -0.1148, 0.1059],\n",
- " [ 0.0968, 0.0459, -0.1055, -0.0412, -0.0335],\n",
- " [-0.0297, 0.0651, 0.0420, 0.0915, -0.0432]],\n",
- "\n",
- " [[ 0.0389, 0.0411, -0.0961, -0.1120, -0.0599],\n",
- " [ 0.0790, -0.1087, -0.1005, 0.0647, 0.0623],\n",
- " [ 0.0950, -0.0872, -0.0845, 0.0592, 0.1004],\n",
- " [ 0.0691, 0.0181, 0.0381, 0.1096, -0.0745],\n",
- " [-0.0524, 0.0808, -0.0790, -0.0637, 0.0843]]]])), ('bias', tensor([ 0.0364, 0.0373, -0.0489, -0.0016, 0.1057, -0.0693, 0.0009, 0.0549,\n",
- " -0.0797, 0.1121]))])\n"
- ]
- }
- ],
- "source": [
- "# Check out the conv_layer_2 internal parameters\n",
- "print(conv_layer_2.state_dict())"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "1s7cGrpwp8OL"
- },
- "source": [
- "Look at that! A bunch of random numbers for a weight and bias tensor.\n",
- "\n",
- "The shapes of these are manipulated by the inputs we passed to `nn.Conv2d()` when we set it up.\n",
- "\n",
- "Let's check them out."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 39,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "PR8gV7Rop_Cd",
- "outputId": "a94962e4-ebb1-4a60-b475-a1957bcc9489"
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "conv_layer_2 weight shape: \n",
- "torch.Size([10, 3, 5, 5]) -> [out_channels=10, in_channels=3, kernel_size=5, kernel_size=5]\n",
- "\n",
- "conv_layer_2 bias shape: \n",
- "torch.Size([10]) -> [out_channels=10]\n"
- ]
- }
- ],
- "source": [
- "# Get shapes of weight and bias tensors within conv_layer_2\n",
- "print(f\"conv_layer_2 weight shape: \\n{conv_layer_2.weight.shape} -> [out_channels=10, in_channels=3, kernel_size=5, kernel_size=5]\")\n",
- "print(f\"\\nconv_layer_2 bias shape: \\n{conv_layer_2.bias.shape} -> [out_channels=10]\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "5MlfiiXMqAX6"
- },
- "source": [
- "> **Question:** What should we set the parameters of our `nn.Conv2d()` layers?\n",
- ">\n",
- "> That's a good one. But similar to many other things in machine learning, the values of these aren't set in stone (and recall, because these values are ones we can set ourselves, they're referred to as \"**hyperparameters**\"). \n",
- ">\n",
- "> The best way to find out is to try out different values and see how they effect your model's performance.\n",
- ">\n",
- "> Or even better, find a working example on a problem similar to yours (like we've done with TinyVGG) and copy it. \n",
- "\n",
- "We're working with a different of layer here to what we've seen before.\n",
- "\n",
- "But the premise remains the same: start with random numbers and update them to better represent the data.\n",
- "\n",
- "Now let's check out what happens when we move data through `nn.MaxPool2d()`."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 40,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "eJfUVP7JqCbA",
- "outputId": "009e83ce-8a4e-405b-9872-1f780685041d"
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Test image original shape: torch.Size([3, 64, 64])\n",
- "Test image with unsqueezed dimension: torch.Size([1, 3, 64, 64])\n",
- "Shape after going through conv_layer(): torch.Size([1, 10, 62, 62])\n",
- "Shape after going through conv_layer() and max_pool_layer(): torch.Size([1, 10, 31, 31])\n"
- ]
- }
- ],
- "source": [
- "# Print out original image shape without and with unsqueezed dimension\n",
- "print(f\"Test image original shape: {test_image.shape}\")\n",
- "print(f\"Test image with unsqueezed dimension: {test_image.unsqueeze(dim=0).shape}\")\n",
- "\n",
- "# Create a sample nn.MaxPoo2d() layer\n",
- "max_pool_layer = nn.MaxPool2d(kernel_size=2)\n",
- "\n",
- "# Pass data through just the conv_layer\n",
- "test_image_through_conv = conv_layer(test_image.unsqueeze(dim=0))\n",
- "print(f\"Shape after going through conv_layer(): {test_image_through_conv.shape}\")\n",
- "\n",
- "# Pass data through the max pool layer\n",
- "test_image_through_conv_and_max_pool = max_pool_layer(test_image_through_conv)\n",
- "print(f\"Shape after going through conv_layer() and max_pool_layer(): {test_image_through_conv_and_max_pool.shape}\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "ICAe2oBtqFIO"
- },
- "source": [
- "Notice the change in the shapes of what's happening in and out of a `nn.MaxPool2d()` layer.\n",
- "\n",
- "The `kernel_size` of the `nn.MaxPool2d()` layer will effects the size of the output shape.\n",
- "\n",
- "In our case, the shape halves from a `62x62` image to `31x31` image.\n",
- "\n",
- "Let's see this work with a smaller tensor."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 41,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "knU2SNx-qD6o",
- "outputId": "f0b2132a-ff8d-4991-ad64-fcac0e3d5bc9"
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Random tensor:\n",
- "tensor([[[[0.3367, 0.1288],\n",
- " [0.2345, 0.2303]]]])\n",
- "Random tensor shape: torch.Size([1, 1, 2, 2])\n",
- "\n",
- "Max pool tensor:\n",
- "tensor([[[[0.3367]]]]) <- this is the maximum value from random_tensor\n",
- "Max pool tensor shape: torch.Size([1, 1, 1, 1])\n"
- ]
- }
- ],
- "source": [
- "torch.manual_seed(42)\n",
- "# Create a random tensor with a similiar number of dimensions to our images\n",
- "random_tensor = torch.randn(size=(1, 1, 2, 2))\n",
- "print(f\"Random tensor:\\n{random_tensor}\")\n",
- "print(f\"Random tensor shape: {random_tensor.shape}\")\n",
- "\n",
- "# Create a max pool layer\n",
- "max_pool_layer = nn.MaxPool2d(kernel_size=2) # see what happens when you change the kernel_size value \n",
- "\n",
- "# Pass the random tensor through the max pool layer\n",
- "max_pool_tensor = max_pool_layer(random_tensor)\n",
- "print(f\"\\nMax pool tensor:\\n{max_pool_tensor} <- this is the maximum value from random_tensor\")\n",
- "print(f\"Max pool tensor shape: {max_pool_tensor.shape}\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "gz4UbBFLqGdy"
- },
- "source": [
- "Notice the final two dimensions between `random_tensor` and `max_pool_tensor`, they go from `[2, 2]` to `[1, 1]`.\n",
- "\n",
- "In essence, they get halved.\n",
- "\n",
- "And the change would be different for different values of `kernel_size` for `nn.MaxPool2d()`.\n",
- "\n",
- "Also notice the value leftover in `max_pool_tensor` is the **maximum** value from `random_tensor`.\n",
- "\n",
- "What's happening here?\n",
- "\n",
- "This is another important piece of the puzzle of neural networks.\n",
- "\n",
- "Essentially, **every layer in a neural network is trying to compress data from higher dimensional space to lower dimensional space**. \n",
- "\n",
- "In other words, take a lot of numbers (raw data) and learn patterns in those numbers, patterns that are predictive whilst also being *smaller* in size than the original values.\n",
- "\n",
- "From an artificial intelligence perspective, you could consider the whole goal of a neural network to *compress* information.\n",
- "\n",
- "\n",
- "\n",
- "This means, that from the point of view of a neural network, intelligence is compression.\n",
- "\n",
- "This is the idea of the use of a `nn.MaxPool2d()` layer: take the maximum value from a portion of a tensor and disregard the rest.\n",
- "\n",
- "In essence, lowering the dimensionality of a tensor whilst still retaining a (hopefully) significant portion of the information.\n",
- "\n",
- "It is the same story for a `nn.Conv2d()` layer.\n",
- "\n",
- "Except instead of just taking the maximum, the `nn.Conv2d()` performs a conovlutional operation on the data (see this in action on the [CNN Explainer webpage](https://poloclub.github.io/cnn-explainer/)).\n",
- "\n",
- "> **Exercise:** What do you think the [`nn.AvgPool2d()`](https://pytorch.org/docs/stable/generated/torch.nn.AvgPool2d.html) layer does? Try making a random tensor like we did above and passing it through. Check the input and output shapes as well as the input and output values.\n",
- "\n",
- "> **Extra-curriculum:** Lookup \"most common convolutional neural networks\", what architectures do you find? Are any of them contained within the [`torchvision.models`](https://pytorch.org/vision/stable/models.html) library? What do you think you could do with these?"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "xdq3qYlCqLo3"
- },
- "source": [
- "### TK - 7.2 Setup a loss function and optimizer\n",
- "\n",
- "We've stepped through the layers in our first CNN enough.\n",
- "\n",
- "But remember, if something still isn't clear, try starting small.\n",
- "\n",
- "Pick a single layer of a model, pass some data through it and see what happens.\n",
- "\n",
- "Now it's time to move forward and get to training!\n",
- "\n",
- "Let's setup a loss function and an optimizer.\n",
- "\n",
- "We'll use the functions as before, `nn.CrossEntropyLoss()` as the loss function (since we're working with multi-class classification data).\n",
- "\n",
- "And `torch.optim.SGD()` as the optimizer to optimize `model_2.parameters()` with a learning rate of `0.1`."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 42,
- "metadata": {
- "id": "6RiPq-OfqIq0"
- },
- "outputs": [],
- "source": [
- "# Setup loss and optimizer\n",
- "loss_fn = nn.CrossEntropyLoss()\n",
- "optimizer = torch.optim.SGD(params=model_2.parameters(), \n",
- " lr=0.1)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "0gogtr-DqOSc"
- },
- "source": [
- "### 7.3 Training and testing model_2 using our training and test functions\n",
- "\n",
- "Loss and optimizer ready!\n",
- "\n",
- "Time to train and test.\n",
- "\n",
- "We'll use our `train_step()` and `test_step()` functions we created before.\n",
- "\n",
- "We'll also measure the time to compare it to our other models."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 43,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "raZ9MUupqNDr",
- "outputId": "eb43922d-275e-426c-81c2-034e2071d261"
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Epoch: 0\n",
- "---------\n",
- "Train loss: 0.47664 | Train accuracy: 83.43%\n",
- "Test loss: 0.40529 | Test accuracy: 85.52%\n",
- "\n",
- "Epoch: 1\n",
- "---------\n",
- "Train loss: 0.47664 | Train accuracy: 83.43%\n",
- "Test loss: 0.35944 | Test accuracy: 86.49%\n",
- "\n",
- "Epoch: 2\n",
- "---------\n",
- "Train loss: 0.47664 | Train accuracy: 83.43%\n",
- "Test loss: 0.33722 | Test accuracy: 87.54%\n",
- "\n",
- "Train time on cpu: 195.082 seconds\n"
- ]
- }
- ],
- "source": [
- "torch.manual_seed(42)\n",
- "\n",
- "# Measure time\n",
- "from timeit import default_timer as timer\n",
- "train_time_start_model_2 = timer()\n",
- "\n",
- "# Train and test model \n",
- "epochs = 3\n",
- "for epoch in range(epochs):\n",
- " print(f\"Epoch: {epoch}\\n---------\")\n",
- " train_step(data_loader=train_dataloader, \n",
- " model=model_2, \n",
- " loss_fn=loss_fn,\n",
- " optimizer=optimizer,\n",
- " accuracy_fn=accuracy_fn,\n",
- " device=device\n",
- " )\n",
- " test_step(data_loader=test_dataloader,\n",
- " model=model_2,\n",
- " loss_fn=loss_fn,\n",
- " accuracy_fn=accuracy_fn,\n",
- " device=device\n",
- " )\n",
- "\n",
- "train_time_end_model_2 = timer()\n",
- "total_train_time_model_2 = print_train_time(start=train_time_start_model_2,\n",
- " end=train_time_end_model_2,\n",
- " device=device)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "3x0RXD3vqP98"
- },
- "source": [
- "Woah! Looks like the convolutional and max pooling layers helped improve performance a little.\n",
- "\n",
- "Let's evaluate `model_2`'s results with our `eval_model()` function."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 44,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "Acv0eUPBqRiO",
- "outputId": "cd0157f7-e448-44da-8fc2-42c486915276"
- },
- "outputs": [
- {
- "data": {
- "text/plain": [
- "{'model_acc': 87.53993610223642,\n",
- " 'model_loss': 0.3372233211994171,\n",
- " 'model_name': 'FashionMNISTModelV2'}"
- ]
- },
- "execution_count": 44,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "# Get model_2 results \n",
- "model_2_results = eval_model(\n",
- " model=model_2,\n",
- " data_loader=test_dataloader,\n",
- " loss_fn=loss_fn,\n",
- " accuracy_fn=accuracy_fn\n",
- ")\n",
- "model_2_results"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {
- "id": "GuD2APG7qSfX"
- },
- "source": [
- "## TK - 8. Compare model results and training time\n",
- "\n",
- "We've trained three different models.\n",
- "\n",
- "1. `model_0` - our baseline model with two `nn.Linear()` layers.\n",
- "2. `model_1` - the same setup as our baseline model except with `nn.ReLU()` layers in between the `nn.Linear()` layers.\n",
- "3. `model_2` - our first CNN model that mimics the TinyVGG architecture on the CNN Explainer website.\n",
- "\n",
- "This is a regular practice in machine learning.\n",
- "\n",
- "Building multiple models and performing multiple training experiments to see which performs best.\n",
- "\n",
- "Let's combine our model results dictionaries into a DataFrame and find out."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 45,
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/",
- "height": 143
- },
- "id": "YVaHEr8bqUcH",
- "outputId": "b212f676-f6d0-4a04-e031-c64275dcc707"
- },
- "outputs": [
- {
- "data": {
- "text/html": [
- "\n",
- "