mirror of
https://github.com/mrdbourke/pytorch-deep-learning.git
synced 2026-11-27 06:07:09 +00:00
add section 06
This commit is contained in:
1 parent
a80d1c0dde
commit
a5ffbdda80
1 file changed
+459
-1
@@ -1316,10 +1316,468 @@
|
||||
"Let's build another model."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "7a1a6190-d1c2-4181-a321-09e242e4b3a7",
|
||||
"metadata": {},
|
||||
"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": 28,
|
||||
"id": "42662f5d-c745-42b7-90ae-ef600239400e",
|
||||
"metadata": {},
|
||||
"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",
|
||||
"id": "c7ed174d-b453-4e0d-8650-e3028a5efd05",
|
||||
"metadata": {},
|
||||
"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": 29,
|
||||
"id": "a6c152ce-0c44-482f-910d-48a1e0d1b7b9",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"device(type='cuda', index=0)"
|
||||
]
|
||||
},
|
||||
"execution_count": 29,
|
||||
"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",
|
||||
"id": "27c77a7e-7317-4b39-8e71-2a5b02ec896f",
|
||||
"metadata": {},
|
||||
"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": 30,
|
||||
"id": "72b47198-af5f-4438-8caa-bcbfa757bd82",
|
||||
"metadata": {},
|
||||
"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",
|
||||
"id": "b0849c87-5d9a-461b-ac09-ef2b48856910",
|
||||
"metadata": {},
|
||||
"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": 31,
|
||||
"id": "509002b3-3e9a-4653-9269-0c1736b567b9",
|
||||
"metadata": {},
|
||||
"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",
|
||||
"id": "0d461b1a-306f-4c6e-87e2-d7c7bbe44fda",
|
||||
"metadata": {},
|
||||
"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": 32,
|
||||
"id": "8042c099-cbb3-4fd6-932b-55e328959f56",
|
||||
"metadata": {},
|
||||
"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 cuda: 17.869 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",
|
||||
"id": "3fd91b08-32e9-4a01-8e5a-fcb0abbd879f",
|
||||
"metadata": {},
|
||||
"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": 33,
|
||||
"id": "af4af755-a34d-4cd2-82ef-0e7505a2a988",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"ename": "RuntimeError",
|
||||
"evalue": "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)",
|
||||
"output_type": "error",
|
||||
"traceback": [
|
||||
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
|
||||
"\u001b[0;31mRuntimeError\u001b[0m Traceback (most recent call last)",
|
||||
"\u001b[0;32m/tmp/ipykernel_285283/2906876561.py\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;31m# Note: This will error due to `eval_model()` not using device agnostic code\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m model_1_results = eval_model(model=model_1, \n\u001b[0m\u001b[1;32m 5\u001b[0m \u001b[0mdata_loader\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mtest_dataloader\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0mloss_fn\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mloss_fn\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
|
||||
"\u001b[0;32m/tmp/ipykernel_285283/2300884397.py\u001b[0m in \u001b[0;36meval_model\u001b[0;34m(model, data_loader, loss_fn, accuracy_fn)\u001b[0m\n\u001b[1;32m 20\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mX\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0my\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mdata_loader\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 21\u001b[0m \u001b[0;31m# Make predictions with the model\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 22\u001b[0;31m \u001b[0my_pred\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mmodel\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mX\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 23\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 24\u001b[0m \u001b[0;31m# Accumulate the loss and accuracy values per batch\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
|
||||
"\u001b[0;32m~/code/pytorch/env/lib/python3.9/site-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[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/tmp/ipykernel_285283/1125546949.py\u001b[0m in \u001b[0;36mforward\u001b[0;34m(self, x)\u001b[0m\n\u001b[1;32m 12\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 13\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[0mx\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---> 14\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mlayer_stack\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
|
||||
"\u001b[0;32m~/code/pytorch/env/lib/python3.9/site-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[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~/code/pytorch/env/lib/python3.9/site-packages/torch/nn/modules/container.py\u001b[0m in \u001b[0;36mforward\u001b[0;34m(self, input)\u001b[0m\n\u001b[1;32m 139\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[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 140\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mmodule\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 141\u001b[0;31m \u001b[0minput\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mmodule\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minput\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 142\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0minput\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 143\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
|
||||
"\u001b[0;32m~/code/pytorch/env/lib/python3.9/site-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[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~/code/pytorch/env/lib/python3.9/site-packages/torch/nn/modules/linear.py\u001b[0m in \u001b[0;36mforward\u001b[0;34m(self, input)\u001b[0m\n\u001b[1;32m 101\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 102\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--> 103\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mF\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mlinear\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 104\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 105\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mextra_repr\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m->\u001b[0m \u001b[0mstr\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
|
||||
"\u001b[0;32m~/code/pytorch/env/lib/python3.9/site-packages/torch/nn/functional.py\u001b[0m in \u001b[0;36mlinear\u001b[0;34m(input, weight, bias)\u001b[0m\n\u001b[1;32m 1846\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mhas_torch_function_variadic\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minput\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mweight\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[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1847\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mhandle_torch_function\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlinear\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0minput\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mweight\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mbias\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0minput\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mweight\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mbias\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[0;32m-> 1848\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mtorch\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_C\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_nn\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mlinear\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minput\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mweight\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 1849\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 1850\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
|
||||
"\u001b[0;31mRuntimeError\u001b[0m: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! (when checking argument for argument mat1 in method wrapper_addmm)"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"torch.manual_seed(42)\n",
|
||||
"\n",
|
||||
"# Note: This will error due to `eval_model()` not using device agnostic code \n",
|
||||
"model_1_results = eval_model(model=model_1, \n",
|
||||
" data_loader=test_dataloader,\n",
|
||||
" loss_fn=loss_fn, \n",
|
||||
" accuracy_fn=accuracy_fn) \n",
|
||||
"model_1_results "
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "5284dccd-e4a2-48a1-a320-f64c8546b714",
|
||||
"metadata": {},
|
||||
"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": 34,
|
||||
"id": "3a1da665-b274-4f2d-9d92-a58a36b69df7",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"{'model_name': 'FashionMNISTModelV1',\n",
|
||||
" 'model_loss': 0.6850008964538574,\n",
|
||||
" 'model_acc': 75.01996805111821}"
|
||||
]
|
||||
},
|
||||
"execution_count": 34,
|
||||
"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": 35,
|
||||
"id": "fbb49530-6cfe-4f36-a8a0-b7fd8af13dbd",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"{'model_name': 'FashionMNISTModelV0',\n",
|
||||
" 'model_loss': 0.47663894295692444,\n",
|
||||
" 'model_acc': 83.42651757188499}"
|
||||
]
|
||||
},
|
||||
"execution_count": 35,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"# Check baseline results\n",
|
||||
"model_0_results"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "bee28a01-c6c5-4214-9ac7-71cc0dcf506f",
|
||||
"metadata": {},
|
||||
"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": "code",
|
||||
"execution_count": null,
|
||||
"id": "21792850-97dc-4b28-867a-d9f272440b98",
|
||||
"id": "994fda81-afad-4a6f-96b8-6a841f5d5f4e",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": []
|
||||
|
||||
Reference in new issue
Block a user