diff --git a/03_pytorch_computer_vision.ipynb b/03_pytorch_computer_vision.ipynb index ba914a9..c49981d 100644 --- a/03_pytorch_computer_vision.ipynb +++ b/03_pytorch_computer_vision.ipynb @@ -104,7 +104,7 @@ }, { "cell_type": "code", - "execution_count": 123, + "execution_count": 1, "metadata": {}, "outputs": [ { @@ -170,7 +170,7 @@ }, { "cell_type": "code", - "execution_count": 124, + "execution_count": 2, "metadata": {}, "outputs": [], "source": [ @@ -201,7 +201,7 @@ }, { "cell_type": "code", - "execution_count": 126, + "execution_count": 3, "metadata": {}, "outputs": [ { @@ -322,7 +322,7 @@ " 9)" ] }, - "execution_count": 126, + "execution_count": 3, "metadata": {}, "output_type": "execute_result" } @@ -346,7 +346,7 @@ }, { "cell_type": "code", - "execution_count": 127, + "execution_count": 4, "metadata": {}, "outputs": [ { @@ -355,7 +355,7 @@ "torch.Size([1, 28, 28])" ] }, - "execution_count": 127, + "execution_count": 4, "metadata": {}, "output_type": "execute_result" } @@ -400,7 +400,7 @@ }, { "cell_type": "code", - "execution_count": 151, + "execution_count": 5, "metadata": {}, "outputs": [ { @@ -409,7 +409,7 @@ "(60000, 60000, 10000, 10000)" ] }, - "execution_count": 151, + "execution_count": 5, "metadata": {}, "output_type": "execute_result" } @@ -432,7 +432,7 @@ }, { "cell_type": "code", - "execution_count": 153, + "execution_count": 6, "metadata": {}, "outputs": [ { @@ -450,7 +450,7 @@ " 'Ankle boot']" ] }, - "execution_count": 153, + "execution_count": 6, "metadata": {}, "output_type": "execute_result" } @@ -467,6 +467,8 @@ "source": [ "Sweet! It looks like we're dealing with 10 different kinds of clothes.\n", "\n", + "Because we're working with 10 different classes, it means our problem is **multi-class classification**.\n", + "\n", "Let's get visual.\n", "\n", "### 1.2 Visualing our data" @@ -474,7 +476,7 @@ }, { "cell_type": "code", - "execution_count": 154, + "execution_count": 7, "metadata": {}, "outputs": [ { @@ -514,7 +516,7 @@ }, { "cell_type": "code", - "execution_count": 99, + "execution_count": 8, "metadata": {}, "outputs": [ { @@ -546,7 +548,7 @@ }, { "cell_type": "code", - "execution_count": 155, + "execution_count": 9, "metadata": {}, "outputs": [ { @@ -636,14 +638,14 @@ }, { "cell_type": "code", - "execution_count": 157, + "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "Dataloaders: (, )\n", + "Dataloaders: (, )\n", "Length of train dataloader: 1875 batches of 32\n", "Length of test dataloader: 313 batches of 32\n" ] @@ -681,7 +683,7 @@ }, { "cell_type": "code", - "execution_count": 158, + "execution_count": 11, "metadata": {}, "outputs": [ { @@ -690,7 +692,7 @@ "(torch.Size([32, 1, 28, 28]), torch.Size([32]))" ] }, - "execution_count": 158, + "execution_count": 11, "metadata": {}, "output_type": "execute_result" } @@ -710,7 +712,7 @@ }, { "cell_type": "code", - "execution_count": 159, + "execution_count": 12, "metadata": {}, "outputs": [ { @@ -777,7 +779,7 @@ }, { "cell_type": "code", - "execution_count": 165, + "execution_count": 13, "metadata": {}, "outputs": [ { @@ -825,7 +827,7 @@ }, { "cell_type": "code", - "execution_count": 166, + "execution_count": 21, "metadata": {}, "outputs": [], "source": [ @@ -847,12 +849,21 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "UPTOHERE: setting up `model_0` with input and output shapes" + "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": 167, + "execution_count": 22, "metadata": {}, "outputs": [ { @@ -867,13 +878,13 @@ ")" ] }, - "execution_count": 167, + "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ - "torch.manaul_seed(42)\n", + "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", @@ -887,12 +898,16 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### TK - 3.1 Setup loss, optimizer and evaluation metrics for Model 1" + "### 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.\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": 168, + "execution_count": 23, "metadata": {}, "outputs": [ { @@ -912,14 +927,26 @@ " 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": {}, + "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": 169, + "execution_count": 24, "metadata": {}, "outputs": [], "source": [ @@ -931,9 +958,28 @@ "optimizer = torch.optim.SGD(params=model_0.parameters(), lr=0.1)" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "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": 170, + "execution_count": 25, "metadata": {}, "outputs": [], "source": [ @@ -954,84 +1000,97 @@ " return total_time" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "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", + "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", + "UPTOHERE: writing about the training loop with batches" + ] + }, { "cell_type": "code", - "execution_count": 171, + "execution_count": 31, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ + "Epoch: 0\n", + "------\n", + "Looked at 0/60000 samples\n", + "Looked at 9600/60000 samples\n", + "Looked at 19200/60000 samples\n", + "Looked at 28800/60000 samples\n", + "Looked at 38400/60000 samples\n", + "Looked at 48000/60000 samples\n", + "Looked at 57600/60000 samples\n", + "Train loss: 0.41008 | Test loss: 0.45462, Test acc: 84.07%\n", "\n", - "Epoch 1\n", - "----------\n", - "Loss: 2.36648 | Looked at 0/60000 samples\n", - "Loss: 0.60986 | Looked at 8000/60000 samples\n", - "Loss: 0.47039 | Looked at 16000/60000 samples\n", - "Loss: 0.27831 | Looked at 24000/60000 samples\n", - "Loss: 0.55116 | Looked at 32000/60000 samples\n", - "Loss: 0.39052 | Looked at 40000/60000 samples\n", - "Loss: 0.66560 | Looked at 48000/60000 samples\n", - "Loss: 0.18336 | Looked at 56000/60000 samples\n", + "Epoch: 1\n", + "------\n", + "Looked at 0/60000 samples\n", + "Looked at 9600/60000 samples\n", + "Looked at 19200/60000 samples\n", + "Looked at 28800/60000 samples\n", + "Looked at 38400/60000 samples\n", + "Looked at 48000/60000 samples\n", + "Looked at 57600/60000 samples\n", + "Train loss: 0.40939 | Test loss: 0.45683, Test acc: 84.23%\n", "\n", - "Testing for Epoch: 0\n", - "----------\n", - "Test loss: 0.50954 | Test accuracy: 82.04%\n", + "Epoch: 2\n", + "------\n", + "Looked at 0/60000 samples\n", + "Looked at 9600/60000 samples\n", + "Looked at 19200/60000 samples\n", + "Looked at 28800/60000 samples\n", + "Looked at 38400/60000 samples\n", + "Looked at 48000/60000 samples\n", + "Looked at 57600/60000 samples\n", + "Train loss: 0.40701 | Test loss: 0.46177, Test acc: 84.20%\n", "\n", "\n", - "Epoch 2\n", - "----------\n", - "Loss: 0.37993 | Looked at 0/60000 samples\n", - "Loss: 0.75278 | Looked at 8000/60000 samples\n", - "Loss: 0.40076 | Looked at 16000/60000 samples\n", - "Loss: 0.42626 | Looked at 24000/60000 samples\n", - "Loss: 0.38653 | Looked at 32000/60000 samples\n", - "Loss: 0.34046 | Looked at 40000/60000 samples\n", - "Loss: 0.63605 | Looked at 48000/60000 samples\n", - "Loss: 0.30932 | Looked at 56000/60000 samples\n", - "\n", - "Testing for Epoch: 1\n", - "----------\n", - "Test loss: 0.47989 | Test accuracy: 83.20%\n", - "\n", - "\n", - "Epoch 3\n", - "----------\n", - "Loss: 0.36814 | Looked at 0/60000 samples\n", - "Loss: 0.52180 | Looked at 8000/60000 samples\n", - "Loss: 0.27517 | Looked at 16000/60000 samples\n", - "Loss: 0.35602 | Looked at 24000/60000 samples\n", - "Loss: 0.19280 | Looked at 32000/60000 samples\n", - "Loss: 0.52069 | Looked at 40000/60000 samples\n", - "Loss: 0.33512 | Looked at 48000/60000 samples\n", - "Loss: 0.62176 | Looked at 56000/60000 samples\n", - "\n", - "Testing for Epoch: 2\n", - "----------\n", - "Test loss: 0.47664 | Test accuracy: 83.43%\n", - "\n", - "\n", - "Train time on cpu: 15.236 seconds\n" + "Train time on cpu: 15.511 seconds\n" ] } ], "source": [ + "from tqdm import tqdm\n", + "# Set the seed and start the timer\n", "torch.manual_seed(42)\n", "train_time_start_on_cpu = timer()\n", "\n", - "# Create training loop\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\"\\nEpoch {epoch+1}\\n----------\")\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", - " # Training\n", + " model_0.train() \n", " # 1. Forward pass\n", - " # print(X.shape)\n", " y_pred = model_0(X)\n", "\n", - " # 2. Calculate loss\n", + " # 2. Calculate loss (per batch)\n", " loss = loss_fn(y_pred, y)\n", + " train_loss += loss\n", "\n", " # 3. Optimizer zero grad\n", " optimizer.zero_grad()\n", @@ -1042,33 +1101,37 @@ " # 5. Optimizer step\n", " optimizer.step()\n", "\n", - " # Print out what's happening\n", - " if batch % 250 == 0:\n", - " batch_number = batch * len(X)\n", - " print(f\"Loss: {loss:.5f} | Looked at {batch_number}/{len(train_dataloader.dataset)} samples\")\n", + " # Print out how many samples have been seen\n", + " if batch % 300 == 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", - " test_loss, test_acc = 0, 0\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", - " \n", " for X, y in test_dataloader:\n", " # 1. Forward pass\n", " test_pred = model_0(X)\n", - " # print(test_pred)\n", + " \n", " # 2. Calculate loss (accumatively)\n", " test_loss += loss_fn(test_pred, y)\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", - " # print(test_acc)\n", - " \n", - " # Divide total loss by length of test dataloader (per batch)\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", - " print(f\"\\nTesting for Epoch: {epoch}\\n----------\")\n", - " print(f\"Test loss: {test_loss:.5f} | Test accuracy: {test_acc:.2f}%\\n\")\n", + "\n", + " ## Print out what's happening\n", + " print(f\"Train 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",