2021-10-20 11:49:02 +10:00
{
2022-01-29 16:26:06 +10:00
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/github/mrdbourke/pytorch-deep-learning/blob/main/02_pytorch_classification.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "r8C1WSzsHC7x"
},
"source": [
"# 02. Neural Network Classification with PyTorch\n",
"\n",
"## What is classification?\n",
"\n",
"TK - image for classification\n",
"\n",
"A [classification problem](https://en.wikipedia.org/wiki/Statistical_classification) involves predicting whether something is one thing or another.\n",
"\n",
"For example, you might want to:\n",
"\n",
"| Problem type | What is it? | Example |\n",
"| ----- | ----- | ----- |\n",
"| **Binary classification** | Target can be one of two options, e.g. yes or no | Predict whether or not someone has heart disease based on their health parameters. |\n",
"| **Multi-class classification** | Target can be one of more than two options | Decide whether a photo of is of food, a person or a dog. |\n",
"| **Multi-label classification** | Target can be assigned more than one option | Predict what categories should be assigned to a Wikipedia article (e.g. mathematics, science & philosohpy). |\n",
"\n",
"Classification, along with regression (predicting a number, covered in [notebook 01](https://www.learnpytorch.io/01_pytorch_workflow/)) is one of the most common types of machine learning problems.\n",
"\n",
"In this notebook, we're going to work through a couple of different classification problems with PyTorch. \n",
"\n",
"In other words, taking a set of inputs and predicting what class those set of inputs belong to.\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"source": [
"## TK - What we're going to cover\n",
"\n",
"TK - include PyTorch workflow\n",
"\n",
"TODO\n",
"* Simple classification (reiterate PyTorch workflow)\n",
" * Binary classification\n",
" * Multi-class classification\n",
"* Writing device agnostic code\n",
" * Data on GPU\n",
" * Model on GPU\n",
"* More advanced classification (e.g. black and white images or FashionMNIST or FoodMNIST or something)\n",
"* Visualizing a PyTorch model (all of the different connections)\n",
"\n",
"\n"
2021-10-20 11:49:02 +10:00
],
2022-01-29 16:26:06 +10:00
"metadata": {
"id": "9wTlTaDKH7Oj"
}
},
{
"cell_type": "markdown",
"source": [
"## Where can can you get help?\n",
"\n",
"All of the materials for this course [live on GitHub](https://github.com/mrdbourke/pytorch-deep-learning).\n",
"\n",
"And if you run into trouble, you can ask a question on the [Discussions page](https://github.com/mrdbourke/pytorch-deep-learning/discussions) there too.\n",
"\n",
"There's also the [PyTorch developer forums](https://discuss.pytorch.org/), a very helpful place for all things PyTorch. \n",
"\n"
],
"metadata": {
"id": "uxdUc9OfHtgU"
}
},
{
"cell_type": "markdown",
"source": [
"## TK - Architecture of a classification neural network\n",
"\n",
"Before we get into writing code, let's look at the general architecture of a classification neural network.\n",
"\n",
"| **Hyperparameter** | **Binary Classification** | **Multiclass classification** |\n",
"| --- | --- | --- |\n",
2022-01-31 09:09:12 +10:00
"| **Input layer shape** (`in_features`) | Same as number of features (e.g. 5 for age, sex, height, weight, smoking status in heart disease prediction) | Same as binary classification |\n",
"| **Hidden layer(s)** | Problem specific, minimum = 1, maximum = unlimited | Same as binary classification |\n",
"| **Neurons per hidden layer** | Problem specific, generally 10 to 512 | Same as binary classification |\n",
"| **Output layer shape** (`out_features`) | 1 (one class or the other) | 1 per class (e.g. 3 for food, person or dog photo) |\n",
"| **Hidden layer activation** | Usually [ReLU](https://pytorch.org/docs/stable/generated/torch.nn.ReLU.html#torch.nn.ReLU) (rectified linear unit) but [can be many others](https://en.wikipedia.org/wiki/Activation_function#Table_of_activation_functions) | Same as binary classification |\n",
"| **Output activation** | [Sigmoid](https://en.wikipedia.org/wiki/Sigmoid_function) ([`torch.sigmoid`](https://pytorch.org/docs/stable/generated/torch.sigmoid.html) in PyTorch)| [Softmax](https://en.wikipedia.org/wiki/Softmax_function) ([`torch.softmax`](https://pytorch.org/docs/stable/generated/torch.nn.Softmax.html) in PyTorch) |\n",
"| **Loss function** | [Binary crossentropy](https://en.wikipedia.org/wiki/Cross_entropy#Cross-entropy_loss_function_and_logistic_regression) ([`torch.nn.BCELoss`](https://pytorch.org/docs/stable/generated/torch.nn.BCELoss.html) in PyTorch) | Cross entropy ([`torch.nn.CrossEntropyLoss`](https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html) in PyTorch) |\n",
"| **Optimizer** | [SGD](https://pytorch.org/docs/stable/generated/torch.optim.SGD.html) (stochastic gradient descent), [Adam](https://pytorch.org/docs/stable/generated/torch.optim.Adam.html) (see [`torch.optim`](https://pytorch.org/docs/stable/optim.html) for more options) | Same as binary classification |\n",
2022-01-29 16:26:06 +10:00
"\n",
"Of course, this ingredient list of classification neural network components will vary depending on the problem you're working on.\n",
"\n",
"But it's more than enough to get started.\n",
"\n",
"We're going to gets hands-on with this setup throughout this notebook.\n",
"\n",
"TK - image: architecture of a classification network"
],
"metadata": {
"id": "MSLHJiQxH4jU"
}
},
{
"cell_type": "markdown",
"metadata": {
"id": "VwvxFEjKHC71"
},
"source": [
"## TK - 1. Make classification data and get it ready\n",
"\n",
"Let's begin by making some data.\n",
"\n",
2022-01-31 09:09:12 +10:00
"We'll use the [`make_circles()`](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_circles.html) method from Scikit-Learn to generate two circles with different coloured dots. "
2021-10-20 11:49:02 +10:00
]
2022-01-29 16:26:06 +10:00
},
{
"cell_type": "code",
2022-01-31 09:09:12 +10:00
"execution_count": 20,
2022-01-29 16:26:06 +10:00
"metadata": {
"id": "RGeZvHsyHC72"
},
"outputs": [],
"source": [
2022-01-31 09:09:12 +10:00
"from sklearn.datasets import make_circles\n",
2022-01-29 16:26:06 +10:00
"\n",
"# Make 1000 samples \n",
"n_samples = 1000\n",
"\n",
"# Create circles\n",
2022-01-31 09:09:12 +10:00
"X, y = make_circles(n_samples,\n",
" noise=0.03, # a little bit of noise to the dots\n",
" random_state=42) # keep random state so we get the same values"
2021-10-20 11:49:02 +10:00
]
2022-01-29 16:26:06 +10:00
},
{
"cell_type": "markdown",
"source": [
"Alright, now let's view the first 5 `X` and `y` values."
],
"metadata": {
"id": "1FwwzJnQV2jv"
}
},
{
"cell_type": "code",
"source": [
"print(f\"First 5 X features:\\n{X[:5]}\")\n",
"print(f\"\\nFirst 5 y labels:\\n{y[:5]}\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "oAb8vcIhWEO8",
2022-01-31 09:09:12 +10:00
"outputId": "5a9ab5be-888c-4696-8653-b17acaec7d3e"
2022-01-29 16:26:06 +10:00
},
2022-01-31 09:09:12 +10:00
"execution_count": 21,
2022-01-29 16:26:06 +10:00
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"First 5 X features:\n",
2022-01-31 09:09:12 +10:00
"[[ 0.75424625 0.23148074]\n",
" [-0.75615888 0.15325888]\n",
" [-0.81539193 0.17328203]\n",
" [-0.39373073 0.69288277]\n",
" [ 0.44220765 -0.89672343]]\n",
2022-01-29 16:26:06 +10:00
"\n",
"First 5 y labels:\n",
"[1 1 1 1 0]\n"
]
}
2021-10-20 11:49:02 +10:00
]
},
{
2022-01-29 16:26:06 +10:00
"cell_type": "markdown",
"source": [
"Looks like there's two `X` values per one `y` value. \n",
"\n",
"Let's keep following the data explorer's motto of *visualize, visualize, visualize* and put them into a pandas DataFrame."
],
"metadata": {
"id": "ATakj2bVWBou"
}
},
{
"cell_type": "code",
2022-01-31 09:09:12 +10:00
"execution_count": 22,
2022-01-29 16:26:06 +10:00
"metadata": {
"id": "XAAqx_8sHC73",
2022-01-31 09:09:12 +10:00
"outputId": "8a0fe01a-d8f9-4dad-8f65-f4c6ad58d188",
2022-01-29 16:26:06 +10:00
"colab": {
"base_uri": "https://localhost:8080/",
"height": 363
}
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/html": [
"\n",
2022-01-31 09:09:12 +10:00
" <div id=\"df-96670f70-4a5f-4e3a-90e1-442a22fa055c\">\n",
2022-01-29 16:26:06 +10:00
" <div class=\"colab-df-container\">\n",
" <div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>X1</th>\n",
" <th>X2</th>\n",
" <th>label</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
2022-01-31 09:09:12 +10:00
" <td>0.754246</td>\n",
" <td>0.231481</td>\n",
2022-01-29 16:26:06 +10:00
" <td>1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
2022-01-31 09:09:12 +10:00
" <td>-0.756159</td>\n",
" <td>0.153259</td>\n",
2022-01-29 16:26:06 +10:00
" <td>1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
2022-01-31 09:09:12 +10:00
" <td>-0.815392</td>\n",
" <td>0.173282</td>\n",
2022-01-29 16:26:06 +10:00
" <td>1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
2022-01-31 09:09:12 +10:00
" <td>-0.393731</td>\n",
" <td>0.692883</td>\n",
2022-01-29 16:26:06 +10:00
" <td>1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
2022-01-31 09:09:12 +10:00
" <td>0.442208</td>\n",
" <td>-0.896723</td>\n",
2022-01-29 16:26:06 +10:00
" <td>0</td>\n",
" </tr>\n",
" <tr>\n",
" <th>5</th>\n",
2022-01-31 09:09:12 +10:00
" <td>-0.479646</td>\n",
" <td>0.676435</td>\n",
2022-01-29 16:26:06 +10:00
" <td>1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>6</th>\n",
2022-01-31 09:09:12 +10:00
" <td>-0.013648</td>\n",
" <td>0.803349</td>\n",
2022-01-29 16:26:06 +10:00
" <td>1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>7</th>\n",
2022-01-31 09:09:12 +10:00
" <td>0.771513</td>\n",
" <td>0.147760</td>\n",
2022-01-29 16:26:06 +10:00
" <td>1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>8</th>\n",
2022-01-31 09:09:12 +10:00
" <td>-0.169322</td>\n",
" <td>-0.793456</td>\n",
2022-01-29 16:26:06 +10:00
" <td>1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>9</th>\n",
2022-01-31 09:09:12 +10:00
" <td>-0.121486</td>\n",
" <td>1.021509</td>\n",
2022-01-29 16:26:06 +10:00
" <td>0</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>\n",
2022-01-31 09:09:12 +10:00
" <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-96670f70-4a5f-4e3a-90e1-442a22fa055c')\"\n",
2022-01-29 16:26:06 +10:00
" title=\"Convert this dataframe to an interactive table.\"\n",
" style=\"display:none;\">\n",
" \n",
" <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n",
" width=\"24px\">\n",
" <path d=\"M0 0h24v24H0V0z\" fill=\"none\"/>\n",
" <path d=\"M18.56 5.44l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94zm-11 1L8.5 8.5l.94-2.06 2.06-.94-2.06-.94L8.5 2.5l-.94 2.06-2.06.94zm10 10l.94 2.06.94-2.06 2.06-.94-2.06-.94-.94-2.06-.94 2.06-2.06.94z\"/><path d=\"M17.41 7.96l-1.37-1.37c-.4-.4-.92-.59-1.43-.59-.52 0-1.04.2-1.43.59L10.3 9.45l-7.72 7.72c-.78.78-.78 2.05 0 2.83L4 21.41c.39.39.9.59 1.41.59.51 0 1.02-.2 1.41-.59l7.78-7.78 2.81-2.81c.8-.78.8-2.07 0-2.86zM5.41 20L4 18.59l7.72-7.72 1.47 1.35L5.41 20z\"/>\n",
" </svg>\n",
" </button>\n",
" \n",
" <style>\n",
" .colab-df-container {\n",
" display:flex;\n",
" flex-wrap:wrap;\n",
" gap: 12px;\n",
" }\n",
"\n",
" .colab-df-convert {\n",
" background-color: #E8F0FE;\n",
" border: none;\n",
" border-radius: 50%;\n",
" cursor: pointer;\n",
" display: none;\n",
" fill: #1967D2;\n",
" height: 32px;\n",
" padding: 0 0 0 0;\n",
" width: 32px;\n",
" }\n",
"\n",
" .colab-df-convert:hover {\n",
" background-color: #E2EBFA;\n",
" box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
" fill: #174EA6;\n",
" }\n",
"\n",
" [theme=dark] .colab-df-convert {\n",
" background-color: #3B4455;\n",
" fill: #D2E3FC;\n",
" }\n",
"\n",
" [theme=dark] .colab-df-convert:hover {\n",
" background-color: #434B5C;\n",
" box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
" filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
" fill: #FFFFFF;\n",
" }\n",
" </style>\n",
"\n",
" <script>\n",
" const buttonEl =\n",
2022-01-31 09:09:12 +10:00
" document.querySelector('#df-96670f70-4a5f-4e3a-90e1-442a22fa055c button.colab-df-convert');\n",
2022-01-29 16:26:06 +10:00
" buttonEl.style.display =\n",
" google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
"\n",
" async function convertToInteractive(key) {\n",
2022-01-31 09:09:12 +10:00
" const element = document.querySelector('#df-96670f70-4a5f-4e3a-90e1-442a22fa055c');\n",
2022-01-29 16:26:06 +10:00
" const dataTable =\n",
" await google.colab.kernel.invokeFunction('convertToInteractive',\n",
" [key], {});\n",
" if (!dataTable) return;\n",
"\n",
" const docLinkHtml = 'Like what you see? Visit the ' +\n",
" '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
" + ' to learn more about interactive tables.';\n",
" element.innerHTML = '';\n",
" dataTable['output_type'] = 'display_data';\n",
" await google.colab.output.renderOutput(dataTable, element);\n",
" const docLink = document.createElement('div');\n",
" docLink.innerHTML = docLinkHtml;\n",
" element.appendChild(docLink);\n",
" }\n",
" </script>\n",
" </div>\n",
" </div>\n",
" "
],
"text/plain": [
" X1 X2 label\n",
2022-01-31 09:09:12 +10:00
"0 0.754246 0.231481 1\n",
"1 -0.756159 0.153259 1\n",
"2 -0.815392 0.173282 1\n",
"3 -0.393731 0.692883 1\n",
"4 0.442208 -0.896723 0\n",
"5 -0.479646 0.676435 1\n",
"6 -0.013648 0.803349 1\n",
"7 0.771513 0.147760 1\n",
"8 -0.169322 -0.793456 1\n",
"9 -0.121486 1.021509 0"
2022-01-29 16:26:06 +10:00
]
},
"metadata": {},
2022-01-31 09:09:12 +10:00
"execution_count": 22
2022-01-29 16:26:06 +10:00
}
],
"source": [
2022-01-31 09:09:12 +10:00
"# Make DataFrame of circle data\n",
2022-01-29 16:26:06 +10:00
"import pandas as pd\n",
2022-01-31 09:09:12 +10:00
"circles = pd.DataFrame({\"X1\": X[:, 0],\n",
2022-01-29 16:26:06 +10:00
" \"X2\": X[:, 1],\n",
" \"label\": y\n",
"})\n",
2022-01-31 09:09:12 +10:00
"circles.head(10)"
2021-10-20 11:49:02 +10:00
]
2022-01-29 16:26:06 +10:00
},
{
"cell_type": "markdown",
"source": [
"It looks like each pair of `X` features (`X1` and `X2`) has a label (`y`) value of either 0 or 1.\n",
"\n",
"This tells us that our problem is **binary classification** since there's only two options (0 or 1).\n",
"\n",
"How many values of each class is there?"
],
"metadata": {
"id": "FK2T7GpYW2BE"
}
},
{
"cell_type": "code",
2022-01-31 09:09:12 +10:00
"execution_count": 23,
2022-01-29 16:26:06 +10:00
"metadata": {
"id": "cV8sVR9tHC74",
2022-01-31 09:09:12 +10:00
"outputId": "0bcfe3c6-f927-4177-979f-1a5e3787b420",
2022-01-29 16:26:06 +10:00
"colab": {
"base_uri": "https://localhost:8080/"
}
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"1 500\n",
"0 500\n",
"Name: label, dtype: int64"
]
},
"metadata": {},
2022-01-31 09:09:12 +10:00
"execution_count": 23
2022-01-29 16:26:06 +10:00
}
],
"source": [
"# Check different labels\n",
2022-01-31 09:09:12 +10:00
"circles.label.value_counts()"
2021-10-27 11:33:46 +10:00
]
2022-01-29 16:26:06 +10:00
},
{
"cell_type": "markdown",
"source": [
"500 each, nice and balanced.\n",
"\n",
"Let's plot them."
],
"metadata": {
"id": "ytQ5rm9eXa65"
}
},
{
"cell_type": "code",
2022-01-31 09:09:12 +10:00
"execution_count": 24,
2022-01-29 16:26:06 +10:00
"metadata": {
"id": "ANkSmESCHC75",
2022-01-31 09:09:12 +10:00
"outputId": "720e0c2a-df38-49d7-9bba-60e77aff0f63",
2022-01-29 16:26:06 +10:00
"colab": {
"base_uri": "https://localhost:8080/",
"height": 265
}
},
"outputs": [
{
"output_type": "display_data",
"data": {
2022-01-31 09:09:12 +10:00
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAXwAAAD4CAYAAADvsV2wAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4yLjIsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+WH4yJAAAgAElEQVR4nOydd3QU1duAn5nZnt4JBAi9d5DemyCCFRQ7CnbF9tkVe0fFLvafilKlSe/SpPcWSggJJaSXrTPz/bEhsuxuspsEpcxzDkczc9sms+/c+1ZBVVU0NDQ0NC59xP96ARoaGhoa/w6awNfQ0NC4TNAEvoaGhsZlgibwNTQ0NC4TNIGvoaGhcZmg+68X4I/Y2Fg1OTn5v16GhoaGxkXFpk2bTquqGufr3gUr8JOTk9m4ceN/vQwNDQ2NiwpBEFL93dNUOhoaGhqXCZrA19DQ0LhM0AS+hoaGxmWCJvA1NDQ0LhM0ga+hUcU4cvPJ252Cq9jqt43scJC5dgvZW3aj5bPS+Le4YL10NDQuROzZuZxYtAZRryNxYDd0IZbSe7LDwYb7x3Hk19mIej2qrND06dE0f/EBBE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jTsxJ8Z5f54AOLXib47PW+Gd8qEEVZZRFYWi1HR0YSGYYqODnkOj6tEEvoYHzvwC/wKgAoZKY2wUjoJC5IJydMuigGQ00vChW6hzyzDArR7ZO/57r2AiyWKm1WtjMcVFc9XuuWTMXU7erhTCG9elxtW9EfXeromiJFH37us59O00r+RmjR8LzKTUYtzDpM9ZjlxkLf0dSRYzbd59koYP3uq3X
2022-01-29 16:26:06 +10:00
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
}
}
],
"source": [
"# Visualize with a plot\n",
"import matplotlib.pyplot as plt\n",
"plt.scatter(x=X[:, 0], \n",
" y=X[:, 1], \n",
" c=y, \n",
" cmap=plt.cm.RdYlBu);"
2021-10-27 11:33:46 +10:00
]
2022-01-29 16:26:06 +10:00
},
{
"cell_type": "markdown",
"metadata": {
"id": "h0e1oR27HC76"
},
"source": [
"Alrighty, looks like we've got a problem to solve.\n",
"\n",
"Let's find out how we could build a PyTorch neural network to classify dots into red (0) or blue (1).\n",
"\n",
"> **Note:** This dataset is often what's considered a **toy problem** (a problem that's used to try and test things out on) in machine learning. \n",
"> \n",
"> But it represents the major key of classification, you have some kind of data represented as numerical values and you'd like to build a model that's able to classify it, in our case, separate it into red or blue dots."
2021-10-27 11:33:46 +10:00
]
2022-01-29 16:26:06 +10:00
},
{
"cell_type": "markdown",
"metadata": {
"id": "Ny6_J7F4HC76"
},
"source": [
"### TK - 1.1 Input and output shapes\n",
"\n",
"One of the most common errors in deep learning is shape errors.\n",
"\n",
"Mismatching the shapes of tensors and tensor operations with result in errors in your models.\n",
"\n",
"We're going to see plenty of these throughout the course.\n",
"\n",
"And there's no surefire way to making sure they won't happen, they will.\n",
"\n",
"What you can do instead is continaully familiarize yourself with the shape of the data you're working with.\n",
"\n",
"I like referring to it as input and output shapes.\n",
"\n",
"Ask yourself:\n",
"\n",
"\"What shapes are my inputs and what shapes are my outputs?\"\n",
"\n",
"Let's find out."
2021-10-28 11:31:25 +10:00
]
2022-01-29 16:26:06 +10:00
},
{
"cell_type": "code",
2022-01-31 09:09:12 +10:00
"execution_count": 30,
2022-01-29 16:26:06 +10:00
"metadata": {
"id": "r0h--vKdHC77",
2022-01-31 09:09:12 +10:00
"outputId": "3351666d-c0a0-48e3-b1d7-7aaef0b41a63",
2022-01-29 16:26:06 +10:00
"colab": {
"base_uri": "https://localhost:8080/"
}
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"((1000, 2), (1000,))"
]
},
"metadata": {},
2022-01-31 09:09:12 +10:00
"execution_count": 30
2022-01-29 16:26:06 +10:00
}
],
"source": [
"# Check the shapes of our features and labels\n",
"X.shape, y.shape"
2021-10-29 12:34:32 +10:00
]
2022-01-29 16:26:06 +10:00
},
{
"cell_type": "markdown",
"source": [
"Looks like we've got a match on the first dimension of each.\n",
"\n",
"There's 1000 `X` and 1000 `y`. \n",
"\n",
"But what's the second dimension on `X`?\n",
"\n",
"It often helps to view the values and shapes of a single sample (features and labels).\n",
"\n",
"Doing so will help you understand what input and output shapes you'd be expecting from your model."
],
"metadata": {
"id": "PW7zolShbfDg"
}
},
{
"cell_type": "code",
2022-01-31 09:09:12 +10:00
"execution_count": 31,
2022-01-29 16:26:06 +10:00
"metadata": {
"id": "k-L5zobVHC78",
2022-01-31 09:09:12 +10:00
"outputId": "6065d030-4a0a-4c4a-88b4-2a899347737f",
2022-01-29 16:26:06 +10:00
"colab": {
"base_uri": "https://localhost:8080/"
}
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
2022-01-31 09:09:12 +10:00
"Values for one sample of X: [0.75424625 0.23148074] and the same for y: 1\n",
2022-01-29 16:26:06 +10:00
"Shapes for one sample of X: (2,) and the same for y: ()\n"
]
}
],
"source": [
"# View the first example of features and labels\n",
"X_sample = X[0]\n",
"y_sample = y[0]\n",
"print(f\"Values for one sample of X: {X_sample} and the same for y: {y_sample}\")\n",
"print(f\"Shapes for one sample of X: {X_sample.shape} and the same for y: {y_sample.shape}\")"
2021-10-27 11:33:46 +10:00
]
2022-01-29 16:26:06 +10:00
},
{
"cell_type": "markdown",
"source": [
"This tells us the second dimension for `X` means it has two features (vector) where as `y` has a single feature (scalar).\n",
"\n",
"We have two inputs for one output."
],
"metadata": {
"id": "Vn692XaRaifl"
}
},
{
"cell_type": "markdown",
"source": [
"### TK - 1.2 Turn data into tensors and create train and test splits\n",
"\n",
"We've investigated the input and output shapes of our data, now let's prepare it for being used with PyTorch and for modelling.\n",
"\n",
"Specifically, we'll need to:\n",
"1. Turn our data into tensors (right now our data is in NumPy arrays and PyTorch prefers to work with PyTorch tensors).\n",
"2. Split our data into training and test sets (we'll train a model on the training set to learn the patterns between `X` and `y` and then evaluate those learned patterns on the test dataset)."
],
"metadata": {
"id": "eLyDPN6ZR_ho"
}
},
{
"cell_type": "code",
2022-01-31 09:09:12 +10:00
"execution_count": 32,
2022-01-29 16:26:06 +10:00
"metadata": {
"id": "Z2gcR31aHC78",
2022-01-31 09:09:12 +10:00
"outputId": "3600215b-26b6-4946-e5d5-e42f49b73394",
2022-01-29 16:26:06 +10:00
"colab": {
"base_uri": "https://localhost:8080/"
}
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
2022-01-31 09:09:12 +10:00
"(tensor([[ 0.7542, 0.2315],\n",
" [-0.7562, 0.1533],\n",
" [-0.8154, 0.1733],\n",
" [-0.3937, 0.6929],\n",
" [ 0.4422, -0.8967]]), tensor([1., 1., 1., 1., 0.]))"
2022-01-29 16:26:06 +10:00
]
},
"metadata": {},
2022-01-31 09:09:12 +10:00
"execution_count": 32
2022-01-29 16:26:06 +10:00
}
],
"source": [
"# Turn data into tensors\n",
"# Otherwise this causes issues with computations later on\n",
"import torch\n",
"X = torch.from_numpy(X).type(torch.float)\n",
"y = torch.from_numpy(y).type(torch.float)\n",
"\n",
"# View the first five samples\n",
"X[:5], y[:5]"
2021-10-27 11:33:46 +10:00
]
2022-01-29 16:26:06 +10:00
},
{
"cell_type": "markdown",
"source": [
"Now our data is in tensor format, let's split it into training and test sets.\n",
"\n",
"To do so, let's use the helpful function [`train_test_split()`](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html) from Scikit-Learn.\n",
"\n",
"We'll use `test_size=0.2` (80% training, 20% testing) and because the split happens randomly across the data, let's use `random_state=42` so the split is reproducible."
],
"metadata": {
"id": "r9XNJv8lfmRG"
}
},
{
"cell_type": "code",
2022-01-31 09:09:12 +10:00
"execution_count": 33,
2022-01-29 16:26:06 +10:00
"metadata": {
"id": "DW6PU82BHC79",
2022-01-31 09:09:12 +10:00
"outputId": "f6354ea6-0187-46fc-ead3-0b8d1d417be9",
2022-01-29 16:26:06 +10:00
"colab": {
"base_uri": "https://localhost:8080/"
}
},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"(800, 200, 800, 200)"
]
},
"metadata": {},
2022-01-31 09:09:12 +10:00
"execution_count": 33
2022-01-29 16:26:06 +10:00
}
],
"source": [
"# Split data into train and test sets\n",
"from sklearn.model_selection import train_test_split\n",
"\n",
"X_train, X_test, y_train, y_test = train_test_split(X, \n",
" y, \n",
" test_size=0.2, # 20% test, 80% train\n",
" random_state=42) # make the random split reproducible\n",
"\n",
"len(X_train), len(X_test), len(y_train), len(y_test)"
2021-10-27 11:33:46 +10:00
]
2022-01-29 16:26:06 +10:00
},
{
"cell_type": "markdown",
"source": [
"Nice! Looks like we've now got 800 training samples and 200 testing samples."
],
"metadata": {
"id": "t-wYDWy9gSRc"
}
},
{
"cell_type": "markdown",
"metadata": {
"id": "iCyQ93VTHC79"
},
"source": [
"## TK - 2. Building a model\n",
"\n",
2022-01-31 09:09:12 +10:00
"We've got some data ready, now it's time to build a model.\n",
"\n",
"We'll break it down into a few parts.\n",
"\n",
"1. Setting up device agnostic code (so our model can run on CPU or GPU if it's available).\n",
"2. Constructing a model by subclassing `nn.Module`.\n",
"3. Defining a loss function and optimizer.\n",
"4. Creating a training loop (this'll be in the next section).\n",
"\n",
"The good news is we've been through all of the above steps before in notebook 01.\n",
"\n",
"Except now we'll be adjusting them so they work with a classification dataset.\n",
2022-01-29 16:26:06 +10:00
"\n",
2022-01-31 09:09:12 +10:00
"Let's start by importing PyTorch and `torch.nn` as well as setting up device agnostic code."
2021-10-27 11:33:46 +10:00
]
2022-01-29 16:26:06 +10:00
},
{
"cell_type": "code",
"source": [
2022-01-31 09:09:12 +10:00
"# Standard PyTorch imports\n",
2022-01-29 16:26:06 +10:00
"import torch\n",
"from torch import nn\n",
"\n",
"# Make device agnostic code\n",
"device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
"device"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
2022-01-31 09:09:12 +10:00
"height": 35
2022-01-29 16:26:06 +10:00
},
"id": "2itMTezPRnVR",
2022-01-31 09:09:12 +10:00
"outputId": "beb00bfb-3244-48ff-93ba-6535f95ec4d4"
2022-01-29 16:26:06 +10:00
},
2022-01-31 09:09:12 +10:00
"execution_count": 34,
2022-01-29 16:26:06 +10:00
"outputs": [
{
2022-01-31 09:09:12 +10:00
"output_type": "execute_result",
"data": {
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
},
"text/plain": [
"'cuda'"
]
},
"metadata": {},
"execution_count": 34
2022-01-29 16:26:06 +10:00
}
2021-10-28 11:31:25 +10:00
]
2022-01-29 16:26:06 +10:00
},
2022-01-31 09:09:12 +10:00
{
"cell_type": "markdown",
"source": [
"Excellent, now `device` is setup, we can use it for any data or models we create and PyTorch will handle it on the CPU (default) or GPU if it's available.\n",
"\n",
"How about we create a model?\n",
"\n",
"We'll want a model capable of handling our `X` data as inputs and producing something in the shape of our `y` data as ouputs.\n",
"\n",
"In other words, given `X` (features) we want our model to predict `y` (label).\n",
"\n",
"This setup where you have features and labels is referred to as **supervised learning**. Because your data is telling your model what the outputs should be given a certain input.\n",
"\n",
"To create such a model it'll need to handle the input and output shapes of `X` and `y`.\n",
"\n",
"Remember how I said input and output shapes are important? Here we'll see why.\n",
"\n",
"Let's create a model class that:\n",
"1. Subclasses `nn.Module` (almost all PyTorch models are subclasses of `nn.Module`).\n",
"2. Creates 2 `nn.Linear` layers in the constructor capable of handling the input and output shapes of `X` and `y`.\n",
"3. Defines a `forward()` method containing the forward pass computation of the model.\n",
"4. Instantiates the model class and sends it to the target `device`. "
],
"metadata": {
"id": "p1Fil1v04nXr"
}
},
2022-01-29 16:26:06 +10:00
{
"cell_type": "code",
2022-01-31 09:09:12 +10:00
"execution_count": 35,
2022-01-29 16:26:06 +10:00
"metadata": {
"id": "C_EsAE3VHC7-",
2022-01-31 09:09:12 +10:00
"outputId": "ae3374b5-fb4a-403e-8985-a1570d47a090",
"colab": {
"base_uri": "https://localhost:8080/"
}
2022-01-29 16:26:06 +10:00
},
"outputs": [
{
2022-01-31 09:09:12 +10:00
"output_type": "execute_result",
2022-01-29 16:26:06 +10:00
"data": {
"text/plain": [
2022-01-31 09:09:12 +10:00
"CircleModelV0(\n",
" (layer_1): Linear(in_features=2, out_features=5, bias=True)\n",
" (layer_2): Linear(in_features=5, out_features=1, bias=True)\n",
2022-01-29 16:26:06 +10:00
")"
]
},
"metadata": {},
2022-01-31 09:09:12 +10:00
"execution_count": 35
2022-01-29 16:26:06 +10:00
}
],
"source": [
2022-01-31 09:09:12 +10:00
"# 1. Construct a model class that subclasses nn.Module\n",
"class CircleModelV0(nn.Module):\n",
2022-01-29 16:26:06 +10:00
" def __init__(self):\n",
" super().__init__()\n",
2022-01-31 09:09:12 +10:00
" # 2. Create 2 nn.Linear layers capable of handling X and y input and output shapes\n",
" self.layer_1 = nn.Linear(in_features=2, out_features=5) # takes in 2 features (X), produces 5 features\n",
" self.layer_2 = nn.Linear(in_features=5, out_features=1) # takes in 5 features, produces 1 feature (y)\n",
2022-01-29 16:26:06 +10:00
" \n",
2022-01-31 09:09:12 +10:00
" # 3. Define a forward method containing the forward pass computation\n",
2022-01-29 16:26:06 +10:00
" def forward(self, x):\n",
2022-01-31 09:09:12 +10:00
" # Return the output of layer_2, a single feature, the same shape as y\n",
" return self.layer_2(self.layer_1(x)) # computation goes through layer_1 first then the output of layer_1 goes through layer_2\n",
2022-01-29 16:26:06 +10:00
"\n",
2022-01-31 09:09:12 +10:00
"# 4. Create an instance of the model and send it to target device\n",
"model_0 = CircleModelV0().to(device)\n",
2022-01-29 16:26:06 +10:00
"model_0"
2021-10-28 11:31:25 +10:00
]
2022-01-29 16:26:06 +10:00
},
2022-01-31 09:09:12 +10:00
{
"cell_type": "markdown",
"source": [
"What's going on here?\n",
"\n",
"We've seen a few of these steps before.\n",
"\n",
"The only major change is what's happening between `self.layer_1` and `self.layer_2`.\n",
"\n",
"`self.layer_1` takes 2 input features `in_features=2` and produces 5 output features `out_features=5`.\n",
"\n",
"This is known as having 5 **hidden units** or **neurons**.\n",
"\n",
"This layer turns the input data from having 2 features to 5 features.\n",
"\n",
"Why do this?\n",
"\n",
"This allows the model to learn patterns from 5 numbers rather than just 2 numbers, *potentially* leading to better outputs.\n",
"\n",
"I say potentially because sometimes it doesn't work.\n",
"\n",
"The number of hidden units you can use in neural network layers is a **hyperparameter** (a value you can set yourself) and there's no set in stone value you have to use.\n",
"\n",
"Generally more is better but there's also such a thing as too much. The amount you choose will depend on your model type and dataset you're working with. \n",
"\n",
"Since our dataset is small and simple, we'll keep it small.\n",
"\n",
"The only rule with hidden units is that the next layer, in our case, `self.layer_2` has to take the same `in_features` as the previous layer `out_features`.\n",
"\n",
"That's why `self.layer_2` has `in_features=5`, it takes the `out_features=5` from `self.layer_1` and performs a linear computation on them, turning them into `out_features=1` (the same shape as `y`).\n",
"\n",
"TK image - TensorFlow playground classification network with 5 hidden units\n",
"\n",
"You can also do the same as above using [`nn.Sequential`](https://pytorch.org/docs/stable/generated/torch.nn.Sequential.html).\n",
"\n",
"`nn.Sequential` performs a forward pass computation of the input data through the layers in the order they appear."
],
"metadata": {
"id": "TtdkMniZ7KyK"
}
},
2022-01-29 16:26:06 +10:00
{
"cell_type": "code",
2022-01-31 09:09:12 +10:00
"execution_count": 36,
2022-01-29 16:26:06 +10:00
"metadata": {
"id": "H7I8GyLjHC7_",
2022-01-31 09:09:12 +10:00
"outputId": "173b3b3e-d401-428e-fdd4-aa65f85c89b2",
"colab": {
"base_uri": "https://localhost:8080/"
}
2022-01-29 16:26:06 +10:00
},
"outputs": [
{
2022-01-31 09:09:12 +10:00
"output_type": "execute_result",
2022-01-29 16:26:06 +10:00
"data": {
"text/plain": [
"Sequential(\n",
2022-01-31 09:09:12 +10:00
" (0): Linear(in_features=2, out_features=5, bias=True)\n",
" (1): Linear(in_features=5, out_features=1, bias=True)\n",
2022-01-29 16:26:06 +10:00
")"
]
},
"metadata": {},
2022-01-31 09:09:12 +10:00
"execution_count": 36
2022-01-29 16:26:06 +10:00
}
],
"source": [
2022-01-31 09:09:12 +10:00
"# Replicate CircleModelV0 with nn.Sequential\n",
2022-01-29 16:26:06 +10:00
"model_0 = nn.Sequential(\n",
2022-01-31 09:09:12 +10:00
" nn.Linear(in_features=2, out_features=5),\n",
" nn.Linear(in_features=5, out_features=1)\n",
").to(device)\n",
2022-01-29 16:26:06 +10:00
"\n",
"model_0"
2021-10-28 11:31:25 +10:00
]
2022-01-29 16:26:06 +10:00
},
2022-01-31 09:09:12 +10:00
{
"cell_type": "markdown",
"source": [
"Woah, that looks much simpler than subclassing `nn.Module`, why not just always use `nn.Sequential`?\n",
"\n",
"`nn.Sequential` is fantastic for straight-forward computations, however, as the namespace says, it *always* runs in sequential order.\n",
"\n",
"So if you'd something else to happen (rather than just straight-forward sequential computation) you'll want to define your own custom `nn.Module` subclass.\n",
"\n",
"Now we've got a model, let's see what happens when we pass some data through it."
],
"metadata": {
"id": "MiRHq9mxFIf-"
}
},
{
"cell_type": "code",
"source": [
"# Make predictions with the model\n",
"untrained_preds = model_0(X_test.to(device))\n",
"print(f\"Length of predictions: {len(untrained_preds)}, Shape: {untrained_preds.shape}\")\n",
"print(f\"Length of test samples: {len(y_test)}, Shape: {y_test.shape}\")\n",
"print(f\"\\nFirst 10 predictions:\\n{untrained_preds[:10]}\")\n",
"print(f\"\\nFirst 10 test labels:\\n{y_test[:10]}\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "Tt339-_CC8sz",
"outputId": "96b2b425-8b91-47a3-836e-a21115fb8511"
},
"execution_count": 49,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Length of predictions: 200, Shape: torch.Size([200, 1])\n",
"Length of test samples: 200, Shape: torch.Size([200])\n",
"\n",
"First 10 predictions:\n",
"tensor([[ 0.0414],\n",
" [ 0.1100],\n",
" [-0.2622],\n",
" [ 0.1280],\n",
" [-0.4590],\n",
" [-0.4156],\n",
" [-0.0667],\n",
" [-0.1902],\n",
" [-0.2534],\n",
" [ 0.1124]], device='cuda:0', grad_fn=<SliceBackward0>)\n",
"\n",
"First 10 test labels:\n",
"tensor([1., 0., 1., 0., 1., 1., 0., 0., 1., 0.])\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"Hmm, it seems there's the same amount of predictions as there is test labels but the predictions don't look like they're in the same form or shape as the test labels.\n",
"\n",
"We've got a couple steps we can do to fix this."
],
"metadata": {
"id": "q7v8TVnqGMZh"
}
},
2022-01-29 16:26:06 +10:00
{
"cell_type": "markdown",
"metadata": {
"id": "8aoQn39pHC7_"
},
"source": [
2022-01-31 09:09:12 +10:00
"### TK - 2.1 Setup loss and optimizer\n",
"\n",
"We've setup a loss and optimizer before in notebook 01.\n",
"\n",
"But different problem types require different loss functions. \n",
"\n",
"For example, for a regression problem (predicting a number) you might used mean absolute error (MAE) loss.\n",
"\n",
"And for a binary classification problem (like ours), you'll often use [binary cross entropy](https://towardsdatascience.com/understanding-binary-cross-entropy-log-loss-a-visual-explanation-a3ac6025181a) as the loss function.\n",
"\n",
"However, the same optimizer function can often be used across different problem spaces.\n",
"\n",
"For example, the stochastic gradient descent optimizer (SGD, [`torch.optim.SGD()`](https://pytorch.org/docs/stable/generated/torch.optim.SGD.html)) can be used for a range of problems, so can too the Adam optimizer ([`torch.optim.Adam()`](https://pytorch.org/docs/stable/generated/torch.optim.Adam.html)). \n",
"\n",
"TK - table for different losses and optimization functions (e.g. loss/optimizer function + problem type + code)\n",
"\n",
"Since we're working with a binary classification problem, let's use a binary cross entropy loss function.\n",
"\n",
"> **Note:** Recall a **loss function** is what measures how *wrong* your model predictions are, the higher the loss, the worse your model.\n",
">\n",
"> Also, PyTorch documentation often refers to loss functions as \"loss criterion\" or \"criterion\", these are all different ways of describing the same thing.\n",
"\n",
"PyTorch has two binary cross entropy implementations:\n",
"1. [`torch.nn.BCELoss()`](https://pytorch.org/docs/stable/generated/torch.nn.BCELoss.html) - Creations a loss function that measures the binary cross entropy between the target (label) and input (features).\n",
"2. [`torch.nn.BCEWithLogitsLoss()`](https://pytorch.org/docs/stable/generated/torch.nn.BCEWithLogitsLoss.html) - This is the same as above except it has a sigmoid layer ([`nn.Sigmoid`](https://pytorch.org/docs/stable/generated/torch.nn.Sigmoid.html)) built-in (we'll see what this means soon).\n",
"\n",
"Which one should you use? \n",
"\n",
"The [documentation for `torch.nn.BCEWithLogitsLoss()`](https://pytorch.org/docs/stable/generated/torch.nn.BCEWithLogitsLoss.html) states that it's more numerically stable than using `torch.nn.BCELoss()` after a `nn.Sigmoid` layer. \n",
"\n",
"So generally, implementation 2 is a better option. However for advanced usage, you may want to separate the combination of `nn.Sigmoid` and `torch.nn.BCELoss()` but that is beyond the scope of this notebook.\n",
"\n",
"UPTOHERE: implementing loss function + optimizer\n",
"\n",
"* BCEWithLogitsLoss = more stable, https://pytorch.org/docs/stable/generated/torch.nn.BCEWithLogitsLoss.html"
2021-10-28 11:31:25 +10:00
]
2022-01-29 16:26:06 +10:00
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "DjpQsdOZHC7_"
},
"outputs": [],
"source": [
"# TK - Explain both of these - https://discuss.pytorch.org/t/bceloss-vs-bcewithlogitsloss/33586/4\n",
"# loss_fn = nn.BCELoss() # BCELoss = no sigmoid built-in\n",
"loss_fn = nn.BCEWithLogitsLoss() # BCEWithLogitsLoss = Sigmoid built-in\n",
"optimizer = torch.optim.SGD(params=model_0.parameters(), lr=0.1)"
2021-10-28 11:31:25 +10:00
]
2022-01-29 16:26:06 +10:00
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "RcaZQR0mHC7_"
},
"outputs": [],
"source": [
"# Calculate accuracy (a classification metric)\n",
"def accuracy_fn(y_true, y_pred):\n",
" correct = torch.eq(y_true, y_pred).sum().item()\n",
" acc = (correct / len(y_pred)) * 100 \n",
" return acc"
2021-10-28 11:31:25 +10:00
]
},
{
2022-01-29 16:26:06 +10:00
"cell_type": "markdown",
"metadata": {
"id": "4UpJKZ8PHC8A"
},
"source": [
"## TK 3. Train model"
2021-10-28 11:31:25 +10:00
]
2022-01-29 16:26:06 +10:00
},
2022-01-31 09:09:12 +10:00
{
"cell_type": "code",
"source": [
"X_train.shape"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "zq49QrxiHEwV",
"outputId": "0e7143ba-5141-47bb-9e6b-6ac90b6581a9"
},
"execution_count": 47,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"torch.Size([800, 2])"
]
},
"metadata": {},
"execution_count": 47
}
]
},
2022-01-29 16:26:06 +10:00
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "DFABVGo2HC8A",
"outputId": "b771bafd-69c6-4cbc-f4d6-762c3826262d"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Epoch: 0 | Loss: 0.69343, Accuracy: 50.00% | Test loss: 0.67247, Test acc: 50.00%\n",
"Epoch: 10 | Loss: 0.53407, Accuracy: 78.38% | Test loss: 0.53940, Test acc: 76.50%\n",
"Epoch: 20 | Loss: 0.45563, Accuracy: 78.62% | Test loss: 0.47073, Test acc: 75.00%\n",
"Epoch: 30 | Loss: 0.40720, Accuracy: 80.50% | Test loss: 0.42620, Test acc: 76.50%\n",
"Epoch: 40 | Loss: 0.37457, Accuracy: 81.00% | Test loss: 0.39463, Test acc: 78.00%\n",
"Epoch: 50 | Loss: 0.35120, Accuracy: 82.38% | Test loss: 0.37088, Test acc: 79.50%\n",
"Epoch: 60 | Loss: 0.33356, Accuracy: 83.50% | Test loss: 0.35218, Test acc: 80.50%\n",
"Epoch: 70 | Loss: 0.31970, Accuracy: 83.75% | Test loss: 0.33694, Test acc: 82.00%\n",
"Epoch: 80 | Loss: 0.30848, Accuracy: 84.38% | Test loss: 0.32422, Test acc: 83.50%\n",
"Epoch: 90 | Loss: 0.29920, Accuracy: 85.00% | Test loss: 0.31344, Test acc: 83.50%\n"
]
}
],
"source": [
"# TK - clean this up for different data types (could be far clearer what's going on)\n",
"torch.manual_seed(42)\n",
"epochs = 100\n",
"for epoch in range(epochs):\n",
2022-01-31 09:09:12 +10:00
" \n",
2022-01-29 16:26:06 +10:00
" # 1. Forward pass\n",
" y_pred = model_0(X_train).squeeze() # this won't work unless X & y are tensors\n",
" \n",
" # 2. Calculate loss/accuracy\n",
" # loss = loss_fn(torch.sigmoid(y_pred), y) # Using nn.BCELoss you need torch.sigmoid()\n",
" loss = loss_fn(y_pred, y_train) # using nn.BCEWithLogitsLoss you *don't* need torch.sigmoid()\n",
" acc = accuracy_fn(y_true=y_train, \n",
" y_pred=torch.round(torch.sigmoid(y_pred)))\n",
"\n",
" # 3. Optimizer zero grad\n",
" optimizer.zero_grad()\n",
"\n",
" # 4. Loss backwards\n",
" loss.backward()\n",
"\n",
" # 5. Optimizer step\n",
" optimizer.step()\n",
"\n",
" # Testing\n",
" model_0.eval()\n",
" with torch.inference_mode():\n",
" test_pred = model_0(X_test).squeeze()\n",
" test_loss = loss_fn(test_pred, y_test)\n",
" test_acc = accuracy_fn(y_true=y_test,\n",
" y_pred=torch.round(torch.sigmoid(test_pred)))\n",
"\n",
" # Print out what's happening\n",
" if epoch % 10 == 0:\n",
" print(f\"Epoch: {epoch} | Loss: {loss:.5f}, Accuracy: {acc:.2f}% | Test loss: {test_loss:.5f}, Test acc: {test_acc:.2f}%\")"
2021-10-28 11:31:25 +10:00
]
2022-01-29 16:26:06 +10:00
},
{
"cell_type": "markdown",
"metadata": {
"id": "WCeyddo-HC8A"
},
"source": [
"## TK - 4. Make predictions and evaluate the model"
2021-10-28 11:31:25 +10:00
]
2022-01-29 16:26:06 +10:00
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "CLHFFuNwHC8B"
},
"outputs": [],
"source": [
"import numpy as np\n",
"def plot_decision_boundary(model, X, y):\n",
" # Source - https://madewithml.com/courses/foundations/neural-networks/ \n",
" # (with modifications)\n",
" x_min, x_max = X[:, 0].min() - 0.1, X[:, 0].max() + 0.1\n",
" y_min, y_max = X[:, 1].min() - 0.1, X[:, 1].max() + 0.1\n",
" xx, yy = np.meshgrid(np.linspace(x_min, x_max, 101), \n",
" np.linspace(y_min, y_max, 101))\n",
"\n",
" X_test = torch.from_numpy(np.column_stack((xx.ravel(), yy.ravel()))).float()\n",
" model.eval()\n",
" with torch.inference_mode():\n",
" y_preds = model(X_test)\n",
"\n",
" # Test for multi-class\n",
" if len(torch.unique(y)) > 2:\n",
" y_pred = torch.softmax(y_preds, dim=1).argmax(dim=1) # mutli-class\n",
" else: \n",
" y_pred = torch.round(torch.sigmoid(y_preds)) # binary\n",
" \n",
" # Reshape preds and plot\n",
" y_pred = y_pred.reshape(xx.shape).detach().numpy()\n",
" plt.contourf(xx, yy, y_pred, cmap=plt.cm.RdYlBu, alpha=0.7)\n",
" plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.RdYlBu)\n",
" plt.xlim(xx.min(), xx.max())\n",
" plt.ylim(yy.min(), yy.max())"
2021-10-28 11:31:25 +10:00
]
2022-01-29 16:26:06 +10:00
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "bEbDUTKjHC8B",
"outputId": "d28730df-cbab-4292-9256-8908f4f54a33"
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAtEAAAF1CA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ha7R+HDHlq5HodgtLMXjr/ee4w+7zvCHXWfWLaBBZaIV90HDQ+3EF6IER2Yz7hg2l53DL56l/0e3kCuzH6YkPhfhxl+8i6Zr1J5upv6BtqytPW9tGZpdw0xnZ7iFrlF7umXNNS2MzDBxdYhUJIG3ppT6c21rOnsoFFvNUsD+ra/17vRSFNtMRVs18bOtjF8ZzMRJ3a7T+bEzeRMGm4kQgvYPnyQ8Ps9s/xRCCCo7a/FU+Ri71E/gzhhGKo3H76P58cM55W+R6SDBkVk0m0ZFew2OEteWrleh2A6y47FAX9Qg6xXQoET0gUNKSXhinuDoHLrDRmXHxgOjpmt0fvQ08YUo0UAIu9dJSW0ZQoiC9dIAmBLTNJi4NoQ0JY0PdxCZWmDs8gDB0dn8NdGGSTqWxO4uXAoycX2I8Uv3mngSoRjzA9Mc/eSDePy+Db1GheJ+WR6wV7NKUuxf6h9oo/pEI5GpILrDhremdNvqgoUQ+Boqcmqvmx49RNOjh/I+RkpJ/49usjA0g5k2EZrG6MV+Ws4fxn+sYTuWrVBsCSsFdGul977Op0T0AUKaJj0/vE54Yn4xMArGLvXT8uQR/EfqizqHmTaY658mEYzhrvRS3urHVebBVZZ99WZz2zGS6dXXkzaZujGCx++zMtcFSjysJ5ZM3Ryh9en89XVGMs3Yxf7sc0irIXHo7W6Ofeqh7OeWkmgghJGwsjA2l331F65QbICVAXu9WQ7F/sHmtFPWXFxJmpk2mB8MkIok8Ph9lNSXb2sz3mzPZEZAA5k+laF37lLaVFkw8WIaJqlIApvLvuUe2ArFevF7J
"text/plain": [
"<Figure size 864x432 with 2 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"# Plot decision boundaries for training and test sets\n",
"plt.figure(figsize=(12, 6))\n",
"plt.subplot(1, 2, 1)\n",
"plt.title(\"Train\")\n",
"plot_decision_boundary(model_0, X_train, y_train)\n",
"plt.subplot(1, 2, 2)\n",
"plt.title(\"Test\")\n",
"plot_decision_boundary(model_0, X_test, y_test)"
2021-10-28 11:31:25 +10:00
]
2022-01-29 16:26:06 +10:00
},
{
"cell_type": "markdown",
"metadata": {
"id": "6VivsLTmHC8B"
},
"source": [
"## TK - 5. Improving a model\n",
"\n",
"TODO\n",
"* Add layers \n",
"* Add units\n",
"* Train for longer...\n"
2021-10-28 11:31:25 +10:00
]
2022-01-29 16:26:06 +10:00
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "j-GRUN9QHC8B",
"outputId": "33ae0784-3ba4-4a0e-aed9-ad82f32367ac"
},
"outputs": [
{
"data": {
"text/plain": [
"MoonModelV1(\n",
" (layer_1): Linear(in_features=2, out_features=10, bias=True)\n",
" (layer_2): Linear(in_features=10, out_features=10, bias=True)\n",
" (layer_3): Linear(in_features=10, out_features=1, bias=True)\n",
")"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
2022-01-31 09:09:12 +10:00
"class CircleModelV1(nn.Module):\n",
2022-01-29 16:26:06 +10:00
" def __init__(self):\n",
" super().__init__()\n",
" self.layer_1 = nn.Linear(in_features=2, out_features=10)\n",
" self.layer_2 = nn.Linear(in_features=10, out_features=10)\n",
" self.layer_3 = nn.Linear(in_features=10, out_features=1)\n",
" \n",
" def forward(self, x): # always make sure forward is spelt correctly!\n",
" # Creating a model like this is the same as below, though below\n",
" # generally benefits from speedups where possible.\n",
" # z = self.layer_1(x)\n",
" # z = self.layer_2(z)\n",
" # z = self.layer_3(z)\n",
" # return z\n",
" return self.layer_3(self.layer_2(self.layer_1(x)))\n",
"\n",
2022-01-31 09:09:12 +10:00
"model_1 = CircleModelV1()\n",
2022-01-29 16:26:06 +10:00
"model_1"
2021-10-28 11:31:25 +10:00
]
2022-01-29 16:26:06 +10:00
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "AXYwYPpSHC8B"
},
"outputs": [],
"source": [
"# loss_fn = nn.BCELoss() # Requires sigmoid on input\n",
"loss_fn = nn.BCEWithLogitsLoss() # Does not require sigmoid on input\n",
"optimizer = torch.optim.SGD(model_1.parameters(), lr=0.1)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "aX0QGBozHC8C",
"outputId": "c2bf4fb0-3ca8-4571-f7e4-6559403a68b8"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Epoch: 0 | Loss: 0.71899, Accuracy: 32.30%\n",
"Epoch: 100 | Loss: 0.26747, Accuracy: 86.60%\n",
"Epoch: 200 | Loss: 0.24532, Accuracy: 88.60%\n",
"Epoch: 300 | Loss: 0.24452, Accuracy: 88.70%\n",
"Epoch: 400 | Loss: 0.24449, Accuracy: 88.60%\n",
"Epoch: 500 | Loss: 0.24449, Accuracy: 88.60%\n",
"Epoch: 600 | Loss: 0.24449, Accuracy: 88.60%\n",
"Epoch: 700 | Loss: 0.24449, Accuracy: 88.60%\n",
"Epoch: 800 | Loss: 0.24449, Accuracy: 88.60%\n",
"Epoch: 900 | Loss: 0.24449, Accuracy: 88.60%\n"
]
}
],
"source": [
"epochs = 1000 # Train for longer\n",
"for epoch in range(epochs):\n",
" # 1. Forward pass\n",
" y_pred = model_1(X).squeeze()\n",
"\n",
" # 2. Calculate loss/accuracy\n",
" loss = loss_fn(y_pred, y)\n",
" acc = accuracy_fn(y_true=y, \n",
" y_pred=torch.round(torch.sigmoid(y_pred)))\n",
"\n",
" # 3. Optimizer zero grad\n",
" optimizer.zero_grad()\n",
"\n",
" # 4. Loss backwards\n",
" loss.backward()\n",
"\n",
" # 5. Optimizer step\n",
" optimizer.step()\n",
"\n",
" # Print outputs\n",
" if epoch % 100 == 0:\n",
" print(f\"Epoch: {epoch} | Loss: {loss:.5f}, Accuracy: {acc:.2f}%\")\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "GUjJqRw7HC8C",
"outputId": "6212ff05-51a1-43e8-e366-5a8a05d53adc"
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAtEAAAF1CAYAAAAurLZiAAAA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xQITIeBDNplHZWYfD59rR8SoUew0log8YUkpi0wtEJkLoDhtVXVufGDVdo+djp0iFEyTmoti9Tnz15QghSuZLA2BKTNNg+too0pQ0P95FfDbM5KVhIhPB4jnRhkkumcHuLp0KMn19lKmL94p40tEkC8MBjnzqUTw1/i29R4VCobhfGh/poPZ4M/HZCLrDhreu7IHlBQsh8DdVFuRet5zrpuVcd9FzpJQM/fAm4dF5zJyJ0DQmLgzR9vQhao42PYhhKxR7AiWiDxDSNOn/3nVi0wuLE6Ng8uIQbc8cpuZw44auYeYMQkMB0pEk7iovFe01uMo9uMrzo702tx0jk1t7PDmT2RvjeGr8VuS6RIqH9cKS2ZvjtD9XPL/OyOSYvDCUfw1pFSSOvtPH0c88lv/aUpKYi2KkrSiMzWVf+40rFArFfWBz2ilv3VhKmpkzWBiZIxtP46nx42useKDFeMH+mWUBDSzXqYy+e5eylqqSgRfTMMnG09hc9h33wFYodgPqU36ACNyeJDa1sJyPLE0JSEZ/0kd5SxV2jxNpSkJDs8z3TSOlpKqnnqruejRdIxmK0/utS8v2c5pdx+a0cfQzj+V1uzIyOTLxjVncSWky+pO+tQX0IulYquS+2EwYoQlkkTrH+GwEKeXyTSgVTnD3O1fJJbOgWb6tdSdbaX68S1WNKxSKh0piPkbfa5eRpsQ0TDRNw1Xh4fCrZ4sK08R8lPEPBojPRNAdOrXHm2k43XZfTaYCtyaKFyNKS
"text/plain": [
"<Figure size 864x432 with 2 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"# Plot decision boundaries for training and test sets\n",
"plt.figure(figsize=(12, 6))\n",
"plt.subplot(1, 2, 1)\n",
"plt.title(\"Train\")\n",
"plot_decision_boundary(model_1, X_train, y_train)\n",
"plt.subplot(1, 2, 2)\n",
"plt.title(\"Test\")\n",
"plot_decision_boundary(model_1, X_test, y_test)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "8UqtuZYwHC8C"
},
"source": [
"Pretty good... but still not where we'd like it.\n",
"\n",
"Our model is drawing straight lines... but we'd like the lines to be curved, what can we do? \n",
"\n",
"How about we check our model on linear data, what does that do?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "xLoEBQ6fHC8C",
"outputId": "9cc631db-ff57-4b06-aba0-68bcd951c061"
},
"outputs": [
{
"data": {
"text/plain": [
"(tensor([[0.0000],\n",
" [0.0200],\n",
" [0.0400],\n",
" [0.0600],\n",
" [0.0800]]),\n",
" tensor([[0.3000],\n",
" [0.3140],\n",
" [0.3280],\n",
" [0.3420],\n",
" [0.3560]]))"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Create some data (same as notebook 01)\n",
"weight = 0.7\n",
"bias = 0.3\n",
"start = 0\n",
"end = 1\n",
"step = 0.02\n",
"\n",
2022-01-31 09:09:12 +10:00
"# TK - change these variable names so they don't interfere with the original circles data\n",
2022-01-29 16:26:06 +10:00
"\n",
"# Create data\n",
"X_regression = torch.arange(start, end, step).unsqueeze(dim=1)\n",
"y_regression = weight * X_regression + bias\n",
"\n",
"X_regression[:5], y_regression[:5]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "UIoO2k8yHC8D",
"outputId": "f88a24f3-aa2a-4ca6-a1b8-5e6fbb108b5e"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"40 40 10 10\n"
]
}
],
"source": [
"# Create train/test split\n",
"train_split = int(0.8 * len(X_regression)) # 80% of data used for training set\n",
"X_train_regression, y_train_regression = X_regression[:train_split], \\\n",
" y_regression[:train_split]\n",
"X_test_regression, y_test_regression = X_regression[train_split:], \\\n",
" y_regression[train_split:]\n",
"\n",
"print(len(X_train_regression), \n",
" len(y_train_regression), \n",
" len(X_test_regression), \n",
" len(y_test_regression))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "xjPmGhidHC8D"
},
"outputs": [],
"source": [
"# TK - put this in helper function file... \n",
"def plot_predictions(train_data=X_train, \n",
" train_labels=y_train, \n",
" test_data=X_test, \n",
" test_labels=y_test, \n",
" predictions=None):\n",
" \"\"\"\n",
" Plots training data, test data and compares predictions.\n",
" \"\"\"\n",
" plt.figure(figsize=(10, 7))\n",
"\n",
" # Plot training data in blue\n",
" plt.scatter(train_data, train_labels, c=\"b\", s=4, label=\"Training data\")\n",
" \n",
" # Plot test data in green\n",
" plt.scatter(test_data, test_labels, c=\"g\", s=4, label=\"Testing data\")\n",
"\n",
" if predictions is not None:\n",
" # Plot the predictions in red (predictions were made on the test data)\n",
" plt.scatter(test_data, predictions, c=\"r\", s=4, label=\"Predictions\")\n",
"\n",
" # Show the legend\n",
" plt.legend(prop={\"size\": 14});"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "pcg5OvncHC8D",
"outputId": "c66fd854-4a80-4ebf-9e84-ba1d92f2e520"
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAlMAAAGbCAYAAADgEhWsAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjQuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8rg+JYAAAACXBIWXMAAAsTAAALEwEAmpwYAAAm+ElEQVR4nO3dfXRUhb3u8eeXBARBIJQAEhRQUUEECxHLWVVA60EFFuXaLkCroFbDBc6SdXzB6hGL2q622lq95tRgD6W+VG0VWwoc0OMVQSuSgEINQU9EhCAlCb0LBVshye/+MTlpEpLMhD3v8/2sNSvZLzPzIxv0yZ49z5i7CwAAACcmK9EDAAAApDLCFAAAQACEKQAAgAAIUwAAAAEQpgAAAALISdQT9+nTxwcPHpyopwcAAIjYli1batw9r7VtCQtTgwcPVmlpaaKeHgAAIGJm9klb23iZDwAAIADCFAAAQACEKQAAgAAIUwAAAAEQpgAAAAII+24+M1smaYqkKncf0cp2k/SopKskfSFpjrtvDTrYZ599pqqqKh07dizoQyEDdOvWTQMHDlRWFr8fAADiK5JqhOWSHpf0VBvbr5Q0tOF2kaRfNHw9YZ999pkOHDig/Px8de3aVaG8BrSuvr5e+/btU01Njfr27ZvocQAAGSbsr/HuvkHSX9vZZZqkpzxkk6ReZnZqkKGqqqqUn5+vk08+mSCFsLKystSvXz8dOnQo0aMAADJQNF4TyZe0t8lyZcO6E3bs2DF17do10FDILJ06dVJtbW2ixwAAZKBohKnWTh15qzua3WJmpWZWWl1d3f6DckYKHcDfFwBAokQjTFVKOq3J8kBJn7a2o7svdfcCdy/Iy2v1420AAABSSjTC1EpJ11vI1yQdcvf9UXhcAACApBc2TJnZc5LelnSOmVWa2U1mNtfM5jbsskbSLkkVkp6UNC9m02agOXPmaMqUKR26z4QJE7RgwYIYTdS+BQsWaMKECQl5bgAAEiFsNYK7zwqz3SXNj9pEKSrcNTuzZ8/W8uXLO/y4jz76qEI/4sitWLFCnTp16vBzJcLu3bs1ZMgQlZSUqKCgINHjAADQYZH0TCEC+/f/45XNVatW6eabb262ruW7E48dOxZR4OnZs2eHZ+ndu3eH7wMAAE4MddFR0r9//8Zbr169mq37+9//rl69eum5557TpZdeqq5du6q4uFgHDx7UrFmzNHDgQHXt2lXnnXeefvWrXzV73JYv802YMEHz5s3T3XffrT59+qhv3766/fbbVV9f32yfpi/zDR48WA8++KAKCwvVo0cPDRw4UA899FCz5/nwww81fvx4denSReecc47WrFmj7t27t3s2ra6uTrfffrtyc3OVm5urhQsXqq6urtk+a9eu1cUXX6zc3Fz17t1bkyZNUnl5eeP2IUOGSJIuvPBCmVnjS4QlJSX653/+Z/Xp00c9evTQ17/+db399tvhDwQAIKPMXz1fOffnaP7qxL1IRpiKo+9973uaN2+eduzYoW9+85v6+9//rtGjR2vVqlUqKyvTrbfeqsLCQr322mvtPs6zzz6rnJwc/elPf9Ljjz+un//853rhhRfavc8jjzyi888/X1u3btWiRYt05513NoaT+vp6TZ8+XTk5Odq0aZOWL1+uJUuW6Msvv2z3MX/605/qySefVHFxsd5++23V1dXp2WefbbbPkSNHtHDhQm3evFnr169Xz549NXXqVB09elSStHnzZkmh0LV//36tWLFCkvT555/ruuuu08aNG7V582ZdcMEFuuqqq1RTU9PuTACAzFK8pVh1XqfiLcWJG8LdE3IbM2aMt2XHjh1tbuuoefPcs7NDX+Pld7/7nYd+tCEff/yxS/KHH3447H1nzJjhN910U+Py7NmzffLkyY3L48eP96997WvN7vONb3yj2X3Gjx/v8+fPb1weNGiQz5w5s9l9zjrrLH/ggQfc3X3t2rWenZ3tlZWVjdvfeustl+S/+tWv2pz11FNP9QcffLBxua6uzocOHerjx49v8z6HDx/2rKws37hxo7v/42dTUlLS5n3c3evr671///7+9NNPt7lPNP/eAABSw7xV8zx7SbbPWxXb/9FLKvU2Mk3an5kqLpbq6kJfE63lBdZ1dXX6wQ9+oJEjR+orX/mKunfvrhUrVmjPnj3tPs7IkSObLQ8YMEBVVVUnfJ+dO3dqwIABys//R3H9hRde2O6HBh86dEj79+/XuHHjGtdlZWXpoouafyzjRx99pGuuuUZnnnmmevTooX79+qm+vj7sn7GqqkqFhYU6++yz1bNnT51yyimqqqoKez8AQGYpmlyk2sW1KppclLAZ0v4C9MLCUJAqLEz0JFK3bt2aLT/88MP66U9/qkcffVTnn3++unfvrrvvvjtsMGp54bqZNbtmqqP3cfeYNYhPnTpV+fn5Ki4uVn5+vnJycjR8+PDGl/naMnv2bB04cECPPPKIBg8erJNOOkmXXXZZ2PsBABBvaR+miopCt2T05ptvaurUqbruuuskhULNhx9+2HgBe7wMGzZM+/bt06effqoBAwZIkkpLS9sNaD179tSpp56qTZs26dJLL5UUmn/z5s069dTQ51wfPHhQ5eXlKioq0sSJEyVJW7dubfYZep07d5ak4y5cf/PNN/XYY49p8uTJkqQDBw40e3ckAADJIu1f5ktmZ599tl577TW9+eab2rlzpxYsWKCPP/447nNcfvnlOuecczR79mxt27ZNmzZt0r/+678qJyen3TNWt956q37yk5/oxRdf1AcffKCFCxc2Czy5ubnq06ePnnzySVVUVOiNN97Q3LlzlZPzjwzft29fde3aVevWrdOBAwd06NAhSaGfzTPPPKMdO3aopKRE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7R//37t379fM2bMaPO57r//fk2bNk3btm3TjBkzdOONN+qTTz6RJB0+fFhTpkzRueeeqy1btugnP
"text/plain": [
"<Figure size 720x504 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"plot_predictions(train_data=X_train_regression,\n",
" train_labels=y_train_regression,\n",
" test_data=X_test_regression,\n",
" test_labels=y_test_regression\n",
");"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "rc13zblAHC8D",
"outputId": "e6da5465-1716-4d08-d6dd-73e645b9c1a6"
},
"outputs": [
{
"data": {
"text/plain": [
"Sequential(\n",
" (0): Linear(in_features=1, out_features=10, bias=True)\n",
" (1): Linear(in_features=10, out_features=10, bias=True)\n",
" (2): Linear(in_features=10, out_features=1, bias=True)\n",
")"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Same architecture as model_1 (but using nn.Sequential)\n",
"model_2 = nn.Sequential(\n",
" nn.Linear(in_features=1, out_features=10),\n",
" nn.Linear(in_features=10, out_features=10),\n",
" nn.Linear(in_features=10, out_features=1)\n",
")\n",
"\n",
"model_2"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "f06fraapHC8E"
},
"outputs": [],
"source": [
"# Loss and optimizer\n",
"loss_fn = nn.L1Loss()\n",
"optimizer = torch.optim.SGD(model_2.parameters(), lr=0.1)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "YTitEWgSHC8E",
"outputId": "652aaa52-5574-4b31-9ca8-6fa941dd1ae8"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Epoch: 0 | Train loss: 0.57614, Test loss: 0.47134\n",
"Epoch: 100 | Train loss: 0.09489, Test loss: 0.24817\n",
"Epoch: 200 | Train loss: 0.05440, Test loss: 0.14747\n",
"Epoch: 300 | Train loss: 0.06319, Test loss: 0.16150\n",
"Epoch: 400 | Train loss: 0.05353, Test loss: 0.13854\n",
"Epoch: 500 | Train loss: 0.06441, Test loss: 0.14258\n",
"Epoch: 600 | Train loss: 0.04558, Test loss: 0.11145\n",
"Epoch: 700 | Train loss: 0.05696, Test loss: 0.12189\n",
"Epoch: 800 | Train loss: 0.05632, Test loss: 0.11305\n",
"Epoch: 900 | Train loss: 0.05212, Test loss: 0.11977\n"
]
}
],
"source": [
"# Train the model\n",
"torch.manual_seed(42)\n",
"epochs = 1000\n",
"for epoch in range(epochs):\n",
" # 1. Forward pass\n",
" y_pred = model_2(X_train_regression)\n",
" \n",
" # 2. Calculate loss\n",
" loss = loss_fn(y_pred, y_train_regression)\n",
"\n",
" # 3. Optimizer zero grad\n",
" optimizer.zero_grad()\n",
"\n",
" # 4. Loss backwards\n",
" loss.backward()\n",
"\n",
" # 5. Optimizer step\n",
" optimizer.step()\n",
"\n",
" # Testing\n",
" model_2.eval()\n",
" with torch.inference_mode():\n",
" test_pred = model_2(X_test_regression)\n",
" test_loss = loss_fn(test_pred, y_test_regression)\n",
"\n",
" # Print out what's happening\n",
" if epoch % 100 == 0: \n",
" print(f\"Epoch: {epoch} | Train loss: {loss:.5f}, Test loss: {test_loss:.5f}\")\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "AvltMCW_HC8E",
"outputId": "e0db77b1-8fce-4f1a-cdba-3660f3628cbd"
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAlMAAAGbCAYAAADgEhWsAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjQuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8rg+JYAAAACXBIWXMAAAsTAAALEwEAmpwYAAAtu0lEQVR4nO3de3RU9bn/8c9DwiUSbkoAIQhUUKGIChG1rYCKBxVY1NNaEI9CtRp+wDm6jhc42IJ4qW3FWntMa9Qq1ntVsBYpXviBYCuSBAUNAYsgAkYI9reQSxWTPL8/Jk2TkGQm7JnMZOb9WmvWZO/9nT1PsgN82Pu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WNBrROnTrp+OOP15o1a3T++edLCtW/du1aHX986HOuP//8c5WUlCgvL0/nnXeeJGndunW1PkOvTZs2knTExPW33npLv/71rzV27FhJ0u7du2vdHQkAQKJI+st8ieykk07S8uXL9dZbb2nTpk2aOXOmtm3b1ux1XHjhhTr55JM1ZcoUrV+/XmvWrNF///d/Kz09vdEzVtdff71+8Ytf6IUXXtDmzZt1ww031Ao8Xbp0UdeuXfXwww9ry5YtevPNNzVt2jSlp/8rw3fr1k0ZGRl69dVXtXv3bu3bt09S6Gfz5JNPauPGjSooKNCkSZOqgxcAAImEMBVHP/7xjzV8+HBdfPHFGjFihNq3b68rrrii2eto1aqVFi9erK+++krDhw/XlClTdOutt8rM1K5duwZfd+ONN+qHP/yhfvSjH+mss85SZWVlrfpbtWql5557Ths2bNDgwYM1Y8YM3XHHHWrbtm31mPT0dP3617/WI488op49e2rChAmSpEcffVQHDhzQsGHDNGnSJF199dXq27dvzH4GAIDEkQjtDprCvIndtaMlJyfHCwsL691WUlKigQMHNnNFqGn9+vU6/fTTVVhYqGHDhsW7nIjwewMAySH99nRVeIXSLE3lc8vDv6AZmFmRu9f7UR2cmYIkafHixXrttde0bds2rVixQlOnTtVpp52moUOHxrs0AECKyR2WqzRLU+6wBLh7LAJJPwEdkdm/f79mzZqlHTt2qEuXLho1apTuu+++mN3lBwBAQ/LG5sW11UFTEaYgSbrqqqt01VVXxbsMAABaHC7zAQAABECYAgAACIAwBQAAmkVLa3kQKcIUAABoFvlF+arwCuUXJcAH5kYRYQoAADSLltbyIFLczQcAAJpFS2t5ECnOTLVgffv21YIFC+Ly3uPGjdPUqVPj8t4AACQSwlSUmFmjjyDB47bbbtPgwYOPWF9QUKDp06cHqLr5rFy5UmamvXv3xrsUAACiist8UVJaWlr99ZIlS3TttdfWWpeRkRH198zKyor6PgEAQNNwZipKevToUf3o3LnzEetWrVqlYcOGqV27durXr59uvfVWHT58uPr1ixYt0pAhQ5SRkaFjjz1WI0eO1O7du7Vw4ULNnz9fxcXF1We5Fi5cKOnIy3xmpoceekiXXXaZ2rdvr2984xt68skna9X5zjvvaOjQoWrXrp3OOOMMLV26VGamlStXNvi9HTp0SFOnTlVmZqa6d++un/70p0eMefLJJ3XmmWeqQ4cO6tatmy677DLt2rVLkvTxxx/rvPPOkxQKgDXP1C1btkznnnuuunTpomOPPVZjxoxRSUlJU3/8AIA4imvLgxkzpPT00HOcEKaawauvvqorrrhCM2fOVHFxsR599FG98MILmjNnjiTps88+06RJkzRlyhSVlJRo1apVuvLKKyVJEydO1I033qiTTz5ZpaWlKi0t1cSJExt8r9tvv10TJkzQ+vXrNXHiRF199dXavn27JOnAgQMaN26cTjnlFBUVF
"text/plain": [
"<Figure size 720x504 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"model_2.eval()\n",
"with torch.inference_mode():\n",
" y_preds = model_2(X_test_regression)\n",
"plot_predictions(train_data=X_train_regression, \n",
" train_labels=y_train_regression,\n",
" test_data=X_test_regression,\n",
" test_labels=y_test_regression,\n",
" predictions=y_preds.detach().numpy());"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "j82n3OyWHC8E"
},
"source": [
"## TK - The missing piece: non-linearity\n",
"\n",
"Our model can draw straight lines, thanks to its linear layers.\n",
"\n",
"But how about we give it the capacity to draw non-straight (non-linear) lines?\n",
"\n",
"Let's try."
]
},
{
"cell_type": "code",
2022-01-31 09:09:12 +10:00
"execution_count": 28,
2022-01-29 16:26:06 +10:00
"metadata": {
"id": "owqilKGBHC8F"
},
"outputs": [],
"source": [
"# Make data\n",
2022-01-31 09:09:12 +10:00
"from sklearn.datasets import make_circles\n",
2022-01-29 16:26:06 +10:00
"\n",
"n_samples = 1000\n",
"\n",
2022-01-31 09:09:12 +10:00
"X, y = make_circles(n_samples=1000,\n",
" noise=0.03,\n",
2022-01-29 16:26:06 +10:00
" random_state=42,\n",
")"
]
},
{
"cell_type": "code",
2022-01-31 09:09:12 +10:00
"execution_count": 29,
2022-01-29 16:26:06 +10:00
"metadata": {
"id": "ODTGd72GHC8F",
2022-01-31 09:09:12 +10:00
"outputId": "a0f1bd61-795f-42ef-f2c8-a7118be55eb9",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 282
}
2022-01-29 16:26:06 +10:00
},
"outputs": [
{
2022-01-31 09:09:12 +10:00
"output_type": "execute_result",
2022-01-29 16:26:06 +10:00
"data": {
"text/plain": [
2022-01-31 09:09:12 +10:00
"<matplotlib.collections.PathCollection at 0x7f1c8683c6d0>"
2022-01-29 16:26:06 +10:00
]
},
"metadata": {},
2022-01-31 09:09:12 +10:00
"execution_count": 29
2022-01-29 16:26:06 +10:00
},
{
2022-01-31 09:09:12 +10:00
"output_type": "display_data",
2022-01-29 16:26:06 +10:00
"data": {
2022-01-31 09:09:12 +10:00
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAXwAAAD4CAYAAADvsV2wAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4yLjIsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+WH4yJAAAgAElEQVR4nOyddXxVZR/Av+f2vSsWjBotIY0goztEEARJE1AQKeEFBJEGBQQBAUFKBZWQlO5O6e5m1AaD1c1zzvvHYDLuvdu920DifD8fY+c8det3nueXgizLKCgoKCi8/Kj+6wUoKCgoKDwbFIGvoKCg8IqgCHwFBQWFVwRF4CsoKCi8IigCX0FBQeEVQfNfL8AdISEhcp48ef7rZSgoKCi8UBw4cCBKluXMru49twI/T5487N+//79ehoKCgsILhSAIV9zdU1Q6CgoKCq8IisBXUFBQeEVQBL6CgoLCK4Ii8BUUFBReERSBr6CQwSTcf8CNk+ewJZjdtnHYbFzcfYCrh46j5LNSeFY8t146CgrPI/H37nNq/XbUWi1F6lVF72NKuuew2ZjzRX/+mfM3Gq0GSZSo1+cL3h7QFUEQktodWbae3z7+H7IsI0sSPsGBdF4+kxzFC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4pCAI+mTLx+aKf+fndDkiiiMNqS3RldZGeARJ32J/NncD5HftZN3oasgs3TVmSubL/KAHZQpHcjJMS57bu5cTqLW6jiyVRRJIk7l2JwODng29IkMt2Cs8WReArJMMcE+tWkKTFUOkbEoQlNhZrbCq6ZZWAVq+nRpdPCP+gCZCoHtkwdga2J4KJdCYjjYf1xC9zMINOrufYyk3cPHGOrIXzU+KdWqi1zq6JKrWaS
2022-01-29 16:26:06 +10:00
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
2022-01-31 09:09:12 +10:00
}
2022-01-29 16:26:06 +10:00
}
],
"source": [
"plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.RdBu)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "0UkH4cKLHC8F",
"outputId": "032d3784-509d-4b43-9438-1d5740861380"
},
"outputs": [
{
"data": {
"text/plain": [
"(tensor([[ 2.0915, 0.3245],\n",
" [-1.1343, 0.4121],\n",
" [-0.1784, 1.1279],\n",
" [-0.0765, 0.9865],\n",
" [ 0.3888, -0.1914]]),\n",
" tensor([1., 0., 0., 0., 1.]))"
]
},
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Convert to tensors and split into train and test sets\n",
"import torch\n",
"from sklearn.model_selection import train_test_split\n",
"X = torch.from_numpy(X).type(torch.float)\n",
"y = torch.from_numpy(y).type(torch.float)\n",
"\n",
"# Split into train and test sets\n",
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,\n",
" random_state=42\n",
")\n",
"\n",
"X_train[:5], y_train[:5]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "i_yG7AFHHC8F",
"outputId": "236686cc-e4d7-465d-9c9f-0f413e142724"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"MoonModelV2(\n",
" (layer_1): Linear(in_features=2, out_features=10, bias=True)\n",
" (layer_2): Linear(in_features=10, out_features=10, bias=True)\n",
" (layer_3): Linear(in_features=10, out_features=1, bias=True)\n",
" (relu): ReLU()\n",
")\n"
]
}
],
"source": [
"# Build model\n",
"from torch import nn\n",
2022-01-31 09:09:12 +10:00
"class CircleModelV2(nn.Module):\n",
2022-01-29 16:26:06 +10:00
" def __init__(self):\n",
" super().__init__()\n",
" self.layer_1 = nn.Linear(in_features=2, out_features=10)\n",
" self.layer_2 = nn.Linear(in_features=10, out_features=10)\n",
" self.layer_3 = nn.Linear(in_features=10, out_features=1)\n",
" self.relu = nn.ReLU()\n",
" # Can also put sigmoid in the model \n",
" # This would mean you don't need to use it on the predictions\n",
" # self.sigmoid = nn.Sigmoid()\n",
"\n",
" def forward(self, x):\n",
" return self.layer_3(self.relu(self.layer_2(self.relu(self.layer_1(x)))))\n",
"\n",
"\n",
2022-01-31 09:09:12 +10:00
"model_3 = CircleModelV2()\n",
2022-01-29 16:26:06 +10:00
"print(model_3)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "uWNlx4lTHC8F"
},
"outputs": [],
"source": [
"# Setup loss and optimizer \n",
"loss_fn = nn.BCEWithLogitsLoss()\n",
"optimizer = torch.optim.SGD(model_3.parameters(), lr=0.1)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "gTS8yTN_HC8F",
"outputId": "d8a55a8e-b5e8-46b5-f1bb-37766cc92d53"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Epoch: 0 | Loss: 0.69510, Accuracy: 38.00%\n",
"Epoch: 100 | Loss: 0.39819, Accuracy: 80.75%\n",
"Epoch: 200 | Loss: 0.26788, Accuracy: 88.12%\n",
"Epoch: 300 | Loss: 0.23489, Accuracy: 89.62%\n",
"Epoch: 400 | Loss: 0.20954, Accuracy: 90.38%\n",
"Epoch: 500 | Loss: 0.17689, Accuracy: 92.25%\n",
"Epoch: 600 | Loss: 0.14114, Accuracy: 94.62%\n",
"Epoch: 700 | Loss: 0.10946, Accuracy: 96.88%\n",
"Epoch: 800 | Loss: 0.08692, Accuracy: 97.62%\n",
"Epoch: 900 | Loss: 0.07172, Accuracy: 97.75%\n"
]
}
],
"source": [
"# Fit the model\n",
"torch.manual_seed(42)\n",
"epochs = 1000\n",
"for epoch in range(epochs):\n",
" # 1. Forward pass\n",
" y_pred = model_3(X_train).squeeze()\n",
" \n",
" # 2. Calculate loss\n",
" loss = loss_fn(y_pred, y_train)\n",
" acc = accuracy_fn(y_true=y_train, \n",
" y_pred=torch.round(torch.sigmoid(y_pred)))\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 what's happening\n",
" if epoch % 100 == 0:\n",
" print(f\"Epoch: {epoch} | Loss: {loss:.5f}, Accuracy: {acc:.2f}%\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "wGHQiWT2HC8G",
"outputId": "4279da7d-3ee6-49eb-ab66-1bdca015043f"
},
"outputs": [
{
"data": {
"text/plain": [
"(tensor([1., 0., 1., 0., 1., 1., 0., 0., 1., 0.]),\n",
" tensor([1., 1., 1., 1., 0., 1., 1., 1., 1., 0.]))"
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Make predictions\n",
"model_3.eval()\n",
"with torch.inference_mode():\n",
" y_preds = torch.round(torch.sigmoid(model_3(X_test))).squeeze()\n",
"y_preds[:10], y[:10] # want preds in same format as truth labels"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "gEeMinjyHC8G",
"outputId": "ced19afc-dd24-48f7-a5bd-c82a9b2f064e"
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAtEAAAF1CAYAAAAurLZiAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjQuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8rg+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xlcroBxVl+O8ugcrVu3kpy4jVItVHtwsYg8Fg7DQavabqyt/mXOdCKqc+xVKgkK608mMwGExEM3aBXCIDwql/tWRRhlQQqx5r63FX3VbIFBCcXN3WmKgsI7oYROChB+kqTRIYDAbjoJKNpuG5NovFX04iuhisGYxYp6nLqSqiicCh+VRn+b4ddhC+ct7mBA6Wdvv2B85gHGFYTjRjx9E3GapO8JzA16z21hi16Lo8iKVfTFVupBRLb0/D1uOGoK/fqSMTSWHqRzchSzKoTEEIYGq2YvATp5kVFYPBOPAEHqxg+b1ZUFkGKBCe9sPgMGH4xbM15zCO5zD0wjimf3JbmZMpBaWAvdeN5hPlIto10g7/nWUUsvlHEWlCwOs0rLCQcSgotfn+44k9yYcGWCSasQtojDrYup0VUQ0icGgd797SAso92lFVJBMCxJaCdY+FUorpH9+GmC2UcrNlUUbSH4Png7m6z8NgMBj7QT6VUwS0JJfErSxKSIeSWLu/suXxJncTzvzaM+h77gS6nh7GiS89ib6PnCg5cKzDawWMffECHAMtiu+1hodzqAVjX7gAXsPibYyDTUlAf3sWPOH2JB8aYJHoY00+mYXv9hLiq2FoDFq0nOqCtce1Iz6nvVfGsPT2FMKza1BOR9BypgstZ7of+9yU1p8bnfLHVNNHqCQjOOllbh8MBuNAE11QL6hen8Nax
"text/plain": [
"<Figure size 864x432 with 2 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"# Plot decision boundaries for training and test sets\n",
"plt.figure(figsize=(12, 6))\n",
"plt.subplot(1, 2, 1)\n",
"plt.title(\"Train\")\n",
"plot_decision_boundary(model_1, X_train, y_train) # model_1 = no non-linearity\n",
"plt.subplot(1, 2, 2)\n",
"plt.title(\"Test\")\n",
"plot_decision_boundary(model_3, X_test, y_test) # model_3 = has non-linearity"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "_1OeaW0FHC8G"
},
"source": [
"## TK - Putting things together by building a multi-class PyTorch model\n",
"\n",
"TK - what is a multi-class model?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "x3_UwcwHHC8G",
"outputId": "8f903562-7f56-4d00-9539-22f5212213bf"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"tensor([[-8.4134, 6.9352],\n",
" [-5.7665, -6.4312],\n",
" [-6.0421, -6.7661],\n",
" [ 3.9508, 0.6984],\n",
" [ 4.2505, -0.2815]]) tensor([3, 2, 2, 1, 1])\n"
]
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAlgAAAGbCAYAAAAY8u5bAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjQuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8rg+JYAAAACXBIWXMAAAsTAAALEwEAmpwYAAEAAElEQVR4nOyddXgUVxeH35lZjQsQ3N3d3a1QakhpqbfUjXpLvf2oC1QpUCgUiru7uzsEAgRCIJ6szsz3x0Jgs7sRGqTtfZ+Hp92RO3c2yc5vzz3ndyRd1xEIBAKBQCAQFB7yzZ6AQCAQCAQCwb8NIbAEAoFAIBAIChkhsAQCgUAgEAgKGSGwBAKBQCAQCAoZIbAEAoFAIBAIChnDzZ7A1RQpUkQvX778zZ6GQCAQCAQCQZ5s27btgq7rRf3tu6UEVvny5dm6devNnoZAIBAIBAJBnkiSdDLQPrFEKBAIBAKBQFDICIElEAgEAoFAUMgIgSUQCAQCgUBQyAiBJRAIBAKBQFDICIElEAgEAoFAUMgIgSUQCAQCgUBQyAiBJRAIBAKBQFDICIElEAgEAoFAUMgIgSUQCAQCgUBQyAiBJRAIBAKBQFDIFIrAkiTpN0mSzkuStPeqbe9KknRGkqSdl/71LIxrCQQCgUAgENzqFFYEayzQ3c/2r3Rdr3/p3/xCupZAIBAIBALBLU2hCCxd11cDSYUxlkAgENxodE3jwBe/MbNse/4Kb8SqvkNJOxx7s6clEAj+wVzvHKynJUnafWkJMdLfAZIkPSZJ0lZJkrYmJiZe5+kIBAKBL1uefJfd73xD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vlBvQmpUOaa51pYpB2O5eLGXdmu9JfR7
"text/plain": [
"<Figure size 720x504 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"import torch\n",
"import matplotlib.pyplot as plt\n",
"from sklearn.datasets import make_blobs\n",
"from sklearn.model_selection import train_test_split\n",
"\n",
"NUM_CLASSES = 4\n",
"NUM_FEATURES = 2\n",
"RANDOM_SEED = 42\n",
"\n",
"# Create data\n",
"X_blob, y_blob = make_blobs(n_samples=1000,\n",
" n_features=NUM_FEATURES,\n",
" centers=NUM_CLASSES,\n",
" cluster_std=1.5,\n",
" random_state=RANDOM_SEED\n",
")\n",
"\n",
"# Turn into tensors\n",
"X_blob = torch.from_numpy(X_blob).type(torch.float)\n",
"y_blob = torch.from_numpy(y_blob).type(torch.LongTensor)\n",
"print(X_blob[:5], y_blob[:5])\n",
"\n",
"# Split into train and test\n",
"X_blob_train, X_blob_test, y_blob_train, y_blob_test = train_test_split(X_blob,\n",
" y_blob,\n",
" test_size=0.2,\n",
" random_state=RANDOM_SEED\n",
")\n",
"\n",
"# Plot data\n",
"plt.figure(figsize=(10, 7))\n",
"plt.scatter(X_blob[:, 0], X_blob[:, 1], c=y_blob, cmap=plt.cm.RdYlBu);"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "xBCnUs0oHC8G"
},
"source": [
"TODO: **Question:** Does this dataset need non-linearity? Or could you draw a succession of straight lines to separate it?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "TGoZCzOrHC8H",
"outputId": "c7126b67-8b56-455c-aa20-9d9841d17ca9"
},
"outputs": [
{
"data": {
"text/plain": [
"BlobModel(\n",
" (linear_layer_stack): Sequential(\n",
" (0): Linear(in_features=2, out_features=8, bias=True)\n",
" (1): Linear(in_features=8, out_features=8, bias=True)\n",
" (2): Linear(in_features=8, out_features=4, bias=True)\n",
" )\n",
")"
]
},
"execution_count": 38,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from torch import nn\n",
"# Build model\n",
"class BlobModel(nn.Module):\n",
" def __init__(self, input_features, output_features, hidden_units):\n",
" super().__init__()\n",
" self.linear_layer_stack = nn.Sequential(\n",
" nn.Linear(in_features=input_features, out_features=hidden_units),\n",
" # nn.ReLU(),\n",
" nn.Linear(in_features=hidden_units, out_features=hidden_units),\n",
" # nn.ReLU(),\n",
" nn.Linear(in_features=hidden_units, out_features=output_features), # how many classes are there?\n",
" )\n",
" \n",
" def forward(self, x):\n",
" return self.linear_layer_stack(x)\n",
"\n",
"model_4 = BlobModel(input_features=NUM_FEATURES, \n",
" output_features=NUM_CLASSES, \n",
" hidden_units=8) # doesn't work with 1, try a different value\n",
"model_4"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "_eOASXWAHC8H"
},
"source": [
"TODO: Explain different loss options for multi-class and binary classification"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "3ngHLo--HC8H"
},
"outputs": [],
"source": [
"# Loss and optimizer\n",
"loss_fn = nn.CrossEntropyLoss()\n",
"optimizer = torch.optim.SGD(model_4.parameters(), lr=0.1)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "55s1Pis9HC8H",
"outputId": "bdd9a172-903c-44ab-9e2b-0309d46c2ad1"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Epoch: 0 | Loss: 1.04324, Accuracy: 65.50%\n",
"Epoch: 10 | Loss: 0.14398, Accuracy: 99.12%\n",
"Epoch: 20 | Loss: 0.08062, Accuracy: 99.12%\n",
"Epoch: 30 | Loss: 0.05924, Accuracy: 99.12%\n",
"Epoch: 40 | Loss: 0.04892, Accuracy: 99.00%\n",
"Epoch: 50 | Loss: 0.04295, Accuracy: 99.00%\n",
"Epoch: 60 | Loss: 0.03910, Accuracy: 99.00%\n",
"Epoch: 70 | Loss: 0.03643, Accuracy: 99.00%\n",
"Epoch: 80 | Loss: 0.03448, Accuracy: 99.00%\n",
"Epoch: 90 | Loss: 0.03300, Accuracy: 99.12%\n"
]
}
],
"source": [
"# Fit the model\n",
"torch.manual_seed(42)\n",
"epochs = 100\n",
"for epoch in range(epochs):\n",
" # 1. Forward pass\n",
" y_pred = model_4(X_blob_train)\n",
"\n",
" # 2. Calculate loss and accuracy\n",
" loss = loss_fn(y_pred, y_blob_train)\n",
" acc = accuracy_fn(y_true=y_blob_train,\n",
" y_pred=y_pred.argmax(dim=1))\n",
"\n",
" # 3. Optimizer zero grad\n",
" optimizer.zero_grad()\n",
"\n",
" # 4. Loss backwards\n",
" loss.backward()\n",
"\n",
" # 5. Optimizer step\n",
" optimizer.step()\n",
"\n",
" # Print out what's happening\n",
" if epoch % 10 == 0:\n",
" print(f\"Epoch: {epoch} | Loss: {loss:.5f}, Accuracy: {acc:.2f}%\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "NjCKKhsGHC8H"
},
"outputs": [],
"source": [
"# Make predictions\n",
"model_4.eval()\n",
"with torch.inference_mode():\n",
" y_preds = model_4(X_blob_test)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "faDQ4oLpHC8H",
"outputId": "9f760bcf-4a3c-4e9e-cfe6-2c7d0c088817"
},
"outputs": [
{
"data": {
"text/plain": [
"tensor([[ 4.3377, 10.3539, -14.8948, -9.7642],\n",
" [ 5.0142, -12.0371, 3.3860, 10.6699],\n",
" [ -5.5885, -13.3448, 20.9894, 12.7711],\n",
" [ 1.8400, 7.5599, -8.6016, -6.9942],\n",
" [ 8.0727, 3.2906, -14.5998, -3.6186],\n",
" [ 5.5844, -14.9521, 5.0168, 13.2891],\n",
" [ -5.9739, -10.1913, 18.8655, 9.9179],\n",
" [ 7.0755, -0.7601, -9.5531, 0.1736],\n",
" [ -5.5918, -18.5990, 25.5310, 17.5799],\n",
" [ 7.3142, 0.7197, -11.2017, -1.2011]])"
]
},
"execution_count": 42,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# TODO: Show the outputs of the model - what do these mean?\n",
"y_preds[:10]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "dJhkzyYJHC8I",
"outputId": "3da24b3a-6c93-4df8-9095-7af088c47d0f"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"tensor([1, 3, 2, 1, 0, 3, 2, 0, 2, 0]) tensor([1, 3, 2, 1, 0, 3, 2, 0, 2, 0])\n",
"Test accuracy: 99.5%\n"
]
}
],
"source": [
"# TODO: Softmax = obtain probabilities, no softmax = logits from model\n",
"print(torch.softmax(y_preds, dim=1).argmax(dim=1)[:10], y_preds.argmax(dim=1)[:10])\n",
"print(f\"Test accuracy: {accuracy_fn(y_true=y_blob_test, y_pred=y_preds.argmax(dim=1))}%\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "kLOzBFdRHC8I",
"outputId": "528c13dc-5055-401a-ce6e-a07823f046da"
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAs8AAAF1CAYAAAAXywc5AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjQuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8rg+JYAAAACXBIWXMAAAsTAAALEwEAmpwYAAD3QElEQVR4nOz9d5Qk6Xmnhz5fRHpblVne2/Zmuqenp8cPZgZDGBLALrg0d3XF1VKHd0nw6AxFcYV7dA9WgrT3cJfaA0jiAHt5Re2SuxL3cgliCRIeGAzGT0/bad9VXd779Dbiu39EVXZlpams6rLd8ZzTp6syIiO+zMr84hfv976/V0gpMTExMTExMTExMTFZH2W3B2BiYmJiYmJiYmKyXzDFs4mJiYmJiYmJiUmFmOLZxMTExMTExMTEpEJM8WxiYmJiYmJiYmJSIaZ4NjExMTExMTExMakQUzybmJiYmJiYmJiYVIgpnk0eaYQQ3xdC/MZuj8PExMTExMRkf2CKZ5N9hxAiuuqfLoRIrPr9H27kWFLKT0sp/2y7xmpiYmJicp+tnL+Xj/emEOK/3I6xmpiUwrLbAzA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iYmJiVZSd+78OYIf/TiK/zBfw2/8/U3+NX63cvPzcRTUCKYo6WySCl3NdijWNSS26QuzcJAk13BjDyb7Fsy8RRTVwYZ/Ok1Ji8P7lqRy8NOUB3LCWcz6mxi8mDstR4AzoAnly+8FrvfteurpIpFpaqjrjD3Whhjt3vN1EeTnccUz7vE117/OOf3abJx4nMRbv31h0x/PEJoZI6Zj0e49dcfEp8zvT23kqA6lmuMYgpnE5Oto
"text/plain": [
"<Figure size 864x432 with 2 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"plt.figure(figsize=(12, 6))\n",
"plt.subplot(1, 2, 1)\n",
"plt.title(\"Train\")\n",
"plot_decision_boundary(model_4, X_blob_train, y_blob_train)\n",
"plt.subplot(1, 2, 2)\n",
"plt.title(\"Test\")\n",
"plot_decision_boundary(model_4, X_blob_test, y_blob_test)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4CbOvj8dHC8I"
},
"source": [
"## TODO: Exercises\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "v4d-S9_-HC8I"
},
"source": [
"## TK - Exercises\n",
"\n",
"* Build a model to fit the spirals data from CS231n - https://cs231n.github.io/neural-networks-case-study/\n",
"\n",
"```python\n",
"N = 100 # number of points per class\n",
"D = 2 # dimensionality\n",
"K = 3 # number of classes\n",
"X = np.zeros((N*K,D)) # data matrix (each row = single example)\n",
"y = np.zeros(N*K, dtype='uint8') # class labels\n",
"for j in range(K):\n",
" ix = range(N*j,N*(j+1))\n",
" r = np.linspace(0.0,1,N) # radius\n",
" t = np.linspace(j*4,(j+1)*4,N) + np.random.randn(N)*0.2 # theta\n",
" X[ix] = np.c_[r*np.sin(t), r*np.cos(t)]\n",
" y[ix] = j\n",
"# lets visualize the data:\n",
"plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral)\n",
"plt.show()\n",
"```\n",
"\n",
"## TODO: Extra-curriculum\n",
"\n",
"* Spend 10-minutes reading the [Wikipedia page for different activation functions](https://en.wikipedia.org/wiki/Activation_function#Table_of_activation_functions), how many of these can you line up with [PyTorch's activation functions](https://pytorch.org/docs/stable/nn.html#non-linear-activations-weighted-sum-nonlinearity)?"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WPEJUDtFHC8I"
},
"source": [
"## TODO\n",
"* ~~Multiclass model~~\n",
"* ~~device agnostic code: GPU model~~ - not doing this due to complications with plotting code, will do it with more advanced modules\n",
"* ~~Fixed data inputs (e.g. calc on tensors when need to calc on tensors)~~\n",
"* ~~Merge the functions so `plot_decision_boundary` works on multi-class~~\n",
"* ~~Introduce non-linearity (the missing piece!) - straight lines and non-straight lines~~\n",
"* Make evaluation functions better - teach someone about different evaluation functions for a classification model\n",
"* Make sure notebook runs from top to bottom\n",
"* Make sure each section can be run individually - all imports should be where they need to be \n",
"* Create helper_functions.py script for different helper functions throughout the course"
2021-10-28 11:31:25 +10:00
]
}
2022-01-29 16:26:06 +10:00
],
"metadata": {
"interpreter": {
"hash": "3fbe1355223f7b2ffc113ba3ade6a2b520cadace5d5ec3e828c83ce02eb221bf"
},
"kernelspec": {
"display_name": "Python 3.9.7 64-bit (conda)",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.7"
},
"orig_nbformat": 4,
"colab": {
"name": "02_pytorch_classification.ipynb",
"provenance": [],
"collapsed_sections": [
"v4d-S9_-HC8I",
"WPEJUDtFHC8I"
],
"include_colab_link": true
},
"accelerator": "GPU"
2021-10-20 11:49:02 +10:00
},
2022-01-29 16:26:06 +10:00
"nbformat": 4,
"nbformat_minor": 0
}