{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Deep Learning Models -- A collection of various deep learning architectures, models, and tips for TensorFlow and PyTorch in Jupyter Notebooks.\n", "- Author: Sebastian Raschka\n", "- GitHub Repository: https://github.com/rasbt/deeplearning-models" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Sebastian Raschka \n", "\n", "CPython 3.6.8\n", "IPython 7.2.0\n", "\n", "torch 1.0.0\n" ] } ], "source": [ "%load_ext watermark\n", "%watermark -a 'Sebastian Raschka' -v -p torch" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Runs on CPU or GPU (if available)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Model Zoo -- Multilayer Perceptron" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Imports" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "import time\n", "import numpy as np\n", "from torchvision import datasets\n", "from torchvision import transforms\n", "from torch.utils.data import DataLoader\n", "import torch.nn.functional as F\n", "import torch\n", "\n", "\n", "if torch.cuda.is_available():\n", " torch.backends.cudnn.deterministic = True" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Settings and Dataset" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Image batch dimensions: torch.Size([64, 1, 28, 28])\n", "Image label dimensions: torch.Size([64])\n" ] } ], "source": [ "##########################\n", "### SETTINGS\n", "##########################\n", "\n", "# Device\n", "device = torch.device(\"cuda:3\" if torch.cuda.is_available() else \"cpu\")\n", "\n", "# Hyperparameters\n", "random_seed = 1\n", "learning_rate = 0.1\n", "num_epochs = 10\n", "batch_size = 64\n", "\n", "# Architecture\n", "num_features = 784\n", "num_hidden_1 = 128\n", "num_hidden_2 = 256\n", "num_classes = 10\n", "\n", "\n", "##########################\n", "### MNIST DATASET\n", "##########################\n", "\n", "# Note transforms.ToTensor() scales input images\n", "# to 0-1 range\n", "train_dataset = datasets.MNIST(root='data', \n", " train=True, \n", " transform=transforms.ToTensor(),\n", " download=True)\n", "\n", "test_dataset = datasets.MNIST(root='data', \n", " train=False, \n", " transform=transforms.ToTensor())\n", "\n", "\n", "train_loader = DataLoader(dataset=train_dataset, \n", " batch_size=batch_size, \n", " shuffle=True)\n", "\n", "test_loader = DataLoader(dataset=test_dataset, \n", " batch_size=batch_size, \n", " shuffle=False)\n", "\n", "# Checking the dataset\n", "for images, labels in train_loader: \n", " print('Image batch dimensions:', images.shape)\n", " print('Image label dimensions:', labels.shape)\n", " break" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "##########################\n", "### MODEL\n", "##########################\n", "\n", "class MultilayerPerceptron(torch.nn.Module):\n", "\n", " def __init__(self, num_features, num_classes):\n", " super(MultilayerPerceptron, self).__init__()\n", " \n", " ### 1st hidden layer\n", " self.linear_1 = torch.nn.Linear(num_features, num_hidden_1)\n", " # The following two lines are not necessary, \n", " # but used here to demonstrate how to access the weights\n", " # and use a different weight initialization.\n", " # By default, PyTorch uses Xavier/Glorot initialization, which\n", " # should usually be preferred.\n", " self.linear_1.weight.detach().normal_(0.0, 0.1)\n", " self.linear_1.bias.detach().zero_()\n", " \n", " ### 2nd hidden layer\n", " self.linear_2 = torch.nn.Linear(num_hidden_1, num_hidden_2)\n", " self.linear_2.weight.detach().normal_(0.0, 0.1)\n", " self.linear_2.bias.detach().zero_()\n", " \n", " ### Output layer\n", " self.linear_out = torch.nn.Linear(num_hidden_2, num_classes)\n", " self.linear_out.weight.detach().normal_(0.0, 0.1)\n", " self.linear_out.bias.detach().zero_()\n", " \n", " def forward(self, x):\n", " out = self.linear_1(x)\n", " out = F.relu(out)\n", " out = self.linear_2(out)\n", " out = F.relu(out)\n", " logits = self.linear_out(out)\n", " probas = F.log_softmax(logits, dim=1)\n", " return logits, probas\n", "\n", " \n", "torch.manual_seed(random_seed)\n", "model = MultilayerPerceptron(num_features=num_features,\n", " num_classes=num_classes)\n", "\n", "model = model.to(device)\n", "\n", "optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate) " ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Epoch: 001/010 | Batch 000/938 | Cost: 2.4231\n", "Epoch: 001/010 | Batch 050/938 | Cost: 0.7213\n", "Epoch: 001/010 | Batch 100/938 | Cost: 0.3137\n", "Epoch: 001/010 | Batch 150/938 | Cost: 0.4774\n", "Epoch: 001/010 | Batch 200/938 | Cost: 0.3311\n", "Epoch: 001/010 | Batch 250/938 | Cost: 0.3082\n", "Epoch: 001/010 | Batch 300/938 | Cost: 0.3940\n", "Epoch: 001/010 | Batch 350/938 | Cost: 0.2292\n", "Epoch: 001/010 | Batch 400/938 | Cost: 0.0837\n", "Epoch: 001/010 | Batch 450/938 | Cost: 0.2238\n", "Epoch: 001/010 | Batch 500/938 | Cost: 0.2501\n", "Epoch: 001/010 | Batch 550/938 | Cost: 0.1543\n", "Epoch: 001/010 | Batch 600/938 | Cost: 0.2353\n", "Epoch: 001/010 | Batch 650/938 | Cost: 0.4138\n", "Epoch: 001/010 | Batch 700/938 | Cost: 0.2955\n", "Epoch: 001/010 | Batch 750/938 | Cost: 0.3486\n", "Epoch: 001/010 | Batch 800/938 | Cost: 0.1391\n", "Epoch: 001/010 | Batch 850/938 | Cost: 0.0675\n", "Epoch: 001/010 | Batch 900/938 | Cost: 0.2827\n", "Epoch: 001/010 training accuracy: 94.90%\n", "Time elapsed: 0.22 min\n", "Epoch: 002/010 | Batch 000/938 | Cost: 0.3237\n", "Epoch: 002/010 | Batch 050/938 | Cost: 0.2792\n", "Epoch: 002/010 | Batch 100/938 | Cost: 0.0915\n", "Epoch: 002/010 | Batch 150/938 | Cost: 0.2269\n", "Epoch: 002/010 | Batch 200/938 | Cost: 0.2248\n", "Epoch: 002/010 | Batch 250/938 | Cost: 0.1607\n", "Epoch: 002/010 | Batch 300/938 | Cost: 0.0551\n", "Epoch: 002/010 | Batch 350/938 | Cost: 0.2369\n", "Epoch: 002/010 | Batch 400/938 | Cost: 0.0538\n", "Epoch: 002/010 | Batch 450/938 | Cost: 0.0951\n", "Epoch: 002/010 | Batch 500/938 | Cost: 0.2423\n", "Epoch: 002/010 | Batch 550/938 | Cost: 0.2082\n", "Epoch: 002/010 | Batch 600/938 | Cost: 0.1623\n", "Epoch: 002/010 | Batch 650/938 | Cost: 0.1743\n", "Epoch: 002/010 | Batch 700/938 | Cost: 0.1987\n", "Epoch: 002/010 | Batch 750/938 | Cost: 0.0871\n", "Epoch: 002/010 | Batch 800/938 | Cost: 0.1662\n", "Epoch: 002/010 | Batch 850/938 | Cost: 0.1087\n", "Epoch: 002/010 | Batch 900/938 | Cost: 0.1574\n", "Epoch: 002/010 training accuracy: 96.62%\n", "Time elapsed: 0.45 min\n", "Epoch: 003/010 | Batch 000/938 | Cost: 0.1088\n", "Epoch: 003/010 | Batch 050/938 | Cost: 0.0994\n", "Epoch: 003/010 | Batch 100/938 | Cost: 0.0771\n", "Epoch: 003/010 | Batch 150/938 | Cost: 0.1926\n", "Epoch: 003/010 | Batch 200/938 | Cost: 0.1231\n", "Epoch: 003/010 | Batch 250/938 | Cost: 0.2532\n", "Epoch: 003/010 | Batch 300/938 | Cost: 0.0637\n", "Epoch: 003/010 | Batch 350/938 | Cost: 0.1193\n", "Epoch: 003/010 | Batch 400/938 | Cost: 0.0839\n", "Epoch: 003/010 | Batch 450/938 | Cost: 0.0830\n", "Epoch: 003/010 | Batch 500/938 | Cost: 0.0689\n", "Epoch: 003/010 | Batch 550/938 | Cost: 0.0504\n", "Epoch: 003/010 | Batch 600/938 | Cost: 0.1999\n", "Epoch: 003/010 | Batch 650/938 | Cost: 0.1190\n", "Epoch: 003/010 | Batch 700/938 | Cost: 0.2022\n", "Epoch: 003/010 | Batch 750/938 | Cost: 0.0598\n", "Epoch: 003/010 | Batch 800/938 | Cost: 0.0216\n", "Epoch: 003/010 | Batch 850/938 | Cost: 0.0174\n", "Epoch: 003/010 | Batch 900/938 | Cost: 0.0660\n", "Epoch: 003/010 training accuracy: 97.70%\n", "Time elapsed: 0.67 min\n", "Epoch: 004/010 | Batch 000/938 | Cost: 0.0067\n", "Epoch: 004/010 | Batch 050/938 | Cost: 0.0344\n", "Epoch: 004/010 | Batch 100/938 | Cost: 0.1624\n", "Epoch: 004/010 | Batch 150/938 | Cost: 0.0572\n", "Epoch: 004/010 | Batch 200/938 | Cost: 0.0306\n", "Epoch: 004/010 | Batch 250/938 | Cost: 0.1564\n", "Epoch: 004/010 | Batch 300/938 | Cost: 0.2233\n", "Epoch: 004/010 | Batch 350/938 | Cost: 0.0229\n", "Epoch: 004/010 | Batch 400/938 | Cost: 0.1174\n", "Epoch: 004/010 | Batch 450/938 | Cost: 0.1853\n", "Epoch: 004/010 | Batch 500/938 | Cost: 0.1418\n", "Epoch: 004/010 | Batch 550/938 | Cost: 0.1071\n", "Epoch: 004/010 | Batch 600/938 | Cost: 0.0354\n", "Epoch: 004/010 | Batch 650/938 | Cost: 0.0487\n", "Epoch: 004/010 | Batch 700/938 | Cost: 0.1886\n", "Epoch: 004/010 | Batch 750/938 | Cost: 0.1568\n", "Epoch: 004/010 | Batch 800/938 | Cost: 0.0702\n", "Epoch: 004/010 | Batch 850/938 | Cost: 0.0533\n", "Epoch: 004/010 | Batch 900/938 | Cost: 0.1500\n", "Epoch: 004/010 training accuracy: 98.01%\n", "Time elapsed: 0.89 min\n", "Epoch: 005/010 | Batch 000/938 | Cost: 0.0225\n", "Epoch: 005/010 | Batch 050/938 | Cost: 0.0168\n", "Epoch: 005/010 | Batch 100/938 | Cost: 0.1133\n", "Epoch: 005/010 | Batch 150/938 | Cost: 0.0691\n", "Epoch: 005/010 | Batch 200/938 | Cost: 0.0413\n", "Epoch: 005/010 | Batch 250/938 | Cost: 0.0840\n", "Epoch: 005/010 | Batch 300/938 | Cost: 0.0697\n", "Epoch: 005/010 | Batch 350/938 | Cost: 0.0901\n", "Epoch: 005/010 | Batch 400/938 | Cost: 0.0370\n", "Epoch: 005/010 | Batch 450/938 | Cost: 0.0514\n", "Epoch: 005/010 | Batch 500/938 | Cost: 0.1403\n", "Epoch: 005/010 | Batch 550/938 | Cost: 0.1164\n", "Epoch: 005/010 | Batch 600/938 | Cost: 0.0624\n", "Epoch: 005/010 | Batch 650/938 | Cost: 0.0280\n", "Epoch: 005/010 | Batch 700/938 | Cost: 0.0555\n", "Epoch: 005/010 | Batch 750/938 | Cost: 0.0432\n", "Epoch: 005/010 | Batch 800/938 | Cost: 0.0434\n", "Epoch: 005/010 | Batch 850/938 | Cost: 0.1074\n", "Epoch: 005/010 | Batch 900/938 | Cost: 0.0353\n", "Epoch: 005/010 training accuracy: 98.56%\n", "Time elapsed: 1.12 min\n", "Epoch: 006/010 | Batch 000/938 | Cost: 0.1073\n", "Epoch: 006/010 | Batch 050/938 | Cost: 0.0901\n", "Epoch: 006/010 | Batch 100/938 | Cost: 0.0736\n", "Epoch: 006/010 | Batch 150/938 | Cost: 0.0290\n", "Epoch: 006/010 | Batch 200/938 | Cost: 0.0399\n", "Epoch: 006/010 | Batch 250/938 | Cost: 0.0720\n", "Epoch: 006/010 | Batch 300/938 | Cost: 0.0863\n", "Epoch: 006/010 | Batch 350/938 | Cost: 0.0629\n", "Epoch: 006/010 | Batch 400/938 | Cost: 0.1095\n", "Epoch: 006/010 | Batch 450/938 | Cost: 0.0531\n", "Epoch: 006/010 | Batch 500/938 | Cost: 0.0680\n", "Epoch: 006/010 | Batch 550/938 | Cost: 0.1777\n", "Epoch: 006/010 | Batch 600/938 | Cost: 0.0525\n", "Epoch: 006/010 | Batch 650/938 | Cost: 0.0364\n", "Epoch: 006/010 | Batch 700/938 | Cost: 0.0836\n", "Epoch: 006/010 | Batch 750/938 | Cost: 0.1251\n", "Epoch: 006/010 | Batch 800/938 | Cost: 0.0638\n", "Epoch: 006/010 | Batch 850/938 | Cost: 0.0725\n", "Epoch: 006/010 | Batch 900/938 | Cost: 0.1785\n", "Epoch: 006/010 training accuracy: 98.88%\n", "Time elapsed: 1.34 min\n", "Epoch: 007/010 | Batch 000/938 | Cost: 0.0043\n", "Epoch: 007/010 | Batch 050/938 | Cost: 0.0928\n", "Epoch: 007/010 | Batch 100/938 | Cost: 0.0375\n", "Epoch: 007/010 | Batch 150/938 | Cost: 0.1094\n", "Epoch: 007/010 | Batch 200/938 | Cost: 0.0237\n", "Epoch: 007/010 | Batch 250/938 | Cost: 0.0398\n", "Epoch: 007/010 | Batch 300/938 | Cost: 0.0592\n", "Epoch: 007/010 | Batch 350/938 | Cost: 0.0340\n", "Epoch: 007/010 | Batch 400/938 | Cost: 0.0255\n", "Epoch: 007/010 | Batch 450/938 | Cost: 0.0472\n", "Epoch: 007/010 | Batch 500/938 | Cost: 0.0172\n", "Epoch: 007/010 | Batch 550/938 | Cost: 0.0860\n", "Epoch: 007/010 | Batch 600/938 | Cost: 0.1124\n", "Epoch: 007/010 | Batch 650/938 | Cost: 0.0783\n", "Epoch: 007/010 | Batch 700/938 | Cost: 0.0307\n", "Epoch: 007/010 | Batch 750/938 | Cost: 0.0686\n", "Epoch: 007/010 | Batch 800/938 | Cost: 0.0128\n", "Epoch: 007/010 | Batch 850/938 | Cost: 0.0684\n", "Epoch: 007/010 | Batch 900/938 | Cost: 0.0541\n", "Epoch: 007/010 training accuracy: 98.98%\n", "Time elapsed: 1.56 min\n", "Epoch: 008/010 | Batch 000/938 | Cost: 0.0237\n", "Epoch: 008/010 | Batch 050/938 | Cost: 0.0167\n", "Epoch: 008/010 | Batch 100/938 | Cost: 0.0446\n", "Epoch: 008/010 | Batch 150/938 | Cost: 0.0324\n", "Epoch: 008/010 | Batch 200/938 | Cost: 0.0068\n", "Epoch: 008/010 | Batch 250/938 | Cost: 0.0529\n", "Epoch: 008/010 | Batch 300/938 | Cost: 0.0278\n", "Epoch: 008/010 | Batch 350/938 | Cost: 0.0289\n", "Epoch: 008/010 | Batch 400/938 | Cost: 0.0099\n", "Epoch: 008/010 | Batch 450/938 | Cost: 0.0052\n", "Epoch: 008/010 | Batch 500/938 | Cost: 0.0116\n", "Epoch: 008/010 | Batch 550/938 | Cost: 0.0049\n", "Epoch: 008/010 | Batch 600/938 | Cost: 0.0214\n", "Epoch: 008/010 | Batch 650/938 | Cost: 0.0397\n", "Epoch: 008/010 | Batch 700/938 | Cost: 0.0494\n", "Epoch: 008/010 | Batch 750/938 | Cost: 0.0166\n", "Epoch: 008/010 | Batch 800/938 | Cost: 0.0482\n", "Epoch: 008/010 | Batch 850/938 | Cost: 0.0049\n", "Epoch: 008/010 | Batch 900/938 | Cost: 0.0482\n", "Epoch: 008/010 training accuracy: 99.25%\n", "Time elapsed: 1.78 min\n", "Epoch: 009/010 | Batch 000/938 | Cost: 0.0367\n", "Epoch: 009/010 | Batch 050/938 | Cost: 0.0624\n", "Epoch: 009/010 | Batch 100/938 | Cost: 0.0095\n", "Epoch: 009/010 | Batch 150/938 | Cost: 0.0166\n", "Epoch: 009/010 | Batch 200/938 | Cost: 0.0764\n", "Epoch: 009/010 | Batch 250/938 | Cost: 0.0056\n", "Epoch: 009/010 | Batch 300/938 | Cost: 0.0066\n", "Epoch: 009/010 | Batch 350/938 | Cost: 0.0060\n", "Epoch: 009/010 | Batch 400/938 | Cost: 0.0583\n", "Epoch: 009/010 | Batch 450/938 | Cost: 0.0170\n", "Epoch: 009/010 | Batch 500/938 | Cost: 0.0252\n", "Epoch: 009/010 | Batch 550/938 | Cost: 0.0140\n", "Epoch: 009/010 | Batch 600/938 | Cost: 0.0911\n", "Epoch: 009/010 | Batch 650/938 | Cost: 0.0469\n", "Epoch: 009/010 | Batch 700/938 | Cost: 0.0146\n", "Epoch: 009/010 | Batch 750/938 | Cost: 0.0573\n", "Epoch: 009/010 | Batch 800/938 | Cost: 0.0067\n", "Epoch: 009/010 | Batch 850/938 | Cost: 0.1513\n", "Epoch: 009/010 | Batch 900/938 | Cost: 0.0029\n", "Epoch: 009/010 training accuracy: 99.30%\n", "Time elapsed: 2.01 min\n", "Epoch: 010/010 | Batch 000/938 | Cost: 0.0207\n", "Epoch: 010/010 | Batch 050/938 | Cost: 0.0154\n", "Epoch: 010/010 | Batch 100/938 | Cost: 0.0135\n", "Epoch: 010/010 | Batch 150/938 | Cost: 0.0122\n", "Epoch: 010/010 | Batch 200/938 | Cost: 0.0354\n", "Epoch: 010/010 | Batch 250/938 | Cost: 0.0217\n", "Epoch: 010/010 | Batch 300/938 | Cost: 0.0102\n", "Epoch: 010/010 | Batch 350/938 | Cost: 0.0189\n", "Epoch: 010/010 | Batch 400/938 | Cost: 0.0015\n", "Epoch: 010/010 | Batch 450/938 | Cost: 0.0101\n", "Epoch: 010/010 | Batch 500/938 | Cost: 0.0950\n", "Epoch: 010/010 | Batch 550/938 | Cost: 0.0130\n", "Epoch: 010/010 | Batch 600/938 | Cost: 0.0328\n", "Epoch: 010/010 | Batch 650/938 | Cost: 0.0506\n", "Epoch: 010/010 | Batch 700/938 | Cost: 0.0182\n", "Epoch: 010/010 | Batch 750/938 | Cost: 0.0091\n", "Epoch: 010/010 | Batch 800/938 | Cost: 0.0075\n", "Epoch: 010/010 | Batch 850/938 | Cost: 0.0092\n", "Epoch: 010/010 | Batch 900/938 | Cost: 0.0413\n", "Epoch: 010/010 training accuracy: 99.00%\n", "Time elapsed: 2.23 min\n", "Total Training Time: 2.23 min\n" ] } ], "source": [ "def compute_accuracy(net, data_loader):\n", " net.eval()\n", " correct_pred, num_examples = 0, 0\n", " with torch.no_grad():\n", " for features, targets in data_loader:\n", " features = features.view(-1, 28*28).to(device)\n", " targets = targets.to(device)\n", " logits, probas = net(features)\n", " _, predicted_labels = torch.max(probas, 1)\n", " num_examples += targets.size(0)\n", " correct_pred += (predicted_labels == targets).sum()\n", " return correct_pred.float()/num_examples * 100\n", " \n", "\n", "start_time = time.time()\n", "for epoch in range(num_epochs):\n", " model.train()\n", " for batch_idx, (features, targets) in enumerate(train_loader):\n", " \n", " features = features.view(-1, 28*28).to(device)\n", " targets = targets.to(device)\n", " \n", " ### FORWARD AND BACK PROP\n", " logits, probas = model(features)\n", " cost = F.cross_entropy(logits, targets)\n", " optimizer.zero_grad()\n", " \n", " cost.backward()\n", " \n", " ### UPDATE MODEL PARAMETERS\n", " optimizer.step()\n", " \n", " ### LOGGING\n", " if not batch_idx % 50:\n", " print ('Epoch: %03d/%03d | Batch %03d/%03d | Cost: %.4f' \n", " %(epoch+1, num_epochs, batch_idx, \n", " len(train_loader), cost))\n", "\n", " with torch.set_grad_enabled(False):\n", " print('Epoch: %03d/%03d training accuracy: %.2f%%' % (\n", " epoch+1, num_epochs, \n", " compute_accuracy(model, train_loader)))\n", " \n", " print('Time elapsed: %.2f min' % ((time.time() - start_time)/60))\n", " \n", "print('Total Training Time: %.2f min' % ((time.time() - start_time)/60))" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Test accuracy: 97.54%\n" ] } ], "source": [ "print('Test accuracy: %.2f%%' % (compute_accuracy(model, test_loader)))" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "numpy 1.15.4\n", "torch 1.0.0\n", "\n" ] } ], "source": [ "%watermark -iv" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "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.7.1" }, "toc": { "nav_menu": {}, "number_sections": true, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": {}, "toc_section_display": true, "toc_window_display": false } }, "nbformat": 4, "nbformat_minor": 2 }