mirror of
https://github.com/mrdbourke/pytorch-deep-learning.git
synced 2026-11-27 06:07:09 +00:00
add exercises for 02
This commit is contained in:
1 parent
66c90fa48e
commit
1d822855ef
1 file changed
+641
@@ -0,0 +1,641 @@
|
||||
{
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"name": "02_pytorch_classification_exercises.ipynb",
|
||||
"provenance": [],
|
||||
"collapsed_sections": [],
|
||||
"authorship_tag": "ABX9TyNloicnciRwCXd2bJo6F2iS",
|
||||
"include_colab_link": true
|
||||
},
|
||||
"kernelspec": {
|
||||
"name": "python3",
|
||||
"display_name": "Python 3"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
},
|
||||
"accelerator": "GPU"
|
||||
},
|
||||
"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/extras/exercises/02_pytorch_classification_exercises.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"# 02. PyTorch Classification Exercises\n",
|
||||
"\n",
|
||||
"The following is a template for 02. PyTorch Classification exercises.\n",
|
||||
"\n",
|
||||
"It's only starter code and it's your job to fill in the blanks.\n",
|
||||
"\n",
|
||||
"Because of the flexibility of PyTorch, there may be more than one way to answer the question.\n",
|
||||
"\n",
|
||||
"Don't worry about trying to be *right* just try writing code that suffices the question.\n",
|
||||
"\n",
|
||||
"## Resources\n",
|
||||
"* These exercises are based on [notebook 02 of the learn PyTorch course](https://www.learnpytorch.io/02_pytorch_classification/).\n",
|
||||
"* You can see one form of [solutions on GitHub](https://github.com/mrdbourke/pytorch-deep-learning/tree/main/extras/solutions) (but try the exercises below yourself first!)."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "ZKJFt7YxH8yl"
|
||||
}
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# Import torch\n",
|
||||
"import torch\n",
|
||||
"\n",
|
||||
"# Setup device agnostic code\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Setup random seed\n",
|
||||
"RANDOM_SEED = 42"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "CSrUPgapO0tf"
|
||||
},
|
||||
"execution_count": 1,
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"## 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. \n",
|
||||
" * Split the data into training and test sets using `train_test_split` with 80% training and 20% testing."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "pH7jIZ2SPFee"
|
||||
}
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# Create a dataset with Scikit-Learn's make_moons()\n",
|
||||
"from sklearn.datasets import make_moons"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "5t4VhPV1PX1X"
|
||||
},
|
||||
"execution_count": 2,
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# Turn data into a DataFrame\n",
|
||||
"import pandas as pd\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "SUeHZ3-3P9C7"
|
||||
},
|
||||
"execution_count": 3,
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# Visualize the data on a scatter plot\n",
|
||||
"import matplotlib.pyplot as plt\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "owrkPSFvQPFI"
|
||||
},
|
||||
"execution_count": 4,
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# Turn data into tensors of dtype float\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Split the data into train and test sets (80% train, 20% test)\n",
|
||||
"from sklearn.model_selection import train_test_split\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "bDhyHn9fR4dq"
|
||||
},
|
||||
"execution_count": 5,
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"## 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."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "cMIjxZdzQfPz"
|
||||
}
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"import torch\n",
|
||||
"from torch import nn\n",
|
||||
"\n",
|
||||
"# Inherit from nn.Module to make a model capable of fitting the mooon data\n",
|
||||
"class MoonModelV0(nn.Module):\n",
|
||||
" ## Your code here ##\n",
|
||||
"\n",
|
||||
" def forward(self, x):\n",
|
||||
" ## Your code here ##\n",
|
||||
" return \n",
|
||||
"\n",
|
||||
"# Instantiate the model\n",
|
||||
"## Your code here ##"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "hwtyvm34Ri6Q"
|
||||
},
|
||||
"execution_count": 6,
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"## 3. Setup a binary classification compatible loss function and optimizer to use when training the model built in 2."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "DSj97RwyVeFE"
|
||||
}
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# Setup loss function\n",
|
||||
"\n",
|
||||
"# Setup optimizer to optimize model's parameters"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "whSGw5qgVvxU"
|
||||
},
|
||||
"execution_count": 7,
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"## 4. Create a training and testing loop to fit the model you created in 2 to the data you created in 1.\n",
|
||||
" * Do a forward pass of the model to see what's coming out in the form of logits, prediction probabilities and labels.\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."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "nvk4PfNTWUAt"
|
||||
}
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# What's coming out of our model?\n",
|
||||
"\n",
|
||||
"# logits (raw outputs of model)\n",
|
||||
"print(\"Logits:\")\n",
|
||||
"## Your code here ##\n",
|
||||
"\n",
|
||||
"# Prediction probabilities\n",
|
||||
"print(\"Pred probs:\")\n",
|
||||
"## Your code here ##\n",
|
||||
"\n",
|
||||
"# Prediction probabilities\n",
|
||||
"print(\"Pred labels:\")\n",
|
||||
"## Your code here ##"
|
||||
],
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
},
|
||||
"id": "AgnFdlamd2-D",
|
||||
"outputId": "627d8c33-071e-4925-f18b-5d5ba6126729"
|
||||
},
|
||||
"execution_count": 8,
|
||||
"outputs": [
|
||||
{
|
||||
"output_type": "stream",
|
||||
"name": "stdout",
|
||||
"text": [
|
||||
"Logits:\n",
|
||||
"Pred probs:\n",
|
||||
"Pred labels:\n"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# Let's calculuate the accuracy using accuracy from TorchMetrics\n",
|
||||
"!pip -q install torchmetrics # Colab doesn't come with torchmetrics\n",
|
||||
"from torchmetrics import Accuracy\n",
|
||||
"\n",
|
||||
"## TODO: Uncomment this code to use the Accuracy function\n",
|
||||
"# acc_fn = Accuracy().to(device) # send accuracy function to device\n",
|
||||
"# acc_fn"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "rUSDNHB4euoJ"
|
||||
},
|
||||
"execution_count": 9,
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"## TODO: Uncomment this to set the seed\n",
|
||||
"# torch.manual_seed(RANDOM_SEED)\n",
|
||||
"\n",
|
||||
"# Setup epochs\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Send data to the device\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Loop through the data\n",
|
||||
"# for epoch in range(epochs):\n",
|
||||
" ### Training\n",
|
||||
" \n",
|
||||
"\n",
|
||||
" # 1. Forward pass (logits output)\n",
|
||||
" \n",
|
||||
" # Turn logits into prediction probabilities\n",
|
||||
" \n",
|
||||
"\n",
|
||||
" # Turn prediction probabilities into prediction labels\n",
|
||||
" \n",
|
||||
"\n",
|
||||
" # 2. Calculaute the loss\n",
|
||||
" # loss = loss_fn(y_logits, y_train) # loss = compare model raw outputs to desired model outputs\n",
|
||||
"\n",
|
||||
" # Calculate the accuracy\n",
|
||||
" # acc = acc_fn(y_pred, y_train.int()) # the accuracy function needs to compare pred labels (not logits) with actual labels\n",
|
||||
"\n",
|
||||
" # 3. Zero the gradients\n",
|
||||
" \n",
|
||||
"\n",
|
||||
" # 4. Loss backward (perform backpropagation) - https://brilliant.org/wiki/backpropagation/#:~:text=Backpropagation%2C%20short%20for%20%22backward%20propagation,to%20the%20neural%20network's%20weights.\n",
|
||||
" \n",
|
||||
" # 5. Step the optimizer (gradient descent) - https://towardsdatascience.com/gradient-descent-algorithm-a-deep-dive-cf04e8115f21#:~:text=Gradient%20descent%20(GD)%20is%20an,e.g.%20in%20a%20linear%20regression) \n",
|
||||
" \n",
|
||||
"\n",
|
||||
" ### Testing\n",
|
||||
" # model_0.eval() \n",
|
||||
" # with torch.inference_mode():\n",
|
||||
" # 1. Forward pass (to get the logits)\n",
|
||||
" \n",
|
||||
" # Turn the test logits into prediction labels\n",
|
||||
" \n",
|
||||
"\n",
|
||||
" # 2. Caculate the test loss/acc\n",
|
||||
" \n",
|
||||
"\n",
|
||||
" # Print out what's happening every 100 epochs\n",
|
||||
" # if epoch % 100 == 0:\n",
|
||||
" "
|
||||
],
|
||||
"metadata": {
|
||||
"id": "SHBY3h7XXnxt"
|
||||
},
|
||||
"execution_count": 10,
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"## 5. Make predictions with your trained model and plot them using the `plot_decision_boundary()` function created in this notebook."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "8Nwihtomj9JO"
|
||||
}
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# Plot the model predictions\n",
|
||||
"import numpy as np\n",
|
||||
"\n",
|
||||
"def plot_decision_boundary(model, X, y):\n",
|
||||
" \n",
|
||||
" # Put everything to CPU (works better with NumPy + Matplotlib)\n",
|
||||
" model.to(\"cpu\")\n",
|
||||
" X, y = X.to(\"cpu\"), y.to(\"cpu\")\n",
|
||||
"\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",
|
||||
" # Make features\n",
|
||||
" X_to_pred_on = torch.from_numpy(np.column_stack((xx.ravel(), yy.ravel()))).float()\n",
|
||||
"\n",
|
||||
" # Make predictions\n",
|
||||
" model.eval()\n",
|
||||
" with torch.inference_mode():\n",
|
||||
" y_logits = model(X_to_pred_on)\n",
|
||||
"\n",
|
||||
" # Test for multi-class or binary and adjust logits to prediction labels\n",
|
||||
" if len(torch.unique(y)) > 2:\n",
|
||||
" y_pred = torch.softmax(y_logits, dim=1).argmax(dim=1) # mutli-class\n",
|
||||
" else: \n",
|
||||
" y_pred = torch.round(torch.sigmoid(y_logits)) # 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())"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "0YRzatb8a1P2"
|
||||
},
|
||||
"execution_count": 11,
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# Plot decision boundaries for training and test sets\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "PMrcpyirig1d"
|
||||
},
|
||||
"execution_count": 12,
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"## 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."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "EtMYBvtciiAU"
|
||||
}
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# Create a straight line tensor\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "BlXaWC5TkEUE"
|
||||
},
|
||||
"execution_count": 13,
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# Test torch.tanh() on the tensor and plot it\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "vZPCcQmIkZjO"
|
||||
},
|
||||
"execution_count": 14,
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# Replicate torch.tanh() and plot it\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "J-ne__Kjkdc1"
|
||||
},
|
||||
"execution_count": 15,
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"## 7. Create a multi-class dataset using the [spirals data creation function from CS231n](https://cs231n.github.io/neural-networks-case-study/) (see below for the code).\n",
|
||||
" * Split the data into training and test sets (80% train, 20% test) as well as turn it into PyTorch tensors.\n",
|
||||
" * Construct a model capable of fitting the data (you may need a combination of linear and non-linear layers).\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) - 1000 epochs should be plenty.\n",
|
||||
" * Plot the decision boundaries on the spirals dataset from your model predictions, the `plot_decision_boundary()` function should work for this dataset too."
|
||||
],
|
||||
"metadata": {
|
||||
"id": "Lbt1bNcWk5G9"
|
||||
}
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# Code for creating a spiral dataset from CS231n\n",
|
||||
"import numpy as np\n",
|
||||
"import matplotlib.pyplot as plt\n",
|
||||
"RANDOM_SEED = 42\n",
|
||||
"np.random.seed(RANDOM_SEED)\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.RdYlBu)\n",
|
||||
"plt.show()"
|
||||
],
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/",
|
||||
"height": 265
|
||||
},
|
||||
"id": "tU-UNZsKlJls",
|
||||
"outputId": "8b7b745a-070d-4ecb-c639-c4ee4d8eae06"
|
||||
},
|
||||
"execution_count": 16,
|
||||
"outputs": [
|
||||
{
|
||||
"output_type": "display_data",
|
||||
"data": {
|
||||
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAYIAAAD4CAYAAADhNOGaAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4yLjIsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+WH4yJAAAgAElEQVR4nOydd3gcxd2A39mrKpYsW+5N7r1isOlgMJhqSkILvYWeSigplARiShLIB6GEEFooxjRjDMYGjA3YuPcq925ZsmWV6zffH3MnXdk7tVOf93n0SNqd2Z2Tduc386tCSolGo9FoWi9GYw9Ao9FoNI2LFgQajUbTytGCQKPRaFo5WhBoNBpNK0cLAo1Go2nlWBt7ALUhNzdX5uXlNfYwNBqNplmxdOnSQ1LKDrHHm6UgyMvLY8mSJY09DI1Go2lWCCF2mB3XqiGNRqNp5WhBoNFoNK0cLQg0Go2mlaMFgUaj0bRymqWxWJNadu0uZvGSPWSk2zj5pDzS022NPSSNRtOAaEHQipFS8tcn5zF9xgYADEMgBDw1ZRInjO/ZyKPTaDQNhVYNtWI+n7WZ6TM24PUG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YPra4itCLine truncated
|
||||
"text/plain": [
|
||||
"<Figure size 432x288 with 1 Axes>"
|
||||
]
|
||||
},
|
||||
"metadata": {
|
||||
"needs_background": "light"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# Turn data into tensors\n",
|
||||
"import torch\n",
|
||||
"X = torch.from_numpy(X).type(torch.float) # features as float32\n",
|
||||
"y = torch.from_numpy(y).type(torch.LongTensor) # labels need to be of type long\n",
|
||||
"\n",
|
||||
"# Create train and test splits\n",
|
||||
"from sklearn.model_selection import train_test_split\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "OWVrmkEyl0VP"
|
||||
},
|
||||
"execution_count": 17,
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# Let's calculuate the accuracy for when we fit our model\n",
|
||||
"!pip -q install torchmetrics # colab doesn't come with torchmetrics\n",
|
||||
"from torchmetrics import Accuracy\n",
|
||||
"\n",
|
||||
"## TODO: uncomment the two lines below to send the accuracy function to the device\n",
|
||||
"# acc_fn = Accuracy().to(device)\n",
|
||||
"# acc_fn"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "a-v-7f0op0tG"
|
||||
},
|
||||
"execution_count": 18,
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# Prepare device agnostic code\n",
|
||||
"# device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
|
||||
"\n",
|
||||
"# Create model by subclassing nn.Module\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Instantiate model and send it to device\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "DB3u3ldumapf"
|
||||
},
|
||||
"execution_count": 19,
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# Setup data to be device agnostic\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Print out first 10 untrained model outputs (forward pass)\n",
|
||||
"print(\"Logits:\")\n",
|
||||
"## Your code here ##\n",
|
||||
"\n",
|
||||
"print(\"Pred probs:\")\n",
|
||||
"## Your code here ##\n",
|
||||
"\n",
|
||||
"print(\"Pred labels:\")\n",
|
||||
"## Your code here ##"
|
||||
],
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
},
|
||||
"id": "QE7XWSSunMTS",
|
||||
"outputId": "00b31909-87c9-41e3-9dbb-fb4c4bd3aabd"
|
||||
},
|
||||
"execution_count": 20,
|
||||
"outputs": [
|
||||
{
|
||||
"output_type": "stream",
|
||||
"name": "stdout",
|
||||
"text": [
|
||||
"Logits:\n",
|
||||
"Pred probs:\n",
|
||||
"Pred labels:\n"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# Setup loss function and optimizer\n",
|
||||
"# loss_fn =\n",
|
||||
"# optimizer = "
|
||||
],
|
||||
"metadata": {
|
||||
"id": "54EqLRKLo0AW"
|
||||
},
|
||||
"execution_count": 21,
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# Build a training loop for the model\n",
|
||||
"\n",
|
||||
"# Loop over data\n",
|
||||
"\n",
|
||||
"\n",
|
||||
" ## Training\n",
|
||||
" \n",
|
||||
" # 1. Forward pass\n",
|
||||
" \n",
|
||||
"\n",
|
||||
" # 2. Calculate the loss\n",
|
||||
" \n",
|
||||
" \n",
|
||||
" # 3. Optimizer zero grad\n",
|
||||
" \n",
|
||||
"\n",
|
||||
" # 4. Loss backward\n",
|
||||
" \n",
|
||||
"\n",
|
||||
" # 5. Optimizer step\n",
|
||||
" \n",
|
||||
"\n",
|
||||
" ## Testing\n",
|
||||
" \n",
|
||||
"\n",
|
||||
" # 1. Forward pass\n",
|
||||
" \n",
|
||||
" # 2. Caculate loss and acc\n",
|
||||
" \n",
|
||||
" # Print out what's happening every 100 epochs\n",
|
||||
" "
|
||||
],
|
||||
"metadata": {
|
||||
"id": "vIlExkUHnmxi"
|
||||
},
|
||||
"execution_count": 22,
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"# Plot decision boundaries for training and test sets\n"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "JrwVRbaE0keT"
|
||||
},
|
||||
"execution_count": 23,
|
||||
"outputs": []
|
||||
}
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user