add more annotations

This commit is contained in:
Daniel Bourke committed 2022-01-26 09:33:37 +10:00
1 parent 5441a678c3
commit 9cf53deef6
1 file changed
+345 -208
+345 -208
View File
@@ -27,6 +27,13 @@
"How about we start with a straight line?\n",
"\n",
"And we see if we can build a model with PyTorch to that straight line.\n",
"\n"
]
},
{
"cell_type": "markdown",
"source": [
"\n",
"\n",
"## What we're going to cover\n",
"\n",
@@ -46,6 +53,15 @@
"| **4. Making predictions and evaluating a model (inference)** | Our model's found patterns in the data, let's compare its findings to the actual (**testing**) data. |\n",
"| **5. Saving and loading a model** | You may want to use your model elsewhere, or come back to it later, here we'll cover that. |\n",
"| **6. Putting it all together** | Let's take all of the above and combine it. |\n",
"\n"
],
"metadata": {
"id": "51Ug7Ug123Ip"
}
},
{
"cell_type": "markdown",
"source": [
"\n",
"## Where can can you get help?\n",
"\n",
@@ -56,11 +72,14 @@
"There's also the [PyTorch developer forums](https://discuss.pytorch.org/), a very helpful place for all things PyTorch. \n",
"\n",
"Let's start by putting what we're covering into a dictionary to reference later.\n"
]
],
"metadata": {
"id": "kKC3ugfM25e_"
}
},
{
"cell_type": "code",
"execution_count": 1,
"execution_count": 100,
"metadata": {
"id": "nGM1dEsYec0u"
},
@@ -88,14 +107,14 @@
},
{
"cell_type": "code",
"execution_count": 2,
"execution_count": 101,
"metadata": {
"id": "ZT_ikDC-ec0w",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 35
},
"outputId": "4a90a60b-35ea-462b-a857-3640d701812c"
"outputId": "cc532d25-035f-4197-d84a-0c91a7098b46"
},
"outputs": [
{
@@ -109,7 +128,7 @@
]
},
"metadata": {},
"execution_count": 2
"execution_count": 101
}
],
"source": [
@@ -155,10 +174,10 @@
},
{
"cell_type": "code",
"execution_count": 3,
"execution_count": 102,
"metadata": {
"id": "HmZWVNjGec0x",
"outputId": "3205f715-61b8-4125-aaac-3603dd45bc67",
"outputId": "9d25f1ac-e821-4671-a1f5-343a3951542b",
"colab": {
"base_uri": "https://localhost:8080/"
}
@@ -190,7 +209,7 @@
]
},
"metadata": {},
"execution_count": 3
"execution_count": 102
}
],
"source": [
@@ -248,10 +267,10 @@
},
{
"cell_type": "code",
"execution_count": 4,
"execution_count": 103,
"metadata": {
"id": "BpyB7JgHec0y",
"outputId": "68c33523-1ad7-4a54-a2f3-187cd4caaf8e",
"outputId": "febfe47e-1d87-431d-fe4e-61f62f634e2a",
"colab": {
"base_uri": "https://localhost:8080/"
}
@@ -265,7 +284,7 @@
]
},
"metadata": {},
"execution_count": 4
"execution_count": 103
}
],
"source": [
@@ -294,7 +313,7 @@
},
{
"cell_type": "code",
"execution_count": 5,
"execution_count": 104,
"metadata": {
"id": "w9Ep0T-Dec0y"
},
@@ -326,10 +345,10 @@
},
{
"cell_type": "code",
"execution_count": 6,
"execution_count": 105,
"metadata": {
"id": "xTaIwydGec0z",
"outputId": "04cd0f80-0e84-4aa5-9c2c-2ddf9b7ca11b",
"outputId": "129f0b1e-a8d7-4938-d286-e9591856252b",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 428
@@ -389,7 +408,7 @@
},
{
"cell_type": "code",
"execution_count": 7,
"execution_count": 106,
"metadata": {
"id": "jhcUJBFuec00"
},
@@ -469,10 +488,10 @@
},
{
"cell_type": "code",
"execution_count": 8,
"execution_count": 107,
"metadata": {
"id": "CsEKA3A_ec01",
"outputId": "eb8c175c-4bf7-4498-df1b-49205003a59f",
"outputId": "3c37a8d7-486a-4b2d-a78b-a9bb0f212b62",
"colab": {
"base_uri": "https://localhost:8080/"
}
@@ -488,7 +507,7 @@
]
},
"metadata": {},
"execution_count": 8
"execution_count": 107
}
],
"source": [
@@ -513,10 +532,10 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 108,
"metadata": {
"id": "XC1N_1Qrec01",
"outputId": "38f7ff61-62fe-4c77-e2c9-f1708de7a33d",
"outputId": "b8f01de4-74eb-49b3-f612-7b1abeab5c09",
"colab": {
"base_uri": "https://localhost:8080/"
}
@@ -530,7 +549,7 @@
]
},
"metadata": {},
"execution_count": 19
"execution_count": 108
}
],
"source": [
@@ -572,7 +591,7 @@
},
{
"cell_type": "code",
"execution_count": 10,
"execution_count": 109,
"metadata": {
"id": "-ITlZgU5ec02"
},
@@ -609,10 +628,10 @@
},
{
"cell_type": "code",
"execution_count": 14,
"execution_count": 110,
"metadata": {
"id": "k4xCScCvec02",
"outputId": "b81699a2-96d8-48e3-a47c-67d35d245bf9",
"outputId": "df2d2f18-c893-4469-838a-559d71a506f6",
"colab": {
"base_uri": "https://localhost:8080/"
}
@@ -662,10 +681,10 @@
},
{
"cell_type": "code",
"execution_count": 15,
"execution_count": 111,
"metadata": {
"id": "pwjxLWZTec02",
"outputId": "54329d51-5e51-492a-d1a5-aa5bd058e090",
"outputId": "10d52b00-dddd-448f-a227-88c344ea2432",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 428
@@ -721,159 +740,150 @@
"Much of the time you won't know what the ideal parameters are for a model.\n",
"\n",
"Instead, it's much more fun to write code to see if the model can try and figure them out itself.\n",
"\n"
]
},
{
"cell_type": "markdown",
"source": [
"### Creating a loss function and optimizer in PyTorch\n",
"\n",
"To do so, we'll need to add a few more things to our recipe.\n",
"For our model to update its parameters on its own, we'll need to add a few more things to our recipe.\n",
"\n",
"And that's a **loss function** as well as an **optimizer**.\n",
"\n",
"The rolls of these are: \n",
"* **Loss function** - Measures how wrong your models predictions (e.g. `y_preds`) are compared to the truth labels (e.g. `y_test`). Lower the better.\n",
"* **Optimizer** - Tells your model how to update its internal parameters to best lower the loss.\n",
"\n",
"UPTOHERE - continuing with loss function and optimizer defintions + diagrams\n",
"| Function | What does it do? | Where does it live in PyTorch? | Common values |\n",
"| ----- | ----- | ----- | ----- |\n",
"| **Loss function** | Measures how wrong your models predictions (e.g. `y_preds`) are compared to</br> the truth labels (e.g. `y_test`). Lower the better. | PyTorch has plenty of built-in loss functions in [`torch.nn`](https://pytorch.org/docs/stable/nn.html#loss-functions). | Mean absolute error (MAE) for regression problems ([`torch.nn.L1Loss()`](https://pytorch.org/docs/stable/generated/torch.nn.L1Loss.html)).</br>Binary cross entropy for binary classification problems ([`torch.nn.BCELoss()`](https://pytorch.org/docs/stable/generated/torch.nn.BCELoss.html)). |\n",
"| **Optimizer** | Tells your model how to update its internal parameters to best lower the loss. | You can find various optimization function implementations in [`torch.optim`](https://pytorch.org/docs/stable/optim.html). | Stochastic gradient descent ([`torch.optim.SGD()`](https://pytorch.org/docs/stable/generated/torch.optim.SGD.html#torch.optim.SGD)).</br>Adam optimizer ([`torch.optim.Adam()`](https://pytorch.org/docs/stable/generated/torch.optim.Adam.html#torch.optim.Adam)). | \n",
"\n",
"Let's create a loss function and an optimizer we can use to help improve our model.\n",
"\n",
"Depending on what kind of problem you're working on will depend on what loss function and what optimizer you use.\n",
"\n",
"However, there are some common values, that are known to work well such as the SGD (stochastic gradient descent) or Adam optimizer. And the MAE (mean absolute error) loss function for regression problems (predicting a number) or binary cross entropy loss function for classification problems (predicting one thing or another). \n",
"\n",
"For our problem, since we're predicting a number, let's use MAE (which is under `torch.nn.L1Loss()`) in PyTorch as our loss function. \n",
"\n",
"And we'll use SGD, `torch.optim.SGD(params, lr)` where:\n",
"\n",
"* `params` is the target model parameters you'd like to optimize (e.g. the `weights` and `bias` values we randomly set before).\n",
"* `lr` is the **learning rate** you'd like the optimizer to update the parameters at, higher means the optimizer will try larger updates (these can sometimes be too large and the optimizer will fail to work), lower means the optimizer will try smaller updates (these can sometimes be too small and the optimizer will take too long to find the ideal values). The learning rate is considered a **hyperparamter** (because it's set by a machine learning engineer). Common starting values for the learning rate are `0.01`, `0.001`, `0.0001`, however, these can also be adjusted over time (this is called [learning rate scheduling](https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate)). \n",
"\n",
"Woah, that's a lot, let's see it in code.\n",
"\n",
"* TK: image - loss function (show graphic for loss function, MAE is distance between the dot points)"
]
],
"metadata": {
"id": "aD8pnhJUyZUT"
}
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 112,
"metadata": {
"id": "P3T7hpNPec03"
},
"outputs": [],
"source": [
"loss_fn = nn.L1Loss() # MAE loss is same as L1Loss, https://pytorch.org/docs/stable/generated/torch.nn.L1Loss.html \n",
"optimizer = torch.optim.SGD(model_0.parameters(), lr=0.01)"
"# Create the loss function\n",
"loss_fn = nn.L1Loss() # MAE loss is same as L1Loss\n",
"\n",
"# Create the optimizer\n",
"optimizer = torch.optim.SGD(params=model_0.parameters(), # parameters of target model to optimize\n",
" lr=0.01) # learning rate (how much the optimizer should change parameters at each step, higher=more (less stable), lower=less (might take a long time))"
]
},
{
"cell_type": "code",
"cell_type": "markdown",
"source": [
"y_preds - y_test"
"### Creating a training loop in PyTorch\n",
"\n",
"Woohoo! Now we've got a loss function and an optimizer, it's now time to create a **training loop** (and **testing loop**).\n",
"\n",
"The training loop involves the model going through the training data and learning the relationships between the `features` and `labels`.\n",
"\n",
"The testing loop involves going through the testing data and evaluating how good the patterns are that the model learned on the training data (the model never see's the testing data during training).\n",
"\n",
"Each of these is called a \"loop\" because we want our model to look (loop through) at each sample in each dataset.\n",
"\n",
"To create these we're going to write a Python `for` loop in the theme of the [PyTorch optimization loop song](https://twitter.com/mrdbourke/status/1450977868406673410?s=20).\n",
"\n",
"* TK - Image: PyTorch optimization loop song\n",
"\n",
"There will be a fair bit of code but nothing we can't handle.\n",
"\n",
"Specifically for the training loop, we'll follow the following steps:\n",
"\n",
"| Number | Step name | What does it do? | Code example |\n",
"| ----- | ----- | ----- | ----- |\n",
"| 1 | Forward pass | The model goes through all of the training data once, performing its `forward()` function calculations. | `model(x_train)` |\n",
"| 2 | Calculate the loss | The model's outputs (predictions) are compared to the ground truth and evaluated to see how wrong they are. | `loss = loss_fn(y_pred, y_train)` | \n",
"| 3 | Zero gradients | The optimizers gradients are set to zero (they are accumulated by default) so they can be recalculated for the specific training step. | `optimizer.zero_grad()` |\n",
"| 4 | Perform backpropagation on the loss | Computes the gradients for every parameter to be updated (each parameter with `requires_grad=True`). This is known as **backpropagation**, hence \"backwards\". | `loss.backward()` |\n",
"| 5 | Update the optimizer (gradient descent) | Update the parameters with `requires_grad=True` with respect to the loss gradients in order to improve them. | `optimizer.step()` |\n",
"\n",
"> **Note:** The above is just one example of how the steps could be ordered or described. With experience you'll find making PyTorch training loops can be quite flexible.\n",
">\n",
"> And on the ordering of things, the above is a good default order but you may see slightly different orders, the only rule of thumb is to zero gradients (`optimizer.zero_grad`) *before* stepping them (`optimizer.step()`) and calculate the loss (`loss = ...`) *before* performing backpropagation on it (`loss.backward()`). Though there are exceptions to these, they are beyond the scope of the course.\n",
"\n",
"And a typical testing loop may contain the following steps:\n",
"\n",
"| Number | Step name | What does it do? | Code example |\n",
"| ----- | ----- | ----- | ----- |\n",
"| 1 | Forward pass | The model goes through all of the training data once, performing its `forward()` function calculations. | `model(x_test)` |\n",
"| 2 | Calculate the loss | The model's outputs (predictions) are compared to the ground truth and evaluated to see how wrong they are. | `loss = loss_fn(y_pred, y_test)` | \n",
"| 3 | Calulate evaluation metrics (optional) | Alongisde the loss value you may want to calculate other evaluation metrics such as accuracy on the test set. | Custom functions |\n",
"\n",
"Notice the testing loop doesn't contain performing backpropagation (`loss.backward()`) or stepping the optimizer (`optimizer.step()`), this is because no parameters in the model are being changed during testing, they've already been calculated. For testing, we're only interested in the output of the forward pass through the model.\n",
"\n",
"Let's put all of the above together and train our model for 100 **epochs** (forward passes through the data) and we'll evaluate it every 10 epochs.\n"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "qzKhVMpl1xPU",
"outputId": "ef691dcc-2d83-4811-f02b-e8e3035dbf8e"
},
"execution_count": 20,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"tensor([[-0.4618],\n",
" [-0.4691],\n",
" [-0.4764],\n",
" [-0.4836],\n",
" [-0.4909],\n",
" [-0.4982],\n",
" [-0.5054],\n",
" [-0.5127],\n",
" [-0.5200],\n",
" [-0.5272]])"
]
},
"metadata": {},
"execution_count": 20
}
]
"id": "aFcKCsPcRfnA"
}
},
{
"cell_type": "code",
"source": [
"torch.mean(torch.abs(y_preds - y_test))"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "3Fcb7bJy0gHl",
"outputId": "ef7a949d-43df-4af2-9ac8-f13dd634cfa6"
},
"execution_count": 19,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"tensor(0.4945)"
]
},
"metadata": {},
"execution_count": 19
}
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Tp6FtV8Oec03",
"outputId": "7052a711-7a48-4bbb-bc23-a140aad9fbd2"
},
"outputs": [
{
"data": {
"text/plain": [
"tensor([[0.8000],\n",
" [0.8200],\n",
" [0.8400],\n",
" [0.8600],\n",
" [0.8800],\n",
" [0.9000],\n",
" [0.9200],\n",
" [0.9400],\n",
" [0.9600],\n",
" [0.9800]])"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X_test"
]
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 116,
"metadata": {
"id": "k1DfhyJ7ec03",
"outputId": "6c625657-9306-4b47-ec5f-d7e4b8cc7bab"
"outputId": "f8ab850c-1da0-474e-f2f0-13272d2b27a3",
"colab": {
"base_uri": "https://localhost:8080/"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"name": "stdout",
"text": [
"Epoch: 0 | MAE Train Loss: 0.31288138031959534 | MAE Test Loss: 0.48106518387794495 \n",
"Epoch: 10 | MAE Train Loss: 0.1976713240146637 | MAE Test Loss: 0.3463551998138428 \n",
"Epoch: 20 | MAE Train Loss: 0.08908725529909134 | MAE Test Loss: 0.21729660034179688 \n",
"Epoch: 30 | MAE Train Loss: 0.053148526698350906 | MAE Test Loss: 0.14464017748832703 \n",
"Epoch: 40 | MAE Train Loss: 0.04543796554207802 | MAE Test Loss: 0.11360953003168106 \n",
"Epoch: 50 | MAE Train Loss: 0.04167863354086876 | MAE Test Loss: 0.09919948130846024 \n",
"Epoch: 60 | MAE Train Loss: 0.03818932920694351 | MAE Test Loss: 0.08886633068323135 \n",
"Epoch: 70 | MAE Train Loss: 0.03476089984178543 | MAE Test Loss: 0.0805937647819519 \n",
"Epoch: 80 | MAE Train Loss: 0.03132382780313492 | MAE Test Loss: 0.07232122868299484 \n",
"Epoch: 90 | MAE Train Loss: 0.02788739837706089 | MAE Test Loss: 0.06473556160926819 \n"
"Epoch: 0 | MAE Train Loss: 0.024458957836031914 | MAE Test Loss: 0.05646304413676262 \n",
"Epoch: 10 | MAE Train Loss: 0.021020207554101944 | MAE Test Loss: 0.04819049686193466 \n",
"Epoch: 20 | MAE Train Loss: 0.01758546568453312 | MAE Test Loss: 0.04060482233762741 \n",
"Epoch: 30 | MAE Train Loss: 0.014155393466353416 | MAE Test Loss: 0.03233227878808975 \n",
"Epoch: 40 | MAE Train Loss: 0.010716589167714119 | MAE Test Loss: 0.024059748277068138 \n",
"Epoch: 50 | MAE Train Loss: 0.0072835334576666355 | MAE Test Loss: 0.016474086791276932 \n",
"Epoch: 60 | MAE Train Loss: 0.0038517764769494534 | MAE Test Loss: 0.008201557211577892 \n",
"Epoch: 70 | MAE Train Loss: 0.008932482451200485 | MAE Test Loss: 0.005023092031478882 \n",
"Epoch: 80 | MAE Train Loss: 0.008932482451200485 | MAE Test Loss: 0.005023092031478882 \n",
"Epoch: 90 | MAE Train Loss: 0.008932482451200485 | MAE Test Loss: 0.005023092031478882 \n"
]
}
],
"source": [
"torch.manual_seed(42)\n",
"\n",
"# Create a new instance of the model (it isn't necessary to create a new instance here but we will anyway so everything fits in one cell)\n",
"model_0 = LinearRegressionModel()\n",
"\n",
"# Set the number of epochs (how many times the model will pass over the training data)\n",
"epochs = 100\n",
"\n",
"# Create empty loss lists to track values\n",
"train_loss_values = []\n",
"test_loss_values = []\n",
"epoch_count = []\n",
"\n",
"for epoch in range(epochs):\n",
" ### Training\n",
"\n",
@@ -882,6 +892,7 @@
"\n",
" # 1. Forward pass on train data using the forward() method inside \n",
" y_pred = model_0(X_train)\n",
" # print(y_pred)\n",
"\n",
" # 2. Calculate the loss (how different)\n",
" loss = loss_fn(y_pred, y_train)\n",
@@ -900,74 +911,128 @@
" # Put the model in evaluation mode\n",
" model_0.eval()\n",
"\n",
" # 1. Forward pass on test data\n",
" with torch.inference_mode():\n",
" test_pred = model_0(X_test)\n",
" # 1. Forward pass on test data\n",
" test_pred = model_0(X_test)\n",
"\n",
" # 2. Caculate loss on test data\n",
" test_loss = loss_fn(test_pred, y_test.type(torch.float)) # predictions come in torch.float datatype, so comparisons need to be done with tensors of the same type\n",
"\n",
" # Print out what's happening\n",
" if epoch % 10 == 0:\n",
" epoch_count.append(epoch)\n",
" train_loss_values.append(loss)\n",
" test_loss_values.append(test_loss)\n",
" print(f\"Epoch: {epoch} | MAE Train Loss: {loss} | MAE Test Loss: {test_loss} \")"
]
},
{
"cell_type": "markdown",
"source": [
"Oh would you look at that! Looks like our loss is going down with every epoch, let's plot it to find out."
],
"metadata": {
"id": "1krgBqXBdYHc"
}
},
{
"cell_type": "code",
"source": [
"# Plot the loss curves\n",
"plt.plot(epoch_count, train_loss_values, label=\"Train loss\")\n",
"plt.plot(epoch_count, test_loss_values, label=\"Test loss\")\n",
"plt.title(\"Training and test loss curves\")\n",
"plt.ylabel(\"Loss\")\n",
"plt.xlabel(\"Epochs\")\n",
"plt.legend();"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 295
},
"id": "FPXfvPLkau72",
"outputId": "7517559e-b9e4-48ab-cb84-c477303ee699"
},
"execution_count": 117,
"outputs": [
{
"output_type": "display_data",
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAYgAAAEWCAYAAAB8LwAVAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4yLjIsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+WH4yJAAAgAElEQVR4nO3deXgV5fX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xTJ48mVtvvZXZs2dz3333MX/+fBITE48M4/3000/zq1/9imuvvZaSkhLKy8tP6xL4Y3cQ1SkyBtJehJ7jYOEj8NZtUFH9vzRjjLcOHz7MihUruOKKK0hNTeX+++8nLy8PgG7dunHttdfy8ssvH3OWuWNZvHgxY8aMAWDs2LEsWrQIgAsuuIDx48fz7LPPHkkEffr04S9/+QsPP/wwmzdvpl696h/dwe4gqltYuDNEeP04WPQoHNwNw5+FiOgT72uMObGT+Es/UFSVLl26sHjxD1svzp07l08++YQ333yTBx54gK+/Pv27naeffprPP/+cuXPn0qtXL7KyshgzZgy9e/dm7ty5DBw4kP/85z9ceumlpLine truncated
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
}
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "lmqQE8Kpec04"
},
"source": [
"* TK - plot loss and epochs over time\n",
"* TK - Let's see how close our model gets to the original values for weights and bias\n",
"Nice! The **loss curves** show the loss going down over time. Remember, loss is the measure of how *wrong* your model is, so the lower the better.\n",
"\n",
"* This is the whole idea of machine learning and deep learning - there are some ideal values that describe our data, can we train a model to figure them out programmatically..."
"But why did the loss go down?\n",
"\n",
"Well, thanks to our loss function and optimizer, the model's internal parameters (`weights` and `bias`) were updated to better reflect the underlying patterns in the data.\n",
"\n",
"Let's inspect our model's [`.state_dict()`](https://pytorch.org/tutorials/recipes/recipes/what_is_state_dict.html) to see see how close our model gets to the original values we set for weights and bias.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 118,
"metadata": {
"id": "Ci0W7kn5ec04",
"outputId": "ffacd2bd-6330-4d82-e17d-d77d991106ff"
"outputId": "9aa8b008-a822-46b3-9152-b1cea037543a",
"colab": {
"base_uri": "https://localhost:8080/"
}
},
"outputs": [
{
"data": {
"text/plain": [
"OrderedDict([('weights', tensor([0.5784])), ('bias', tensor([0.3513]))])"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
"output_type": "stream",
"name": "stdout",
"text": [
"The model learned the following values for weights and bias:\n",
"OrderedDict([('weights', tensor([0.6990])), ('bias', tensor([0.3093]))])\n",
"\n",
"And the original values for weights and bias are:\n",
"weights: 0.7, bias: 0.3\n"
]
}
],
"source": [
"model_0.state_dict()"
"# Find our model's learned parameters\n",
"print(\"The model learned the following values for weights and bias:\")\n",
"print(model_0.state_dict())\n",
"print(\"\\nAnd the original values for weights and bias are:\")\n",
"print(f\"weights: {weight}, bias: {bias}\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "NoSUzI_Zec04",
"outputId": "f3ccf6e6-61f3-4a0e-b4cf-74c6916b8f58"
},
"outputs": [
{
"data": {
"text/plain": [
"(0.7, 0.3)"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"cell_type": "markdown",
"source": [
"weight, bias"
]
"Wow! How cool is that?\n",
"\n",
"Our model got very close to calculate the exact original values for `weight` and `bias` (and it would probably get even closer if we trained it for longer).\n",
"\n",
"> **Exercise:** Try changing the `epochs` value above to 200, what happens to the loss curves and the weights and bias parameter values of the model?\n",
"\n",
"It'd likely never guess them *perfectly* (especially when using more complicated datasets) but that's okay, often you can do very cool things with a close approximation.\n",
"\n",
"This is the whole idea of machine learning and deep learning, **there are some ideal values that describe our data** and rather than figuring them out by hand, **we can train a model to figure them out programmatically**."
],
"metadata": {
"id": "BZyBa9rMelBv"
}
},
{
"cell_type": "markdown",
@@ -975,81 +1040,125 @@
"id": "c-VBDFd2ec05"
},
"source": [
"## TK - Making predictions with a trained model\n",
"## TK - 4. Making predictions with a trained PyTorch model (inference)\n",
"\n",
"Notes: \n",
"* When making predictions or using model in inference mode, use `model.eval()`\n",
"* When making predictions, use `with torch.inference_mode():` context manager\n",
"* All predictions and calculations should be made on same device (e.g. on GPU or on CPU only)"
"Once you've trained a model, you'll likely want to make predictions with it.\n",
"\n",
"We've already seen a glimpse of this in the training and testing code above, the steps to do it outside of the training/testing loop are similar.\n",
"\n",
"There are three things to remember when making predictions (also called performing inference) with a PyTorch model:\n",
"\n",
"1. Set the model in evaluation mode (`model.eval()`).\n",
"2. Make the predictions using the inference mode context manager (`with torch.inference_mode(): ...`).\n",
"3. All predictions should be made with objects on the same device (e.g. data and model on GPU only or data and model on CPU only).\n",
"\n",
"The first two items make sure all helpful calculations and settings PyTorch uses behind the scenes during training but aren't necessary for inference are turned off (this results in faster computation). And the third ensures that you won't run into cross-device errors."
]
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 124,
"metadata": {
"id": "xKKxSBVuec05",
"outputId": "6c94a117-3fb6-4577-c7cd-7ddcd346b351"
"outputId": "98263e99-e825-4bbc-9c99-2879a9889032",
"colab": {
"base_uri": "https://localhost:8080/"
}
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"tensor([[0.8141],\n",
" [0.8256],\n",
" [0.8372],\n",
" [0.8488],\n",
" [0.8603],\n",
" [0.8719],\n",
" [0.8835],\n",
" [0.8950],\n",
" [0.9066],\n",
" [0.9182]])"
"tensor([[0.8685],\n",
" [0.8825],\n",
" [0.8965],\n",
" [0.9105],\n",
" [0.9245],\n",
" [0.9384],\n",
" [0.9524],\n",
" [0.9664],\n",
" [0.9804],\n",
" [0.9944]])"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
"execution_count": 124
}
],
"source": [
"# 1. Set the model in evaluation mode\n",
"model_0.eval()\n",
"\n",
"# 2. Setup the inference mode context manager\n",
"with torch.inference_mode():\n",
" y_preds = model_0(X_test)\n",
" # 3. Make sure the calculations are done with the model and data on the same device\n",
" # in our case, we haven't setup device-agnostic code yet so our data and model are\n",
" # on the CPU by default.\n",
" # model_0.to(device)\n",
" # X_test = X_test.to(device)\n",
" y_preds = model_0(X_test)\n",
"y_preds"
]
},
{
"cell_type": "markdown",
"source": [
"Nice! We've made some predictions with our trained model, now how do they look?"
],
"metadata": {
"id": "Cn21JvzmjbBO"
}
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 125,
"metadata": {
"id": "b_kBqpCfec05",
"outputId": "277b4f1a-6536-4935-b4f7-b1a9c927deb2"
"outputId": "a470e2f3-3e0f-4231-c41f-2782bf78a83c",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 428
}
},
"outputs": [
{
"output_type": "display_data",
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAlMAAAGbCAYAAADgEhWsAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjQuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8rg+JYAAAACXBIWXMAAAsTAAALEwEAmpwYAAAtvElEQVR4nO3de3RU9bn/8c9DwiUQbkoAIQgIqCCiQkSx5aZ4UIFFbbUgVkGthh9wjq7jBaqnIN4vWGtrWlGreKtaFaxFilp+INiKJEGhQsCDeAGMEOxvoWAVkzy/PyZNk5BkJsx95v1aa1ay9/7OniezA3zY+7ufMXcXAAAADk+zeBcAAACQzAhTAAAAYSBMAQAAhIEwBQAAEAbCFAAAQBgy4/XCnTp18l69esXr5QEAAEJWXFy8191z6tsWtzDVq1cvFRUVxevlAQAAQmZmnzS0jct8AAAAYSBMAQAAhIEwBQAAEAbCFAAAQBgIUwAAAGEIejefmT0mabykPe4+sJ7tJukBSedJ+lrSNHdfH25hX375pfbs2aPvvvsu3F0hDbRp00a5ublq1oz/HwAAYiuU1giLJD0o6ckGtp8rqV/V4zRJv636eti+/PJL7d69W927d1dWVpYCeQ2oX2VlpXbt2qW9e/eqc+fO8S4HAJBmgv433t1XS/pHI0MmSnrSA9ZK6mBmR4VT1J49e9S9e3e1bt2aIIWgmjVrpi5dumjfvn3xLgUAkIYicU2ku6QdNZZ3Vq07bN99952ysrLCKgrppXnz5iovL493GQCANBSJMFXfqSOvd6DZVWZWZGZFZWVlje+UM1JoAn5fAADxEokwtVNSjxrLuZI+q2+guz/s7nnunpeTU+/H2wAAACSVSISpVyRdagGnS9rn7qUR2C8AAEDCCxqmzOxZSW9LOs7MdprZFWY23cymVw1ZJmm7pG2SHpE0I2rVpqFp06Zp/PjxTXrOqFGjNGvWrChV1LhZs2Zp1KhRcXltAADiIWhrBHe/KMh2lzQzYhUlqWBzdqZOnapFixY1eb8PPPCAAm9x6BYvXqzmzZs3+bXi4eOPP1bv3r1VWFiovLy8eJcDAECThdJnCiEoLf33lc2lS5fqyiuvrLWu7t2J3333XUiBp3379k2u5YgjjmjycwAAwOGhXXSEdO3atfrRoUOHWuu++eYbdejQQc8++6zOPPNMZWVlaeHChfriiy900UUXKTc3V1lZWTrhhBP0+OOP19pv3ct8o0aN0owZM3TjjTeqU6dO6ty5s6677jpVVlbWGlPzMl+vXr102223KT8/X+3atVNubq7uvffeWq/zwQcfaOTIkWrVqpWOO+44LVu2TNnZ2Y2eTauoqNB1112njh07qmPHjrrmmmtUUVFRa8zy5cs1fPhwdezYUUcccYTGjh2rkpKS6u29e/eWJJ166qkys+pLhIWFhfqP//gPderUSe3atdP3v/99vf3228EPBAAgrcx8daYyb8nUzFfjd5GMMBVDP/vZzzRjxgxt3rxZP/jBD/TNN99o8ODBWrp0qTZt2qSrr75a+fn5WrFiRaP7eeaZZ5SZmam//e1vevDBB/XLX/5Szz//fKPPuf/++3XiiSdq/fr1mj17tm644YbqcFJZWanzzz9fmZmZWrt2rRYtWqT58+fr22+/bXSf9913nx555BEtXLhQb7/9tioqKvTMM8/UGnPgwAFdc801WrdunVatWqX27dtrwoQJOnjwoCRp3bp1kgKhq7S0VIsXL5YkffXVV7rkkku0Zs0arVu3TieffLLOO+887d27t9GaAADpZWHxQlV4hRYWL4xfEe4el8eQIUO8IZs3b25wW1PNmOGekRH4GisvvPCCB97agI8++sgl+YIFC4I+d9KkSX7FFVdUL0+dOtXHjRtXvTxy5Eg//fTTaz1nzJgxtZ4zcuRInzlzZvVyz549ffLkybWe07dvX7/11lvd3X358uWekZHhO3furN7+17/+1SX5448/3mCtRx11lN92223VyxUVFd6vXz8fOXJkg8/Zv3+/N2vWzNesWePu/35vCgsLG3yOu3tlZaV37drVn3rqqQbHRPL3BgCQHGYsneEZ8zN8xtLo/kMvqcgbyDQpf2Zq4UKpoiLwNd7qTrCuqKjQ7bffrkGDBunII49Udna2Fi9erE8//bTR/QwaNKjWcrdu3bRnz57Dfs6WLVvUrVs3de/+78b1p556aqMfGrxv3z6VlpZq2LBh1euaNWum006r/bGMH374oaZMmaI+ffqoXbt26tKliyorK4P+jHv27FF+fr6OPfZYtW/fXm3bttWePXuCPg8AkF4KxhWofG65CsYVxK2GlJ+Anp8fCFL5+fGuRGrTpk2t5QULFui+++7TAw88oBNPPFHZ2dm68cYbgwajuhPXzazWnKmmPsfdo9ZBfMKECerevbsWLlyo7t27KzMzUwMGDKi+zNeQqVOnavfu3br//vvVq1cvtWzZUmeddVbQ5wEAEGspH6YKCgKPRPTWW29pwoQJuuSSSyQFQs0HH3xQPYE9Vvr3769du3bps88+U7du3SRJRUVFjQa09u3b66ijjtLatWt15plnSgrUv27dOh11VOBzrr/44guVlJSooKBAo0ePliStX7++1mfotWjRQpIOmbj+1ltv6Ve/+pXGjRsnSdq9e3etuyMBAEgUKX+ZL5Ede+yxWrFihd566y1t2bJFs2bN0kcffRTzOs4++2wdd9xxmjp1qjZs2KC1a9fqv//7v5WZmdnoGaurr75a99xzj1588UVt3bpV11xzTa3A07FjR3Xq1EmPPPKItm3bpjfffFPTp09XZua/M3znzp2VlZWl1157Tbt379a+ffskBd6bp59+Wps3b1ZhYaEmT55cHbwAAEgkhKk4+p//+R8NHTpU5557rkaMGKE2bdro4osvjnkdzZo105IlS/Ttt99q6NChmjp1qm666SaZmVq1atXg86699lpddtll+ulPf6rTTjtNlZWVtepv1qyZnn/+eW3cuFEDBw7UzJkzdeutt6ply5bVYzIzM/WrX/1Kjz76qLp166aJEydKkh577DHt379fQ4YM0eTJk3X55ZerV69eUXsPAACJIxHaHTSFeRO7a0dKXl6eFxUV1butpKRE/fv3j3FFqGnDhg06+eSTVVRUpCFDhsS7nJDwewMAqSHzlkxVeIUyLEPlc8uDPyE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wrt2belZrpkzZ0o6/m0+M9Mzzzyja665Ro0aNdKpp56qF198sdw8ly9frt69e6tBgwY699xzNX/+fJmZlixZUuXPdvDgQY0aNUqNGzdW69at9Ytf/OK4MS+++KLOO+88NWnSRK1atdI111yjnTt3SpK2bt2q73znO5JCAbDsmboFCxbo4osvVosWLXTSSSfp8ssv1/r162v85w8ASKAI79JLtcqDSBGm4mDhwoW6/vrrNX78eK1du1bPPvusZs+erbvvvluS9Pnnn2v48OEaOXKk1q9fr3feeUc33HCDJGnYsGG6/fbbdcYZZ5Se5Ro2bFiV+5o6daqGDh2q1atXa9iwYbrxxhv16aefSpL279+vwYMHq1u3blqxYoUeffRR3XHHHWHnP2HCBP3lL3/R66+/rkWLFmnlypV65513yo05cuSI7r//fq1evVrz5s3T3r17NWLECElS+/bt9frrr0uS1q5dW+5M3YEDB3Tbbbfpgw8+0JIlS9SsWTMNGTKkXNAEACS5WnqXXsTcPSGPPn36eFXWrVtX5baaGjtvrGfcn+Fj542N2muGM2vWLA/90YZcfPHFPnXq1HJj3njjDW/UqJEXFxf7ihUrXJJv3bq10tebPHmyn3XWWcet79ixoz/22GOly5J84sSJpctHjx71rKwsf+GFF9zd/be//a23aNHCDx48WDrmpZdeckm+ePHiSve9b98+r1evnr/44ovl1jVr1sxHjhxZ5Z/B+vXrXZJv377d3d0XL17skrywsLDK57i779+/3+vUqePvvvtuteMqE83fGwAAypJU4FVkmlp/ZioZLnZbsWKFHnroITVu3Lj0cd111+nAgQP6/PPPdc4552jAgAHq0aOHrr76aj399NMqLCw8oX317Nmz9PvMzExlZ2drz549kqQNGzaoR48eysrKKh1zwQUXVPt6H3/8sY4cOaK+ffuWrmvcuLHOPvvscuM+/PBDDR06VB07dlSTJk2Um5srSaVnxap7/euuu05dunRR06ZN1bp1axUXF4d9HgAAyaLWh6lkuNituLhYkydP1qpVq0ofH330kf7xj38oOztbGRkZ+vOf/6w///nP6tmzp37/+9+ra9euWr16dY33Vbdu3XLLZqbi4uJo/SiVOnDggC6//HI1bNhQL7zwgvLz87VgwQJJCvt23eDBg1VYWKjp06dr+fLlWrlypTIzMLine truncated
"text/plain": [
"<Figure size 720x504 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
}
],
"source": [
"plot_predictions(predictions=y_preds)"
]
},
{
"cell_type": "markdown",
"source": [
"Woohoo! Those red dots are looking far closer than they were before!\n",
"\n",
"Let's get onto saving an reloading a model in PyTorch."
],
"metadata": {
"id": "fEHGrjLgji6E"
}
},
{
"cell_type": "markdown",
"metadata": {
"id": "8NRng9aEec05"
},
"source": [
"## TK 5. Saving and loading a model\n",
"## TK 5. Saving and loading a PyTorch model\n",
"\n",
"UPTOHERE: reading the article on saving and loading models in PyTorch\n",
"\n",
"See here for more: https://pytorch.org/tutorials/beginner/saving_loading_models.html\n",
"\n",
@@ -1089,6 +1198,41 @@
"```"
]
},
{
"cell_type": "code",
"source": [
"from pathlib import Path\n",
"\n",
"# Create models directory \n",
"MODEL_PATH = Path(\"models\")\n",
"MODEL_PATH.mkdir(parents=True, exist_ok=True)\n",
"\n",
"# Create model save path \n",
"MODEL_NAME = \"01_pytorch_workflow_model_0.pth\"\n",
"MODEL_SAVE_PATH = MODEL_PATH / MODEL_NAME\n",
"print(f\"Saving model to: {MODEL_SAVE_PATH}\")\n",
"\n",
"# Save the model state dict \n",
"torch.save(model_0.state_dict(), MODEL_SAVE_PATH)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "qsQhY2S2jv90",
"outputId": "bdc358d2-5310-4667-ee10-1d1c6419dd91"
},
"execution_count": 131,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Saving model to: models/01_pytorch_workflow_model_0.pth\n"
]
}
]
},
{
"cell_type": "code",
"execution_count": null,
@@ -1826,14 +1970,7 @@
"colab": {
"name": "01_pytorch_workflow.ipynb",
"provenance": [],
"collapsed_sections": [
"DmilLp3Vec07",
"X0ycBrxIec07",
"jwTeP_vkec08",
"mBR1qvqhec09",
"K8jCHl1gec0-"
],
"toc_visible": true,
"collapsed_sections": [],
"include_colab_link": true
}
},