"<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. PyTorch Neural Network Classification\n",
"\n",
"## What is a classification problem?\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",
"\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",
"metadata": {
"id": "9wTlTaDKH7Oj"
},
"source": [
"## What we're going to cover\n",
"\n",
"In this notebook we're going to reiterate over the PyTorch workflow we coverd in notebook 01.\n",
"Except instead of trying to predict a straight line (predicting a number, also called a regression problem), we'll be working on a **classification problem**.\n",
"\n",
"Specifically, we're going to cover:\n",
"\n",
"| **Topic** | **Contents** |\n",
"| ----- | ----- |\n",
"| **0. Architecture of a classification neural network** | Neural networks can come in almost any shape or size, but they typically follow a similar floor plan. |\n",
"| **1. Getting binary classification data ready** | Data can be almost anything but to get started we're going to create a simple binary classification dataset. |\n",
"| **2. Building a PyTorch classification model** | Here we'll create a model to learn patterns in the data, we'll also choose a **loss function**, **optimizer** and build a **training loop** specific to classification. | \n",
"| **3. Fitting the model to data (training)** | We've got data and a model, now let's let the model (try to) find patterns in the (**training**) data. |\n",
"| **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. Improving a model (from a model perspective)** | We've trained an evaluated a model but it's not working, let's try a few things to improve it. |\n",
"| **6. Non-linearity** | So far our model has only had the ability to model straight lines, what about non-linear (non-straight) lines? |\n",
"| **7. Replicating non-linear functions** | We used **non-linear functions** to help model non-linear data, but what do these look like? |\n",
"| **8. Putting it all together with multi-class classification** | Let's put everything we've done so far for binary classification together with a multi-class classification problem. |\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "uxdUc9OfHtgU"
},
"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"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "MSLHJiQxH4jU"
},
"source": [
"## 0. 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",
"| **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",
"\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."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "VwvxFEjKHC71"
},
"source": [
"## 1. Make classification data and get it ready\n",
"\n",
"Let's begin by making some data.\n",
"\n",
"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. "
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"id": "RGeZvHsyHC72"
},
"outputs": [],
"source": [
"from sklearn.datasets import make_circles\n",
"\n",
"\n",
"# Make 1000 samples \n",
"n_samples = 1000\n",
"\n",
"# Create circles\n",
"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"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1FwwzJnQV2jv"
},
"source": [
"Alright, now let's view the first 5 `X` and `y` values."
"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."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Ny6_J7F4HC76"
},
"source": [
"### 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",
"Values for one sample of X: [0.75424625 0.23148074] and the same for y: 1\n",
"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}\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Vn692XaRaifl"
},
"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."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "eLyDPN6ZR_ho"
},
"source": [
"### 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)."
"# 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]"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "r9XNJv8lfmRG"
},
"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."
"device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
"device"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "p1Fil1v04nXr"
},
"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`. "
" # 3. Define a forward method containing the forward pass computation\n",
" def forward(self, x):\n",
" # 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",
"\n",
"# 4. Create an instance of the model and send it to target device\n",
"model_0 = CircleModelV0().to(device)\n",
"model_0"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "TtdkMniZ7KyK"
},
"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",
"\n",
"*A visual example of what a similar classificiation neural network to the one we've just built looks like. Try create one of your own on the [TensorFlow Playground website](https://playground.tensorflow.org/).*\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."
"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."
"print(f\"\\nFirst 10 test labels:\\n{y_test[:10]}\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "q7v8TVnqGMZh"
},
"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, we'll see these later on."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "8aoQn39pHC7_"
},
"source": [
"### 2.1 Setup loss function and optimizer\n",
"\n",
"We've setup a loss (also called a criterion or cost function) and optimizer before in [notebook 01](https://www.learnpytorch.io/01_pytorch_workflow/#creating-a-loss-function-and-optimizer-in-pytorch).\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()`) can be used for a range of problems, so can too the Adam optimizer (`torch.optim.Adam()`). \n",
"\n",
"| Loss function/Optimizer | Problem type | PyTorch Code |\n",
"| Adam Optimizer | Classification, regression, many others. | [`torch.optim.Adam()`](https://pytorch.org/docs/stable/generated/torch.optim.Adam.html) |\n",
"| Binary cross entropy loss | Binary classification | [`torch.nn.BCELossWithLogits`](https://pytorch.org/docs/stable/generated/torch.nn.BCEWithLogitsLoss.html) or [`torch.nn.BCELoss`](https://pytorch.org/docs/stable/generated/torch.nn.BCELoss.html) |\n",
"| Cross entropy loss | Mutli-class classification | [`torch.nn.CrossEntropyLoss`](https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html) |\n",
"| Mean absolute error (MAE) or L1 Loss | Regression | [`torch.nn.L1Loss`](https://pytorch.org/docs/stable/generated/torch.nn.L1Loss.html) | \n",
"| Mean squared error (MSE) or L2 Loss | Regression | [`torch.nn.MSELoss`](https://pytorch.org/docs/stable/generated/torch.nn.MSELoss.html#torch.nn.MSELoss) | \n",
"\n",
"*Table of various loss functions and optimizers, there are more but these some common ones you'll see.*\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) - Creates 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",
"Knowing this, let's create a loss function and an optimizer. \n",
"\n",
"For the optimizer we'll use `torch.optim.SGD()` to optimize the model parameters with learning rate 0.1.\n",
"\n",
"> **Note:** There's a [discussion on the PyTorch forums about the use of `nn.BCELoss` vs. `nn.BCEWithLogitsLoss`](https://discuss.pytorch.org/t/bceloss-vs-bcewithlogitsloss/33586/4). It can be confusing at first but as with many things, it becomes easier with practice."
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"id": "DjpQsdOZHC7_"
},
"outputs": [],
"source": [
"# Create a loss function\n",
"# loss_fn = nn.BCELoss() # BCELoss = no sigmoid built-in\n",
"Now let's also create an **evaluation metric**.\n",
"\n",
"An evaluation metric can be used to offer another perspective on how your model is going.\n",
"\n",
"If a loss function measures how *wrong* your model is, I like to think of evaluation metrics as measuring how *right* it is.\n",
"\n",
"Of course, you could argue both of these are doing the same thing but evaluation metrics offer a different perspective.\n",
"\n",
"After all, when evaluating your models it's good to look at things from multiple points of view.\n",
"\n",
"There are several evaluation metrics that can be used for classification problems but let's start out with **accuracy**.\n",
"\n",
"Accuracy can be measured by dividing the total number of correct predictions over the total number of predictions.\n",
"\n",
"For example, a model that makes 99 correct predictions out of 100 will have an accuracy of 99%.\n",
"\n",
"Let's write a function to do so.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 15,
"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() # torch.eq() calculates where two tensors are equal\n",
" acc = (correct / len(y_pred)) * 100 \n",
" return acc"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "OuplloDPxviL"
},
"source": [
"Excellent! We can now use this function whilst training our model to measure it's performance alongside the loss."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4UpJKZ8PHC8A"
},
"source": [
"## 3. Train model\n",
"\n",
"Okay, now we've got a loss function and optimizer ready to go, let's train a model.\n",
"\n",
"Do you remember the steps in a PyTorch training loop?\n",
"\n",
"If not, here's a reminder.\n",
"\n",
"Steps in training:\n",
"\n",
"<details>\n",
" <summary>PyTorch training loop steps</summary>\n",
" <ol>\n",
" <li><b>Forward pass</b> - The model goes through all of the training data once, performing its\n",
" <code>forward()</code> function\n",
" calculations (<code>model(x_train)</code>).\n",
" </li>\n",
" <li><b>Calculate the loss</b> - The model's outputs (predictions) are compared to the ground truth and evaluated\n",
" to see how\n",
" wrong they are (<code>loss = loss_fn(y_pred, y_train</code>).</li>\n",
" <li><b>Zero gradients</b> - The optimizers gradients are set to zero (they are accumulated by default) so they\n",
" can be\n",
" recalculated for the specific training step (<code>optimizer.zero_grad()</code>).</li>\n",
" <li><b>Perform backpropagation on the loss</b> - Computes the gradient of the loss with respect for every model\n",
" parameter to\n",
" be updated (each parameter\n",
" with <code>requires_grad=True</code>). This is known as <b>backpropagation</b>, hence \"backwards\"\n",
" (<code>loss.backward()</code>).</li>\n",
" <li><b>Step the optimizer (gradient descent)</b> - Update the parameters with <code>requires_grad=True</code>\n",
" with respect to the loss\n",
" gradients in order to improve them (<code>optimizer.step()</code>).</li>\n",
" </ol>\n",
"</details>\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "NMeDqPpsnst6"
},
"source": [
"### 3.1 Going from raw model outputs to predicted labels (logits -> prediction probabilities -> prediction labels)\n",
"\n",
"Before we the training loop steps, let's see what comes out of our model during the forward pass (the forward pass is defined by the `foward()` method).\n",
"# View the frist 5 outputs of the forward pass on the test data\n",
"y_logits = model_0(X_test.to(device))[:5]\n",
"y_logits"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "b1sNl8D8fWXm"
},
"source": [
"Since our model hasn't been trained, these outputs are basically random.\n",
"\n",
"But *what* are they?\n",
"\n",
"They're the output of our `forward()` method.\n",
"\n",
"Which implements two layers of `nn.Linear()` which internally calls the following equation:\n",
"\n",
"$$\n",
"\\mathbf{y} = x \\cdot \\mathbf{Weights}^T + \\mathbf{bias}\n",
"$$\n",
"\n",
"The *raw outputs* (unmodified) of this equation ($\\mathbf{y}$) and in turn, the raw outputs of our model are often referred to as [**logits**](https://datascience.stackexchange.com/a/31045).\n",
"\n",
"That's what our model is outputing above when it takes in the input data ($x$ in the equation or `X_test` in the code), logits.\n",
"\n",
"However, these numbers are hard to interpret.\n",
"\n",
"We'd like some numbers that are comparable to our truth labels.\n",
"\n",
"To get our model's raw outputs (logits) into such a form, we can use the [sigmoid activation function](https://pytorch.org/docs/stable/generated/torch.sigmoid.html).\n",
"Okay, it seems like the outputs now have some kind of consistency (even though they're still random).\n",
"\n",
"They're now in the form of **prediction probabilities** (I usually refer to these as `y_pred_probs`), in other words, the values are now how much the model thinks the data point belongs to one class or another.\n",
"\n",
"In our case, since we're dealing with binary classification, our ideal outputs are 0 or 1.\n",
"\n",
"So these values can be viewed as a decision boundary.\n",
"\n",
"The closer to 0, the more the model thinks the sample belongs to class 0, the closer to 1, the more the model thinks the sample belongs to class 1.\n",
"\n",
"More specificially:\n",
"* If `y_pred_probs` >= 0.5, `y=1` (class 1)\n",
"* If `y_pred_probs` < 0.5, `y=0` (class 0)\n",
"\n",
"To turn our prediction probabilities in prediction labels, we can round the outputs of the sigmoid activation function."
"This means we'll be able to compare our models predictions to the test labels to see how well it's going. \n",
"\n",
"To recap, we converted our model's raw outputs (logits) to predicition probabilities using a sigmoid activation function.\n",
"\n",
"And then converted the prediction probabilities to prediction labels by rounding them.\n",
"\n",
"> **Note:** The use of the sigmoid activation function is often only for binary classification logits. For multi-class classification, we'll be looking at using the [softmax activation function](https://pytorch.org/docs/stable/generated/torch.nn.Softmax.html) (this will come later on).\n",
">\n",
"> And the use of the sigmoid activation function is not required when passing our model's raw outputs to the `nn.BCEWithLogitsLoss` (the \"logits\" in logits loss is because it works on the model's raw logits output), this is because it has a sigmoid function built-in."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Va7gg8yxn6Sg"
},
"source": [
"### 3.2 Building a training and testing loop\n",
"\n",
"Alright, we've discussed how to take our raw model outputs and convert them to prediction labels, now let's build a training loop.\n",
"\n",
"Let's start by training for 100 epochs and outputing the model's progress every 10 epochs. "
" # Print out what's happening every 10 epochs\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}%\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "It1Xy_f5perA"
},
"source": [
"Hmm, what do you notice about the performance of our model?\n",
"\n",
"It looks like it went through the training and testing steps fine but the results don't seem to have moved too much.\n",
"\n",
"The accuracy barely moves above 50% on each data split.\n",
"\n",
"And because we're working with a balanced binary classification problem, it means our model is performing as good as random guessing (with 500 samples of class 0 and class 1 a model predicting class 1 every single time would achieve 50% accuracy)."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WCeyddo-HC8A"
},
"source": [
"## 4. Make predictions and evaluate the model\n",
"\n",
"From the metrics it looks like our model is random guessing.\n",
"\n",
"How could we investigate this further?\n",
"\n",
"I've got an idea.\n",
"\n",
"The data explorer's motto!\n",
"\n",
"\"Visualize, visualize, visualize!\"\n",
"\n",
"Let's make a plot of our model's predictions, the data it's trying to predict on and the decision boundary it's creating for whether something is class 0 or class 1.\n",
"\n",
"To do so, we'll write some code to download and import the [`helper_functions.py` script](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/helper_functions.py) from the [Learn PyTorch for Deep Learning repo](https://github.com/mrdbourke/pytorch-deep-learning).\n",
"\n",
"It contains a helpful function called `plot_decision_boundary()` which creates a NumPy meshgrid to visually plot the different points where our model is predicting certain classes.\n",
"\n",
"We'll also import `plot_predictions()` which we wrote in notebook 01 to use later."
"Oh wow, it seems like we've found the cause of model's performance issue.\n",
"\n",
"It's currently trying to split the red and blue dots using a straight line...\n",
"\n",
"That explains the 50% accuracy. Since our data is circular, drawing a straight line can at best cut it down the middle.\n",
"\n",
"In machine learning terms, our model is **underfitting**, meaning it's not learning predictive patterns from the data.\n",
"\n",
"How could we improve this?"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "6VivsLTmHC8B"
},
"source": [
"## 5. Improving a model (from a model perspective) \n",
"\n",
"Let's try to fix our model's underfitting problem.\n",
"\n",
"Focusing specifically on the model (not the data), there are a few ways we could do this.\n",
"\n",
"| Model improvement technique* | What does it do? |\n",
"| ----- | ----- |\n",
"| **Add more layers** | Each layer *potentially* increases the learning capabilities of the model with each layer being able to learn some kind of new pattern in the data, more layers is often referred to as making your neural network *deeper*. |\n",
"| **Add more hidden units** | Similar to the above, more hidden units per layer means a *potential* increase in learning capabilities of the model, more hidden units is often referred to as making your neural network *wider*. |\n",
"| **Fitting for longer (more epochs)** | Your model might learn more if it had more opportunities to look at the data. |\n",
"| **Changing the activation functions** | Some data just can't be fit with only straight lines (like what we've seen), using non-linear activation functions can help with this (hint, hint). |\n",
"| **Change the learning rate** | Less model specific, but still related, the learning rate of the optimizer decides how much a model should change its parameters each step, too much and the model overcorrects, too little and it doesn't learn enough. |\n",
"| **Change the loss function** | Again, less model specific but still important, different problems require different loss functions. For example, a binary cross entropy loss function won't work with a multi-class classification problem. |\n",
"| **Use transfer learning** | Take a pretrained model from a problem domain similar to yours and adjust it to your own problem. We cover transfer learning in [notebook 06](https://www.learnpytorch.io/06_pytorch_transfer_learning/). |\n",
"\n",
"> **Note:** *because you can adjust all of these by hand, they're referred to as **hyperparameters**. \n",
">\n",
"> And this is also where machine learning's half art half science comes in, there's no real way to know here what the best combination of values is for your project, best to follow the data scientist's motto of \"experiment, experiment, experiment\".\n",
"\n",
"Let's see what happens if we add an extra layer to our model, fit for longer (`epochs=1000` instead of `epochs=100`) and increase the number of hidden units from `5` to `10`.\n",
"\n",
"We'll follow the same steps we did above but with a few changed hyperparameters."
"To do so, we'll use the `plot_predictions()` function we created in notebook 01. \n",
"\n",
"It's contained within the [`helper_functions.py` script](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/helper_functions.py) on the Learn PyTorch for Deep Learning repo which we downloaded above."
"Now let's train the model using the regular training loop steps for `epochs=1000` (just like `model_1`).\n",
"\n",
"> **Note:** We've been writing similar training loop code over and over again. I've made it that way on purpose though, to keep practicing. However, do you have ideas how we could functionize this? That would save a fair bit of coding in the future. Potentially there could be a function for training and a function for testing. "
" print(f\"Epoch: {epoch} | Train loss: {loss:.5f}, Test loss: {test_loss:.5f}\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "IoyLsZW78m_6"
},
"source": [
"Okay, unlike `model_1` on the classification data, it looks like `model_2`'s loss is actually going down.\n",
"\n",
"Let's plot its predictions to see if that's so.\n",
"\n",
"And remember, since our model and data are using the target `device`, and this device may be a GPU, however, our plotting function uses matplotlib and matplotlib can't handle data on the GPU.\n",
"\n",
"To handle that, we'll send all of our data to the CPU using [`.cpu()`](https://pytorch.org/docs/stable/generated/torch.Tensor.cpu.html) when we pass it to `plot_predictions()`."
"Alright, it looks like our model is able to do far better than random guessing on straight lines.\n",
"\n",
"This is a good thing.\n",
"\n",
"It means our model at least has *some* capacity to learn.\n",
"\n",
"> **Note:** A helpful troubleshooting step when building deep learning models is to start as small as possible to see if the model works before scaling it up. \n",
">\n",
"> This could mean starting with a simple neural network (not many layers, not many hidden neurons) and a small dataset (like the one we've made) and then **overfitting** (making the model perform too well) on that small example before increasing the amount data or the model size/design to *reduce* overfitting.\n",
"\n",
"So what could it be?\n",
"\n",
"Let's find out."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "j82n3OyWHC8E"
},
"source": [
"## 6. The missing piece: non-linearity \n",
"\n",
"We've seen our model can draw straight (linear) 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",
"How?\n",
"\n",
"Let's find out.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "cmfOV8v6__17"
},
"source": [
"### 6.1 Recreating non-linear data (red and blue circles)\n",
"\n",
"First, let's recreate the data to start off fresh. We'll use the same setup as before. "
"What kind of pattern do you think you could draw with unlimited straight (linear) and non-straight (non-linear) lines?\n",
"\n",
"I bet you could get pretty creative.\n",
"\n",
"So far our neural networks have only been using linear (straight) line functions.\n",
"\n",
"But the data we've been working with is non-linear (circles).\n",
"\n",
"What do you think will happen when we introduce the capability for our model to use **non-linear actviation functions**?\n",
"\n",
"Well let's see.\n",
"\n",
"PyTorch has a bunch of [ready-made non-linear activation functions](https://pytorch.org/docs/stable/nn.html#non-linear-activations-weighted-sum-nonlinearity) that do similiar but different things. \n",
"One of the most common and best performing is [ReLU](https://en.wikipedia.org/wiki/Rectifier_(neural_networks)) (rectified linear-unit, [`torch.nn.ReLU()`](https://pytorch.org/docs/stable/generated/torch.nn.ReLU.html)).\n",
"\n",
"*A visual example of what a similar classificiation neural network to the one we've just built (suing ReLU activation) looks like. Try create one of your own on the [TensorFlow Playground website](https://playground.tensorflow.org/).*\n",
"\n",
"> **Question:** *Where should I put the non-linear activation functions when constructing a neural network?*\n",
">\n",
"> A rule of thumb is to put them in between hidden layers and just after the output layer, however, there is no set in stone option. As you learn more about neural networks and deep learning you'll find a bunch of different ways of putting things together. In the meantine, best to experiment, experiment, experiment.\n",
"\n",
"Now we've got a model ready to go, let's create a binary classification loss function as well as an optimizer."
" print(f\"Epoch: {epoch} | Loss: {loss:.5f}, Accuracy: {acc:.2f}% | Test Loss: {test_loss:.5f}, Test Accuracy: {test_acc:.2f}%\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "x89XvV-EMqvB"
},
"source": [
"Ho ho! That's looking far better!"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "tfViHC1aM15t"
},
"source": [
"### 6.4 Evaluating a model trained with non-linear activation functions\n",
"\n",
"Remember how our circle data is non-linear? Well, let's see how our models predictions look now the model's been trained with non-linear activation functions."
"We saw before how adding non-linear activation functions to our model can helped it to model non-linear data.\n",
"\n",
"> **Note:** Much of the data you'll encounter in the wild is non-linear (or a combination of linear and non-linear). Right now we've been working with dots on a 2D plot. But imagine if you had images of plants you'd like to classify, there's a lot of different plant shapes. Or text from Wikipedia you'd like to summarize, there's lots of different ways words can be put together (linear and non-linear patterns). \n",
"\n",
"But what does a non-linear activation *look* like?\n",
"\n",
"How about we replicate some and what they do?\n",
"Nice! That looks exactly like the shape of the ReLU function on the [Wikipedia page for ReLU](https://en.wikipedia.org/wiki/Rectifier_(neural_networks)).\n",
"\n",
"How about we try the [sigmoid function](https://en.wikipedia.org/wiki/Sigmoid_function) we've been using?\n",
"\n",
"The sigmoid function formula goes like so:\n",
"\n",
"$$ out_i = \\frac{1}{1+e^{-input_i}} $$ \n",
"\n",
"Or using $x$ as input:\n",
"\n",
"$$ S(x) = \\frac{1}{1+e^{-x_i}} $$\n",
"\n",
"Where $S$ stands for sigmoid, $e$ stands for [exponential](https://en.wikipedia.org/wiki/Exponential_function) ([`torch.exp()`](https://pytorch.org/docs/stable/generated/torch.exp.html)) and $i$ stands for a particular element in a tensor.\n",
"\n",
"Let's build a function to replicate the sigmoid function with PyTorch."
"Looking good! We've gone from a straight line to a curved line.\n",
"\n",
"Now there's plenty more [non-linear activation functions](https://pytorch.org/docs/stable/nn.html#non-linear-activations-weighted-sum-nonlinearity) that exist in PyTorch that we haven't tried.\n",
"\n",
"But these two are two of the most common.\n",
"\n",
"And the point remains, what patterns could you draw using an unlimited amount of linear (straight) and non-linear (not straight) lines?\n",
"\n",
"Almost anything right?\n",
"\n",
"That's exactly what our model is doing when we combine linear and non-linear functions.\n",
"\n",
"Instead of telling our model what to do, we give it tools to figure out how to best discover patterns in the data.\n",
"\n",
"And those tools are linear and non-linear functions."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "_1OeaW0FHC8G"
},
"source": [
"## 8. Putting things together by building a multi-class PyTorch model\n",
"\n",
"We've covered a fair bit.\n",
"\n",
"But now let's put it all together using a multi-class classification problem.\n",
"\n",
"Recall a **binary classification** problem deals with classifying something as one of two options (e.g. a photo as a cat photo or a dog photo) where as a **multi-class classification** problem deals with classifying something from a list of *more than* two options (e.g. classifying a photo as a cat a dog or a chicken).\n",
"\n",
"\n",
"*Example of binary vs. multi-class classification. Binary deals with two classes (one thing or another), where as multi-class classification can deal with any number of classes over two, for example, the popular [ImageNet-1k dataset](https://www.image-net.org/) is used as a computer vision benchmark and has 1000 classes.*\n"
"To begin a multi-class classification problem, let's create some multi-class data.\n",
"\n",
"To do so, we can leverage Scikit-Learn's [`make_blobs()`](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_blobs.html) method.\n",
"\n",
"This method will create however many classes (using the `centers` parameter) we want.\n",
"\n",
"Specifically, let's do the following:\n",
"\n",
"1. Create some multi-class data with `make_blobs()`.\n",
"2. Turn the data into tensors (the default of `make_blobs()` is to use NumPy arrays).\n",
"3. Split the data into training and test sets using `train_test_split()`.\n",
"Nice! Looks like we've got some multi-class data ready to go.\n",
"\n",
"Let's build a model to separate the coloured blobs. \n",
"\n",
"> **Question:** Does this dataset need non-linearity? Or could you draw a succession of straight lines to separate it?"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "_dINSA0Chiof"
},
"source": [
"### 8.2 Building a multi-class classification model in PyTorch\n",
"\n",
"We've created a few models in PyTorch so far.\n",
"\n",
"You might also be starting to get an idea of how flexible neural networks are.\n",
"\n",
"How about we build one similar to `model_3` but this still capable of handling multi-class data?\n",
"\n",
"To do so, let's create a subclass of `nn.Module` that takes in three hyperparameters:\n",
"* `input_features` - the number of `X` features coming into the model.\n",
"* `output_features` - the ideal numbers of output features we'd like (this will be equivalent to `NUM_CLASSES` or the number of classes in your multi-class classification problem).\n",
"* `hidden_units` - the number of hidden neurons we'd like each hidden layer to use.\n",
"\n",
"Since we're putting things together, let's setup some device agnostic code (we don't have to do this again in the same notebook, it's only a reminder).\n",
"\n",
"Then we'll create the model class using the hyperparameters above."
" lr=0.1) # exercise: try changing the learning rate here and seeing what happens to the model's performance"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "orcVVmLzo3gX"
},
"source": [
"### 8.4 Getting prediction probabilities for a multi-class PyTorch model\n",
"\n",
"Alright, we've got a loss function and optimizer ready, and we're ready to train our model but before we do let's do a single forward pass with our model to see if it works."
"It may still look like the outputs of the softmax function are jumbled numbers (and they are, since our model hasn't been trained and is predicting using random patterns) but there's a very specific thing different about each sample.\n",
"\n",
"After passing the logits through the softmax function, each individual sample now adds to 1 (or very close to).\n",
"# Sum the first sample output of the softmax activation function \n",
"torch.sum(y_pred_probs[0])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "yhwu9ln1sbl7"
},
"source": [
"These prediction probablities are essentially saying how much the model *thinks* the target `X` sample (the input) maps to each class.\n",
"\n",
"Since there's one value for each class in `y_pred_probs`, the index of the *highest* value is the class the model thinks the specific data sample *most* belongs to.\n",
"\n",
"We can check which index has the highest value using `torch.argmax()`."
"# Which class does the model think is *most* likely at the index 0 sample?\n",
"print(y_pred_probs[0])\n",
"print(torch.argmax(y_pred_probs[0]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "9veE071JtSZJ"
},
"source": [
"You can see the output of `torch.argmax()` returns 3, so for the features (`X`) of the sample at index 0, the model is predicting that the most likely class value (`y`) is 3.\n",
"\n",
"Of course, right now this is just random guessing so it's got a 25% chance of being right (since there's four classes). But we can improve those chances by training the model.\n",
"\n",
"> **Note:** To summarize the above, a model's raw output is referred to as **logits**.\n",
"> \n",
"> For a multi-class classification problem, to turn the logits into **prediction probabilities**, you use the softmax activation function (`torch.softmax`).\n",
">\n",
"> The index of the value with the highest **prediction probability** is the class number the model thinks is *most* likely given the input features for that sample (although this is a prediction, it doesn't mean it will be correct)."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "hlqJ3_xTupU3"
},
"source": [
"### 8.5 Creating a training and testing loop for a multi-class PyTorch model\n",
"\n",
"Alright, now we've got all of the preparation steps out of the way, let's write a training and testing loop to improve and evaluation our model.\n",
"\n",
"We've done many of these steps before so much of this will be practice.\n",
"\n",
"The only difference is that we'll be adjusting the steps to turn the model outputs (logits) to prediction probabilities (using the softmax activation function) and then to prediction labels (by taking the argmax of the output of the softmax activation function).\n",
"\n",
"Let's train the model for `epochs=100` and evaluate it every 10 epochs."
"Alright, looks like our model's predictions are still in logit form.\n",
"\n",
"Though to evaluate them, they'll have to be in the same form as our labels (`y_blob_test`) which are in integer form.\n",
"\n",
"Let's convert our model's prediction logits to prediction probabilities (using `torch.softmax()`) then to prediction labels (by taking the `argmax()` of each sample).\n",
"\n",
"> **Note:** It's possible to skip the `torch.softmax()` function and go straight from `predicted logits -> predicted labels` by calling `torch.argmax()` directly on the logits.\n",
">\n",
"> For example, `y_preds = torch.argmax(y_logits, dim=1)`, this saves a computation step (no `torch.softmax()`) but results in no prediction probabilities being available to use. "
"Nice! Our model predictions are now in the same form as our test labels.\n",
"\n",
"Let's visualize them with `plot_decision_boundary()`, remember because our data is on the GPU, we'll have to move it to the CPU for use with matplotlib (`plot_decision_boundary()` does this automatically for us)."
"| Accuracy | Out of 100 predictions, how many does your model get correct? E.g. 95% accuracy means it gets 95/100 predictions correct. | [`torchmetrics.Accuracy()`](https://torchmetrics.readthedocs.io/en/latest/references/modules.html#id3) or [`sklearn.metrics.accuracy_score()`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html) |\n",
"| Precision | Proportion of true positives over total number of samples. Higher precision leads to less false positives (model predicts 1 when it should've been 0). | [`torchmetrics.Precision()`](https://torchmetrics.readthedocs.io/en/latest/references/modules.html#id4) or [`sklearn.metrics.precision_score()`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_score.html) |\n",
"| Recall | Proportion of true positives over total number of true positives and false negatives (model predicts 0 when it should've been 1). Higher recall leads to less false negatives. | [`torchmetrics.Recall()`](https://torchmetrics.readthedocs.io/en/latest/references/modules.html#id5) or [`sklearn.metrics.recall_score()`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.recall_score.html) |\n",
"| F1-score | Combines precision and recall into one metric. 1 is best, 0 is worst. | [`torchmetrics.F1Score()`](https://torchmetrics.readthedocs.io/en/latest/references/modules.html#f1score) or [`sklearn.metrics.f1_score()`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html) |\n",
"| [Confusion matrix](https://www.dataschool.io/simple-guide-to-confusion-matrix-terminology/) | Compares the predicted values with the true values in a tabular way, if 100% correct, all values in the matrix will be top left to bottom right (diagnol line). | [`torchmetrics.ConfusionMatrix`](https://torchmetrics.readthedocs.io/en/latest/references/modules.html#confusionmatrix) or [`sklearn.metrics.plot_confusion_matrix()`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.ConfusionMatrixDisplay.html#sklearn.metrics.ConfusionMatrixDisplay.from_predictions) |\n",
"| Classification report | Collection of some of the main classification metrics such as precision, recall and f1-score. | [`sklearn.metrics.classification_report()`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html) |\n",
"\n",
"Scikit-Learn (a popular and world-class machine learning library) has many implementations of the above metrics and you're looking for a PyTorch-like version, check out [TorchMetrics](https://torchmetrics.readthedocs.io/en/latest/), especially the [TorchMetrics classification section](https://torchmetrics.readthedocs.io/en/latest/references/modules.html#classification). \n",
"\n",
"Let's try the `torchmetrics.Accuracy` metric out.\n",
"All of the exercises are focused on practicing the code in the sections above.\n",
"\n",
"You should be able to complete them by referencing each section or by following the resource(s) linked.\n",
"\n",
"All exercises should be completed using [device-agonistic code](https://pytorch.org/docs/stable/notes/cuda.html#device-agnostic-code).\n",
"\n",
"Resources:\n",
"* [Exercise template notebook for 02](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/extras/exercises/02_pytorch_classification_exercises.ipynb)\n",
"* [Example solutions notebook for 02](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/extras/solutions/02_pytorch_classification_exercise_solutions.ipynb) (try the exercises *before* looking at this)\n",
"\n",
"1. Make a binary classification dataset with Scikit-Learn's [`make_moons()`](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_moons.html) function.\n",
" * For consistency, the dataset should have 1000 samples and a `random_state=42`.\n",
" * Turn the data into PyTorch tensors. Split the data into training and test sets using `train_test_split` with 80% training and 20% testing.\n",
"2. Build a model by subclassing `nn.Module` that incorporates non-linear activation functions and is capable of fitting the data you created in 1.\n",
" * Feel free to use any combination of PyTorch layers (linear and non-linear) you want.\n",
"3. Setup a binary classification compatible loss function and optimizer to use when training the model.\n",
"4. Create a training and testing loop to fit the model you created in 2 to the data you created in 1.\n",
" * To measure model accuray, you can create your own accuracy function or use the accuracy function in [TorchMetrics](https://torchmetrics.readthedocs.io/en/latest/).\n",
" * Train the model for long enough for it to reach over 96% accuracy.\n",
" * The training loop should output progress every 10 epochs of the model's training and test set loss and accuracy.\n",
"5. Make predictions with your trained model and plot them using the `plot_decision_boundary()` function created in this notebook.\n",
"6. Replicate the Tanh (hyperbolic tangent) activation function in pure PyTorch.\n",
" * Feel free to reference the [ML cheatsheet website](https://ml-cheatsheet.readthedocs.io/en/latest/activation_functions.html#tanh) for the formula.\n",
"7. Create a multi-class dataset using the [spirals data creation function from CS231n](https://cs231n.github.io/neural-networks-case-study/\n",
" ) (see below for the code).\n",
" * Construct a model capable of fitting the data (you may need a combination of linear and non-linear layers).\n",
" * Build a loss function and optimizer capable of handling multi-class data (optional extension: use the Adam optimizer instead of SGD, you may have to experiment with different values of the learning rate to get it working).\n",
" * Make a training and testing loop for the multi-class data and train a model on it to reach over 95% testing accuracy (you can use any accuracy measuring function here that you like).\n",
" * Plot the decision boundaries on the spirals dataset from your model predictions, the `plot_decision_boundary()` function should work for this dataset too.\n",
"\n",
"```python\n",
"# Code for creating a spiral dataset from CS231n\n",
"import numpy as np\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",
"* Write down 3 problems where you think machine classification could be useful (these can be anything, get creative as you like, for example, classifying credit card transactions as fraud or not fraud based on the purchase amount and purchase location features). \n",
"* Research the concept of \"momentum\" in gradient-based optimizers (like SGD or Adam), what does it mean?\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)?\n",
"* Research when accuracy might be a poor metric to use (hint: read [\"Beyond Accuracy\" by by Will Koehrsen](https://willkoehrsen.github.io/statistics/learning/beyond-accuracy-precision-and-recall/) for ideas).\n",
"* **Watch:** For an idea of what's happening within our neural networks and what they're doing to learn, watch [MIT's Introduction to Deep Learning video](https://youtu.be/7sB052Pz0sQ)."