{"backend_state":"running","connection_file":"/projects/800fec81-81db-4589-8df3-d839b1d21871/.local/share/jupyter/runtime/kernel-06bdf45a-6d6c-4ca4-a462-f80adeba05ab.json","kernel":"python3-ubuntu","kernel_error":"","kernel_state":"idle","kernel_usage":{"cpu":0,"memory":0},"metadata":{"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.9.6"}},"trust":true,"type":"settings"} {"cell_type":"code","end":1631142385589,"exec_count":1,"id":"d98d2f","input":"from pathlib import Path\nimport requests\n\nDATA_PATH = Path(\"data\")\nPATH = DATA_PATH / \"mnist\"\n\nPATH.mkdir(parents=True, exist_ok=True)\n\nURL = \"https://github.com/pytorch/tutorials/raw/master/_static/\"\nFILENAME = \"mnist.pkl.gz\"\n\nif not (PATH / FILENAME).exists():\n content = requests.get(URL + FILENAME).content\n (PATH / FILENAME).open(\"wb\").write(content)","kernel":"python3-ubuntu","metadata":{"jupyter":{}},"pos":3,"start":1631142385566,"state":"done","type":"cell"} {"cell_type":"code","end":1631142391724,"exec_count":2,"id":"ea520d","input":"import pickle\nimport gzip\n\nwith gzip.open((PATH / FILENAME).as_posix(), \"rb\") as f:\n ((x_train, y_train), (x_valid, y_valid), _) = pickle.load(f, encoding=\"latin-1\")","kernel":"python3-ubuntu","metadata":{"jupyter":{}},"pos":5,"start":1631142391204,"state":"done","type":"cell"} {"cell_type":"code","end":1631142394859,"exec_count":3,"id":"d0427c","input":"print(x_valid)","kernel":"python3-ubuntu","output":{"0":{"name":"stdout","text":"[[0. 0. 0. ... 0. 0. 0.]\n [0. 0. 0. ... 0. 0. 0.]\n [0. 0. 0. ... 0. 0. 0.]\n ...\n [0. 0. 0. ... 0. 0. 0.]\n [0. 0. 0. ... 0. 0. 0.]\n [0. 0. 0. ... 0. 0. 0.]]\n"}},"pos":6,"start":1631142394853,"state":"done","type":"cell"} {"cell_type":"code","end":1631142400094,"exec_count":4,"id":"1334ae","input":"from matplotlib import pyplot\nimport numpy as np\n\npyplot.imshow(x_train[0].reshape((28, 28)), cmap=\"gray\")\nprint(x_train.shape)","kernel":"python3-ubuntu","metadata":{"jupyter":{}},"output":{"0":{"name":"stdout","text":"(50000, 784)\n"},"1":{"data":{"image/png":"b47b60f61738c85903c970a7f1240828ce556776","text/plain":"
"},"metadata":{"image/png":{"height":411,"width":414},"needs_background":"light"}}},"pos":8,"start":1631142399901,"state":"done","type":"cell"} {"cell_type":"code","end":1631142407955,"exec_count":5,"id":"06a83f","input":"import torch\n\nx_train, y_train, x_valid, y_valid = map(\n torch.tensor, (x_train, y_train, x_valid, y_valid)\n)\nn, c = x_train.shape\nprint(x_train, y_train)\nprint(x_train.shape)\nprint(y_train.min(), y_train.max())","kernel":"python3-ubuntu","metadata":{"jupyter":{}},"output":{"0":{"name":"stdout","text":"tensor([[0., 0., 0., ..., 0., 0., 0.],\n [0., 0., 0., ..., 0., 0., 0.],\n [0., 0., 0., ..., 0., 0., 0.],\n ...,\n [0., 0., 0., ..., 0., 0., 0.],\n [0., 0., 0., ..., 0., 0., 0.],\n [0., 0., 0., ..., 0., 0., 0.]]) tensor([5, 0, 4, ..., 8, 4, 8])\ntorch.Size([50000, 784])\ntensor(0) tensor(9)\n"}},"pos":10,"start":1631142407778,"state":"done","type":"cell"} {"cell_type":"code","id":"04818f","input":"class Mnist_Logistic(nn.Module):\n def __init__(self):\n super().__init__()\n self.lin = nn.Linear(784, 10)\n\n def forward(self, xb):\n return self.lin(xb)","metadata":{"jupyter":{"outputs_hidden":false}},"pos":44,"state":"done","type":"cell"} {"cell_type":"code","id":"0baf97","input":"print(loss_func(model(xb), yb))","metadata":{"jupyter":{"outputs_hidden":false}},"pos":38,"state":"done","type":"cell"} {"cell_type":"code","id":"1112e9","input":"def log_softmax(x):\n return x - x.exp().sum(-1).log().unsqueeze(-1)\n\ndef model(xb):\n return log_softmax(xb @ weights + bias)","metadata":{"jupyter":{"outputs_hidden":false}},"pos":14,"state":"done","type":"cell"} {"cell_type":"code","id":"278747","input":"fit(epochs, model, loss_func, opt, train_dl, valid_dl)","metadata":{"jupyter":{"outputs_hidden":false}},"pos":88,"state":"done","type":"cell"} {"cell_type":"code","id":"28c6eb","input":"model = nn.Sequential(\n Lambda(preprocess),\n nn.Conv2d(1, 16, kernel_size=3, stride=2, padding=1),\n nn.ReLU(),\n nn.Conv2d(16, 16, kernel_size=3, stride=2, padding=1),\n nn.ReLU(),\n nn.Conv2d(16, 10, kernel_size=3, stride=2, padding=1),\n nn.ReLU(),\n nn.AvgPool2d(4),\n Lambda(lambda x: x.view(x.size(0), -1)),\n)\n\nopt = optim.SGD(model.parameters(), lr=lr, momentum=0.9)\n\nfit(epochs, model, loss_func, opt, train_dl, valid_dl)","metadata":{"jupyter":{"outputs_hidden":false}},"pos":82,"state":"done","type":"cell"} {"cell_type":"code","id":"2bd101","input":"%matplotlib inline","metadata":{"jupyter":{"outputs_hidden":false}},"pos":0,"state":"done","type":"cell"} {"cell_type":"code","id":"33c506","input":"def accuracy(out, yb):\n preds = torch.argmax(out, dim=1)\n return (preds == yb).float().mean()","metadata":{"jupyter":{"outputs_hidden":false}},"pos":22,"state":"done","type":"cell"} {"cell_type":"code","id":"3622f3","input":"print(accuracy(preds, yb))","metadata":{"jupyter":{"outputs_hidden":false}},"pos":24,"state":"done","type":"cell"} {"cell_type":"code","id":"3ad235","input":"model = Mnist_CNN()\nopt = optim.SGD(model.parameters(), lr=lr, momentum=0.9)\n\nfit(epochs, model, loss_func, opt, train_dl, valid_dl)","metadata":{"jupyter":{"outputs_hidden":false}},"pos":78,"state":"done","type":"cell"} {"cell_type":"code","id":"3b235d","input":"from IPython.core.debugger import set_trace\n\nlr = 0.5 # learning rate\nepochs = 2 # how many epochs to train for\n\nfor epoch in range(epochs):\n for i in range((n - 1) // bs + 1):\n # set_trace()\n start_i = i * bs\n end_i = start_i + bs\n xb = x_train[start_i:end_i]\n yb = y_train[start_i:end_i]\n pred = model(xb)\n loss = loss_func(pred, yb)\n\n loss.backward()\n with torch.no_grad():\n weights -= weights.grad * lr\n bias -= bias.grad * lr\n weights.grad.zero_()\n bias.grad.zero_()","metadata":{"jupyter":{"outputs_hidden":false}},"pos":26,"state":"done","type":"cell"} {"cell_type":"code","id":"40bcfc","input":"import numpy as np\n\ndef fit(epochs, model, loss_func, opt, train_dl, valid_dl):\n for epoch in range(epochs):\n model.train()\n for xb, yb in train_dl:\n loss_batch(model, loss_func, xb, yb, opt)\n\n model.eval()\n with torch.no_grad():\n losses, nums = zip(\n *[loss_batch(model, loss_func, xb, yb) for xb, yb in valid_dl]\n )\n val_loss = np.sum(np.multiply(losses, nums)) / np.sum(nums)\n\n print(epoch, val_loss)","metadata":{"jupyter":{"outputs_hidden":false}},"pos":70,"state":"done","type":"cell"} {"cell_type":"code","id":"441030","input":"def loss_batch(model, loss_func, xb, yb, opt=None):\n loss = loss_func(model(xb), yb)\n\n if opt is not None:\n loss.backward()\n opt.step()\n opt.zero_grad()\n\n return loss.item(), len(xb)","metadata":{"jupyter":{"outputs_hidden":false}},"pos":68,"state":"done","type":"cell"} {"cell_type":"code","id":"450e1d","input":"print(loss_func(model(xb), yb), accuracy(model(xb), yb))","metadata":{"jupyter":{"outputs_hidden":false}},"pos":28,"state":"done","type":"cell"} {"cell_type":"code","id":"47c4b8","input":"fit(epochs, model, loss_func, opt, train_dl, valid_dl)","metadata":{"jupyter":{"outputs_hidden":false}},"pos":98,"state":"done","type":"cell"} {"cell_type":"code","id":"48c137","input":"print(loss_func(model(xb), yb), accuracy(model(xb), yb))","metadata":{"jupyter":{"outputs_hidden":false}},"pos":32,"state":"done","type":"cell"} {"cell_type":"code","id":"5710c8","input":"def nll(input, target):\n return -input[range(target.shape[0]), target].mean()\n\nloss_func = nll","metadata":{"jupyter":{"outputs_hidden":false}},"pos":18,"state":"done","type":"cell"} {"cell_type":"code","id":"5a7882","input":"fit()\n\nprint(loss_func(model(xb), yb))","metadata":{"jupyter":{"outputs_hidden":false}},"pos":48,"state":"done","type":"cell"} {"cell_type":"code","id":"5aa7dc","input":"print(loss_func(model(xb), yb))","metadata":{"jupyter":{"outputs_hidden":false}},"pos":42,"state":"done","type":"cell"} {"cell_type":"code","id":"5c1249","input":"model, opt = get_model()\n\nfor epoch in range(epochs):\n for i in range((n - 1) // bs + 1):\n xb, yb = train_ds[i * bs: i * bs + bs]\n pred = model(xb)\n loss = loss_func(pred, yb)\n\n loss.backward()\n opt.step()\n opt.zero_grad()\n\nprint(loss_func(model(xb), yb))","metadata":{"jupyter":{"outputs_hidden":false}},"pos":58,"state":"done","type":"cell"} {"cell_type":"code","id":"638429","input":"model, opt = get_model()\n\nfor epoch in range(epochs):\n model.train()\n for xb, yb in train_dl:\n pred = model(xb)\n loss = loss_func(pred, yb)\n\n loss.backward()\n opt.step()\n opt.zero_grad()\n\n model.eval()\n with torch.no_grad():\n valid_loss = sum(loss_func(model(xb), yb) for xb, yb in valid_dl)\n\n print(epoch, valid_loss / len(valid_dl))","metadata":{"jupyter":{"outputs_hidden":false}},"pos":66,"state":"done","type":"cell"} {"cell_type":"code","id":"63e25b","input":"def preprocess(x, y):\n return x.view(-1, 1, 28, 28).to(dev), y.to(dev)\n\n\ntrain_dl, valid_dl = get_data(train_ds, valid_ds, bs)\ntrain_dl = WrappedDataLoader(train_dl, preprocess)\nvalid_dl = WrappedDataLoader(valid_dl, preprocess)","metadata":{"jupyter":{"outputs_hidden":false}},"pos":94,"state":"done","type":"cell"} {"cell_type":"code","id":"684c65","input":"def get_model():\n model = Mnist_Logistic()\n return model, optim.SGD(model.parameters(), lr=lr)\n\nmodel, opt = get_model()\nprint(loss_func(model(xb), yb))\n\nfor epoch in range(epochs):\n for i in range((n - 1) // bs + 1):\n start_i = i * bs\n end_i = start_i + bs\n xb = x_train[start_i:end_i]\n yb = y_train[start_i:end_i]\n pred = model(xb)\n loss = loss_func(pred, yb)\n\n loss.backward()\n opt.step()\n opt.zero_grad()\n\nprint(loss_func(model(xb), yb))","metadata":{"jupyter":{"outputs_hidden":false}},"pos":52,"state":"done","type":"cell"} {"cell_type":"code","id":"7f399f","input":"class Lambda(nn.Module):\n def __init__(self, func):\n super().__init__()\n self.func = func\n\n def forward(self, x):\n return self.func(x)\n\n\ndef preprocess(x):\n return x.view(-1, 1, 28, 28)","metadata":{"jupyter":{"outputs_hidden":false}},"pos":80,"state":"done","type":"cell"} {"cell_type":"code","id":"7f80d5","input":"model = nn.Sequential(\n nn.Conv2d(1, 16, kernel_size=3, stride=2, padding=1),\n nn.ReLU(),\n nn.Conv2d(16, 16, kernel_size=3, stride=2, padding=1),\n nn.ReLU(),\n nn.Conv2d(16, 10, kernel_size=3, stride=2, padding=1),\n nn.ReLU(),\n nn.AdaptiveAvgPool2d(1),\n Lambda(lambda x: x.view(x.size(0), -1)),\n)\n\nopt = optim.SGD(model.parameters(), lr=lr, momentum=0.9)","metadata":{"jupyter":{"outputs_hidden":false}},"pos":86,"state":"done","type":"cell"} {"cell_type":"code","id":"82e1af","input":"from torch import nn\n\nclass Mnist_Logistic(nn.Module):\n def __init__(self):\n super().__init__()\n self.weights = nn.Parameter(torch.randn(784, 10) / math.sqrt(784))\n self.bias = nn.Parameter(torch.zeros(10))\n\n def forward(self, xb):\n return xb @ self.weights + self.bias","metadata":{"jupyter":{"outputs_hidden":false}},"pos":34,"state":"done","type":"cell"} {"cell_type":"code","id":"86e2dc","input":"train_dl, valid_dl = get_data(train_ds, valid_ds, bs)\nmodel, opt = get_model()\nfit(epochs, model, loss_func, opt, train_dl, valid_dl)","metadata":{"jupyter":{"outputs_hidden":false}},"pos":74,"state":"done","type":"cell"} {"cell_type":"code","id":"8b69e0","input":"from torch import optim","metadata":{"jupyter":{"outputs_hidden":false}},"pos":50,"state":"done","type":"cell"} {"cell_type":"code","id":"a0d1d7","input":"from torch.utils.data import TensorDataset","metadata":{"jupyter":{"outputs_hidden":false}},"pos":54,"state":"done","type":"cell"} {"cell_type":"code","id":"a24d3e","input":"from torch.utils.data import DataLoader\n\ntrain_ds = TensorDataset(x_train, y_train)\ntrain_dl = DataLoader(train_ds, batch_size=bs)","metadata":{"jupyter":{"outputs_hidden":false}},"pos":60,"state":"done","type":"cell"} {"cell_type":"code","id":"a53ec7","input":"model = Mnist_Logistic()\nprint(loss_func(model(xb), yb))","metadata":{"jupyter":{"outputs_hidden":false}},"pos":46,"state":"done","type":"cell"} {"cell_type":"code","id":"abe186","input":"bs = 64 # batch size\n\nxb = x_train[0:bs] # a mini-batch from x\npreds = model(xb) # predictions\npreds[0], preds.shape\nprint(preds[0], preds.shape)","metadata":{"jupyter":{"outputs_hidden":false}},"pos":16,"state":"done","type":"cell"} {"cell_type":"code","id":"aedfb9","input":"import math\n\nweights = torch.randn(784, 10) / math.sqrt(784)\nweights.requires_grad_()\nbias = torch.zeros(10, requires_grad=True)","metadata":{"jupyter":{"outputs_hidden":false}},"pos":12,"state":"done","type":"cell"} {"cell_type":"code","id":"af0899","input":"print(torch.cuda.is_available())","metadata":{"jupyter":{"outputs_hidden":false}},"pos":90,"state":"done","type":"cell"} {"cell_type":"code","id":"b07f3b","input":"model.to(dev)\nopt = optim.SGD(model.parameters(), lr=lr, momentum=0.9)","metadata":{"jupyter":{"outputs_hidden":false}},"pos":96,"state":"done","type":"cell"} {"cell_type":"code","id":"b18555","input":"def preprocess(x, y):\n return x.view(-1, 1, 28, 28), y\n\n\nclass WrappedDataLoader:\n def __init__(self, dl, func):\n self.dl = dl\n self.func = func\n\n def __len__(self):\n return len(self.dl)\n\n def __iter__(self):\n batches = iter(self.dl)\n for b in batches:\n yield (self.func(*b))\n\ntrain_dl, valid_dl = get_data(train_ds, valid_ds, bs)\ntrain_dl = WrappedDataLoader(train_dl, preprocess)\nvalid_dl = WrappedDataLoader(valid_dl, preprocess)","metadata":{"jupyter":{"outputs_hidden":false}},"pos":84,"state":"done","type":"cell"} {"cell_type":"code","id":"bf0aa3","input":"yb = y_train[0:bs]\nprint(loss_func(preds, yb))","metadata":{"jupyter":{"outputs_hidden":false}},"pos":20,"state":"done","type":"cell"} {"cell_type":"code","id":"cf1a79","input":"model, opt = get_model()\n\nfor epoch in range(epochs):\n for xb, yb in train_dl:\n pred = model(xb)\n loss = loss_func(pred, yb)\n\n loss.backward()\n opt.step()\n opt.zero_grad()\n\nprint(loss_func(model(xb), yb))","metadata":{"jupyter":{"outputs_hidden":false}},"pos":62,"state":"done","type":"cell"} {"cell_type":"code","id":"d24f32","input":"class Mnist_CNN(nn.Module):\n def __init__(self):\n super().__init__()\n self.conv1 = nn.Conv2d(1, 16, kernel_size=3, stride=2, padding=1)\n self.conv2 = nn.Conv2d(16, 16, kernel_size=3, stride=2, padding=1)\n self.conv3 = nn.Conv2d(16, 10, kernel_size=3, stride=2, padding=1)\n\n def forward(self, xb):\n xb = xb.view(-1, 1, 28, 28)\n xb = F.relu(self.conv1(xb))\n xb = F.relu(self.conv2(xb))\n xb = F.relu(self.conv3(xb))\n xb = F.avg_pool2d(xb, 4)\n return xb.view(-1, xb.size(1))\n\nlr = 0.1","metadata":{"jupyter":{"outputs_hidden":false}},"pos":76,"state":"done","type":"cell"} {"cell_type":"code","id":"d6d84e","input":"model = Mnist_Logistic()","metadata":{"jupyter":{"outputs_hidden":false}},"pos":36,"state":"done","type":"cell"} {"cell_type":"code","id":"e6f29c","input":"train_ds = TensorDataset(x_train, y_train)","metadata":{"jupyter":{"outputs_hidden":false}},"pos":56,"state":"done","type":"cell"} {"cell_type":"code","id":"ed46a9","input":"import torch.nn.functional as F\n\nloss_func = F.cross_entropy\n\ndef model(xb):\n return xb @ weights + bias","metadata":{"jupyter":{"outputs_hidden":false}},"pos":30,"state":"done","type":"cell"} {"cell_type":"code","id":"ed8dbd","input":"def fit():\n for epoch in range(epochs):\n for i in range((n - 1) // bs + 1):\n start_i = i * bs\n end_i = start_i + bs\n xb = x_train[start_i:end_i]\n yb = y_train[start_i:end_i]\n pred = model(xb)\n loss = loss_func(pred, yb)\n\n loss.backward()\n with torch.no_grad():\n for p in model.parameters():\n p -= p.grad * lr\n model.zero_grad()\n\nfit()","metadata":{"jupyter":{"outputs_hidden":false}},"pos":40,"state":"done","type":"cell"} {"cell_type":"code","id":"f054c0","input":"train_ds = TensorDataset(x_train, y_train)\ntrain_dl = DataLoader(train_ds, batch_size=bs, shuffle=True)\n\nvalid_ds = TensorDataset(x_valid, y_valid)\nvalid_dl = DataLoader(valid_ds, batch_size=bs * 2)","metadata":{"jupyter":{"outputs_hidden":false}},"pos":64,"state":"done","type":"cell"} {"cell_type":"code","id":"f60dd8","input":"def get_data(train_ds, valid_ds, bs):\n return (\n DataLoader(train_ds, batch_size=bs, shuffle=True),\n DataLoader(valid_ds, batch_size=bs * 2),\n )","metadata":{"jupyter":{"outputs_hidden":false}},"pos":72,"state":"done","type":"cell"} {"cell_type":"code","id":"f88b82","input":"dev = torch.device(\n \"cuda\") if torch.cuda.is_available() else torch.device(\"cpu\")","metadata":{"jupyter":{"outputs_hidden":false}},"pos":92,"state":"done","type":"cell"} {"cell_type":"markdown","id":"06792d","input":"And then create a device object for it:\n\n","pos":91,"state":"done","type":"cell"} {"cell_type":"markdown","id":"0d02a9","input":"Using torch.nn.functional\n------------------------------\n\nWe will now refactor our code, so that it does the same thing as before, only\nwe'll start taking advantage of PyTorch's ``nn`` classes to make it more concise\nand flexible. At each step from here, we should be making our code one or more\nof: shorter, more understandable, and/or more flexible.\n\nThe first and easiest step is to make our code shorter by replacing our\nhand-written activation and loss functions with those from ``torch.nn.functional``\n(which is generally imported into the namespace ``F`` by convention). This module\ncontains all the functions in the ``torch.nn`` library (whereas other parts of the\nlibrary contain classes). As well as a wide range of loss and activation\nfunctions, you'll also find here some convenient functions for creating neural\nnets, such as pooling functions. (There are also functions for doing convolutions,\nlinear layers, etc, but as we'll see, these are usually better handled using\nother parts of the library.)\n\nIf you're using negative log likelihood loss and log softmax activation,\nthen Pytorch provides a single function ``F.cross_entropy`` that combines\nthe two. So we can even remove the activation function from our model.\n\n","pos":29,"state":"done","type":"cell"} {"cell_type":"markdown","id":"13d2e9","input":"In the above, the ``@`` stands for the dot product operation. We will call\nour function on one batch of data (in this case, 64 images). This is\none *forward pass*. Note that our predictions won't be any better than\nrandom at this stage, since we start with random weights.\n\n","pos":15,"state":"done","type":"cell"} {"cell_type":"markdown","id":"144069","input":"`Momentum `_ is a variation on\nstochastic gradient descent that takes previous updates into account as well\nand generally leads to faster training.\n\n","pos":77,"state":"done","type":"cell"} {"cell_type":"markdown","id":"1ec075","input":"Let's update ``preprocess`` to move batches to the GPU:\n\n","pos":93,"state":"done","type":"cell"} {"cell_type":"markdown","id":"24a7ad","input":"We will calculate and print the validation loss at the end of each epoch.\n\n(Note that we always call ``model.train()`` before training, and ``model.eval()``\nbefore inference, because these are used by layers such as ``nn.BatchNorm2d``\nand ``nn.Dropout`` to ensure appropriate behaviour for these different phases.)\n\n","pos":65,"state":"done","type":"cell"} {"cell_type":"markdown","id":"2665fd","input":"We can now run a training loop. For each iteration, we will:\n\n- select a mini-batch of data (of size ``bs``)\n- use the model to make predictions\n- calculate the loss\n- ``loss.backward()`` updates the gradients of the model, in this case, ``weights``\n and ``bias``.\n\nWe now use these gradients to update the weights and bias. We do this\nwithin the ``torch.no_grad()`` context manager, because we do not want these\nactions to be recorded for our next calculation of the gradient. You can read\nmore about how PyTorch's Autograd records operations\n`here `_.\n\nWe then set the\ngradients to zero, so that we are ready for the next loop.\nOtherwise, our gradients would record a running tally of all the operations\nthat had happened (i.e. ``loss.backward()`` *adds* the gradients to whatever is\nalready stored, rather than replacing them).\n\n.. tip:: You can use the standard python debugger to step through PyTorch\n code, allowing you to check the various variable values at each step.\n Uncomment ``set_trace()`` below to try it out.\n\n\n","pos":25,"state":"done","type":"cell"} {"cell_type":"markdown","id":"26ffdc","input":"The model created with ``Sequential`` is simply:\n\n","pos":81,"state":"done","type":"cell"} {"cell_type":"markdown","id":"298978","input":"We recommend running this tutorial as a notebook, not a script. To download the notebook (.ipynb) file,\nclick the link at the top of the page.\n\nPyTorch provides the elegantly designed modules and classes `torch.nn `_ ,\n`torch.optim `_ ,\n`Dataset `_ ,\nand `DataLoader `_\nto help you create and train neural networks.\nIn order to fully utilize their power and customize\nthem for your problem, you need to really understand exactly what they're\ndoing. To develop this understanding, we will first train basic neural net\non the MNIST data set without using any features from these models; we will\ninitially only use the most basic PyTorch tensor functionality. Then, we will\nincrementally add one feature from ``torch.nn``, ``torch.optim``, ``Dataset``, or\n``DataLoader`` at a time, showing exactly what each piece does, and how it\nworks to make the code either more concise, or more flexible.\n\n**This tutorial assumes you already have PyTorch installed, and are familiar\nwith the basics of tensor operations.** (If you're familiar with Numpy array\noperations, you'll find the PyTorch tensor operations used here nearly identical).\n\nMNIST data setup\n----------------\n\nWe will use the classic `MNIST `_ dataset,\nwhich consists of black-and-white images of hand-drawn digits (between 0 and 9).\n\nWe will use `pathlib `_\nfor dealing with paths (part of the Python 3 standard library), and will\ndownload the dataset using\n`requests `_. We will only\nimport modules when we use them, so you can see exactly what's being\nused at each point.\n\n","pos":2,"state":"done","type":"cell"} {"cell_type":"markdown","id":"2a0f71","input":"You should find it runs faster now:\n\n","pos":97,"state":"done","type":"cell"} {"cell_type":"markdown","id":"2bc0e0","input":"Let's double-check that our loss has gone down:\n\n","pos":41,"state":"done","type":"cell"} {"cell_type":"markdown","id":"2f876e","input":"Let's try it out:\n\n","pos":87,"state":"done","type":"cell"} {"cell_type":"markdown","id":"3152f1","input":"Refactor using Dataset\n------------------------------\n\nPyTorch has an abstract Dataset class. A Dataset can be anything that has\na ``__len__`` function (called by Python's standard ``len`` function) and\na ``__getitem__`` function as a way of indexing into it.\n`This tutorial `_\nwalks through a nice example of creating a custom ``FacialLandmarkDataset`` class\nas a subclass of ``Dataset``.\n\nPyTorch's `TensorDataset `_\nis a Dataset wrapping tensors. By defining a length and way of indexing,\nthis also gives us a way to iterate, index, and slice along the first\ndimension of a tensor. This will make it easier to access both the\nindependent and dependent variables in the same line as we train.\n\n","pos":53,"state":"done","type":"cell"} {"cell_type":"markdown","id":"32d67f","input":"We are still able to use our same ``fit`` method as before.\n\n","pos":47,"state":"done","type":"cell"} {"cell_type":"markdown","id":"39260e","input":"PyTorch uses ``torch.tensor``, rather than numpy arrays, so we need to\nconvert our data.\n\n","pos":9,"state":"done","type":"cell"} {"cell_type":"markdown","id":"411394","input":"``fit`` runs the necessary operations to train our model and compute the\ntraining and validation losses for each epoch.\n\n","pos":69,"state":"done","type":"cell"} {"cell_type":"markdown","id":"4b1a4f","input":"Now, our whole process of obtaining the data loaders and fitting the\nmodel can be run in 3 lines of code:\n\n","pos":73,"state":"done","type":"cell"} {"cell_type":"markdown","id":"4fe9bb","input":"Since we're now using an object instead of just using a function, we\nfirst have to instantiate our model:\n\n","pos":35,"state":"done","type":"cell"} {"cell_type":"markdown","id":"53d8e0","input":"nn.Sequential\n------------------------\n\n``torch.nn`` has another handy class we can use to simplify our code:\n`Sequential `_ .\nA ``Sequential`` object runs each of the modules contained within it, in a\nsequential manner. This is a simpler way of writing our neural network.\n\nTo take advantage of this, we need to be able to easily define a\n**custom layer** from a given function. For instance, PyTorch doesn't\nhave a `view` layer, and we need to create one for our network. ``Lambda``\nwill create a layer that we can then use when defining a network with\n``Sequential``.\n\n","pos":79,"state":"done","type":"cell"} {"cell_type":"markdown","id":"5618be","input":"``get_data`` returns dataloaders for the training and validation sets.\n\n","pos":71,"state":"done","type":"cell"} {"cell_type":"markdown","id":"59aaf4","input":"Let's check our loss with our random model, so we can see if we improve\nafter a backprop pass later.\n\n","pos":19,"state":"done","type":"cell"} {"cell_type":"markdown","id":"5e3759","input":"\nWhat is `torch.nn` *really*?\n============================\nby Jeremy Howard, `fast.ai `_. Thanks to Rachel Thomas and Francisco Ingham.\n\n","pos":1,"state":"done","type":"cell"} {"cell_type":"markdown","id":"5f9e23","input":"Now we can calculate the loss in the same way as before. Note that\n``nn.Module`` objects are used as if they are functions (i.e they are\n*callable*), but behind the scenes Pytorch will call our ``forward``\nmethod automatically.\n\n","pos":37,"state":"done","type":"cell"} {"cell_type":"markdown","id":"610c24","input":"Note that we no longer call ``log_softmax`` in the ``model`` function. Let's\nconfirm that our loss and accuracy are the same as before:\n\n","pos":31,"state":"done","type":"cell"} {"cell_type":"markdown","id":"67a0eb","input":"Let's check the accuracy of our random model, so we can see if our\naccuracy improves as our loss improves.\n\n","pos":23,"state":"done","type":"cell"} {"cell_type":"markdown","id":"682fa6","input":"Wrapping DataLoader\n-----------------------------\n\nOur CNN is fairly concise, but it only works with MNIST, because:\n - It assumes the input is a 28\\*28 long vector\n - It assumes that the final CNN grid size is 4\\*4 (since that's the average\npooling kernel size we used)\n\nLet's get rid of these two assumptions, so our model works with any 2d\nsingle channel image. First, we can remove the initial Lambda layer by\nmoving the data preprocessing into a generator:\n\n","pos":83,"state":"done","type":"cell"} {"cell_type":"markdown","id":"69e5bd","input":"Finally, we can move our model to the GPU.\n\n","pos":95,"state":"done","type":"cell"} {"cell_type":"markdown","id":"70be5f","input":"Refactor using nn.Linear\n-------------------------\n\nWe continue to refactor our code. Instead of manually defining and\ninitializing ``self.weights`` and ``self.bias``, and calculating ``xb @\nself.weights + self.bias``, we will instead use the Pytorch class\n`nn.Linear `_ for a\nlinear layer, which does all that for us. Pytorch has many types of\npredefined layers that can greatly simplify our code, and often makes it\nfaster too.\n\n","pos":43,"state":"done","type":"cell"} {"cell_type":"markdown","id":"711a8d","input":"Neural net from scratch (no torch.nn)\n---------------------------------------------\n\nLet's first create a model using nothing but PyTorch tensor operations. We're assuming\nyou're already familiar with the basics of neural networks. (If you're not, you can\nlearn them at `course.fast.ai `_).\n\nPyTorch provides methods to create random or zero-filled tensors, which we will\nuse to create our weights and bias for a simple linear model. These are just regular\ntensors, with one very special addition: we tell PyTorch that they require a\ngradient. This causes PyTorch to record all of the operations done on the tensor,\nso that it can calculate the gradient during back-propagation *automatically*!\n\nFor the weights, we set ``requires_grad`` **after** the initialization, since we\ndon't want that step included in the gradient. (Note that a trailing ``_`` in\nPyTorch signifies that the operation is performed in-place.)\n\n

Note

We are initializing the weights here with\n `Xavier initialisation `_\n (by multiplying with 1/sqrt(n)).

\n\n","pos":11,"state":"done","type":"cell"} {"cell_type":"markdown","id":"74be6e","input":"Thanks to Pytorch's ``nn.Module``, ``nn.Parameter``, ``Dataset``, and ``DataLoader``,\nour training loop is now dramatically smaller and easier to understand. Let's\nnow try to add the basic features necessary to create effective models in practice.\n\nAdd validation\n-----------------------\n\nIn section 1, we were just trying to get a reasonable training loop set up for\nuse on our training data. In reality, you **always** should also have\na `validation set `_, in order\nto identify if you are overfitting.\n\nShuffling the training data is\n`important `_\nto prevent correlation between batches and overfitting. On the other hand, the\nvalidation loss will be identical whether we shuffle the validation set or not.\nSince shuffling takes extra time, it makes no sense to shuffle the validation data.\n\nWe'll use a batch size for the validation set that is twice as large as\nthat for the training set. This is because the validation set does not\nneed backpropagation and thus takes less memory (it doesn't need to\nstore the gradients). We take advantage of this to use a larger batch\nsize and compute the loss more quickly.\n\n","pos":63,"state":"done","type":"cell"} {"cell_type":"markdown","id":"77b646","input":"Refactor using optim\n------------------------------\n\nPytorch also has a package with various optimization algorithms, ``torch.optim``.\nWe can use the ``step`` method from our optimizer to take a forward step, instead\nof manually updating each parameter.\n\nThis will let us replace our previous manually coded optimization step:\n::\n with torch.no_grad():\n for p in model.parameters(): p -= p.grad * lr\n model.zero_grad()\n\nand instead use just:\n::\n opt.step()\n opt.zero_grad()\n\n(``optim.zero_grad()`` resets the gradient to 0 and we need to call it before\ncomputing the gradient for the next minibatch.)\n\n","pos":49,"state":"done","type":"cell"} {"cell_type":"markdown","id":"841c6f","input":"As you see, the ``preds`` tensor contains not only the tensor values, but also a\ngradient function. We'll use this later to do backprop.\n\nLet's implement negative log-likelihood to use as the loss function\n(again, we can just use standard Python):\n\n","pos":17,"state":"done","type":"cell"} {"cell_type":"markdown","id":"a0d8c3","input":"Previously for our training loop we had to update the values for each parameter\nby name, and manually zero out the grads for each parameter separately, like this:\n::\n with torch.no_grad():\n weights -= weights.grad * lr\n bias -= bias.grad * lr\n weights.grad.zero_()\n bias.grad.zero_()\n\n\nNow we can take advantage of model.parameters() and model.zero_grad() (which\nare both defined by PyTorch for ``nn.Module``) to make those steps more concise\nand less prone to the error of forgetting some of our parameters, particularly\nif we had a more complicated model:\n::\n with torch.no_grad():\n for p in model.parameters(): p -= p.grad * lr\n model.zero_grad()\n\n\nWe'll wrap our little training loop in a ``fit`` function so we can run it\nagain later.\n\n","pos":39,"state":"done","type":"cell"} {"cell_type":"markdown","id":"ae0d92","input":"Next, we can replace ``nn.AvgPool2d`` with ``nn.AdaptiveAvgPool2d``, which\nallows us to define the size of the *output* tensor we want, rather than\nthe *input* tensor we have. As a result, our model will work with any\nsize input.\n\n","pos":85,"state":"done","type":"cell"} {"cell_type":"markdown","id":"ae716c","input":"Thanks to PyTorch's ability to calculate gradients automatically, we can\nuse any standard Python function (or callable object) as a model! So\nlet's just write a plain matrix multiplication and broadcasted addition\nto create a simple linear model. We also need an activation function, so\nwe'll write `log_softmax` and use it. Remember: although PyTorch\nprovides lots of pre-written loss functions, activation functions, and\nso forth, you can easily write your own using plain python. PyTorch will\neven create fast GPU or vectorized CPU code for your function\nautomatically.\n\n","pos":13,"state":"done","type":"cell"} {"cell_type":"markdown","id":"aebae7","input":"We'll define a little function to create our model and optimizer so we\ncan reuse it in the future.\n\n","pos":51,"state":"done","type":"cell"} {"cell_type":"markdown","id":"b0fd86","input":"We instantiate our model and calculate the loss in the same way as before:\n\n","pos":45,"state":"done","type":"cell"} {"cell_type":"markdown","id":"b3c5e0","input":"Previously, our loop iterated over batches (xb, yb) like this:\n::\n for i in range((n-1)//bs + 1):\n xb,yb = train_ds[i*bs : i*bs+bs]\n pred = model(xb)\n\nNow, our loop is much cleaner, as (xb, yb) are loaded automatically from the data loader:\n::\n for xb,yb in train_dl:\n pred = model(xb)\n\n","pos":61,"state":"done","type":"cell"} {"cell_type":"markdown","id":"b85c97","input":"Refactor using DataLoader\n------------------------------\n\nPytorch's ``DataLoader`` is responsible for managing batches. You can\ncreate a ``DataLoader`` from any ``Dataset``. ``DataLoader`` makes it easier\nto iterate over batches. Rather than having to use ``train_ds[i*bs : i*bs+bs]``,\nthe DataLoader gives us each minibatch automatically.\n\n","pos":59,"state":"done","type":"cell"} {"cell_type":"markdown","id":"bba2b6","input":"Each image is 28 x 28, and is being stored as a flattened row of length\n784 (=28x28). Let's take a look at one; we need to reshape it to 2d\nfirst.\n\n","pos":7,"state":"done","type":"cell"} {"cell_type":"markdown","id":"cadeff","input":"Let's also implement a function to calculate the accuracy of our model.\nFor each prediction, if the index with the largest value matches the\ntarget value, then the prediction was correct.\n\n","pos":21,"state":"done","type":"cell"} {"cell_type":"markdown","id":"cf6a2b","input":"Closing thoughts\n-----------------\n\nWe now have a general data pipeline and training loop which you can use for\ntraining many types of models using Pytorch. To see how simple training a model\ncan now be, take a look at the `mnist_sample` sample notebook.\n\nOf course, there are many things you'll want to add, such as data augmentation,\nhyperparameter tuning, monitoring training, transfer learning, and so forth.\nThese features are available in the fastai library, which has been developed\nusing the same design approach shown in this tutorial, providing a natural\nnext step for practitioners looking to take their models further.\n\nWe promised at the start of this tutorial we'd explain through example each of\n``torch.nn``, ``torch.optim``, ``Dataset``, and ``DataLoader``. So let's summarize\nwhat we've seen:\n\n - **torch.nn**\n\n + ``Module``: creates a callable which behaves like a function, but can also\n contain state(such as neural net layer weights). It knows what ``Parameter`` (s) it\n contains and can zero all their gradients, loop through them for weight updates, etc.\n + ``Parameter``: a wrapper for a tensor that tells a ``Module`` that it has weights\n that need updating during backprop. Only tensors with the `requires_grad` attribute set are updated\n + ``functional``: a module(usually imported into the ``F`` namespace by convention)\n which contains activation functions, loss functions, etc, as well as non-stateful\n versions of layers such as convolutional and linear layers.\n - ``torch.optim``: Contains optimizers such as ``SGD``, which update the weights\n of ``Parameter`` during the backward step\n - ``Dataset``: An abstract interface of objects with a ``__len__`` and a ``__getitem__``,\n including classes provided with Pytorch such as ``TensorDataset``\n - ``DataLoader``: Takes any ``Dataset`` and creates an iterator which returns batches of data.\n\n","pos":99,"state":"done","type":"cell"} {"cell_type":"markdown","id":"d0346c","input":"You can use these basic 3 lines of code to train a wide variety of models.\nLet's see if we can use them to train a convolutional neural network (CNN)!\n\nSwitch to CNN\n-------------\n\nWe are now going to build our neural network with three convolutional layers.\nBecause none of the functions in the previous section assume anything about\nthe model form, we'll be able to use them to train a CNN without any modification.\n\nWe will use Pytorch's predefined\n`Conv2d `_ class\nas our convolutional layer. We define a CNN with 3 convolutional layers.\nEach convolution is followed by a ReLU. At the end, we perform an\naverage pooling. (Note that ``view`` is PyTorch's version of numpy's\n``reshape``)\n\n","pos":75,"state":"done","type":"cell"} {"cell_type":"markdown","id":"d10549","input":"Create fit() and get_data()\n----------------------------------\n\nWe'll now do a little refactoring of our own. Since we go through a similar\nprocess twice of calculating the loss for both the training set and the\nvalidation set, let's make that into its own function, ``loss_batch``, which\ncomputes the loss for one batch.\n\nWe pass an optimizer in for the training set, and use it to perform\nbackprop. For the validation set, we don't pass an optimizer, so the\nmethod doesn't perform backprop.\n\n","pos":67,"state":"done","type":"cell"} {"cell_type":"markdown","id":"d398a1","input":"That's it: we've created and trained a minimal neural network (in this case, a\nlogistic regression, since we have no hidden layers) entirely from scratch!\n\nLet's check the loss and accuracy and compare those to what we got\nearlier. We expect that the loss will have decreased and accuracy to\nhave increased, and they have.\n\n","pos":27,"state":"done","type":"cell"} {"cell_type":"markdown","id":"e02480","input":"Refactor using nn.Module\n-----------------------------\nNext up, we'll use ``nn.Module`` and ``nn.Parameter``, for a clearer and more\nconcise training loop. We subclass ``nn.Module`` (which itself is a class and\nable to keep track of state). In this case, we want to create a class that\nholds our weights, bias, and method for the forward step. ``nn.Module`` has a\nnumber of attributes and methods (such as ``.parameters()`` and ``.zero_grad()``)\nwhich we will be using.\n\n

Note

``nn.Module`` (uppercase M) is a PyTorch specific concept, and is a\n class we'll be using a lot. ``nn.Module`` is not to be confused with the Python\n concept of a (lowercase ``m``) `module `_,\n which is a file of Python code that can be imported.

\n\n","pos":33,"state":"done","type":"cell"} {"cell_type":"markdown","id":"e51cd0","input":"Both ``x_train`` and ``y_train`` can be combined in a single ``TensorDataset``,\nwhich will be easier to iterate over and slice.\n\n","pos":55,"state":"done","type":"cell"} {"cell_type":"markdown","id":"f1ddaa","input":"This dataset is in numpy array format, and has been stored using pickle,\na python-specific format for serializing data.\n\n","pos":4,"state":"done","type":"cell"} {"cell_type":"markdown","id":"f3f1d1","input":"Previously, we had to iterate through minibatches of x and y values separately:\n::\n xb = x_train[start_i:end_i]\n yb = y_train[start_i:end_i]\n\n\nNow, we can do these two steps together:\n::\n xb,yb = train_ds[i*bs : i*bs+bs]\n\n\n","pos":57,"state":"done","type":"cell"} {"cell_type":"markdown","id":"f73650","input":"Using your GPU\n---------------\n\nIf you're lucky enough to have access to a CUDA-capable GPU (you can\nrent one for about $0.50/hour from most cloud providers) you can\nuse it to speed up your code. First check that your GPU is working in\nPytorch:\n\n","pos":89,"state":"done","type":"cell"} {"id":0,"time":1631142246776,"type":"user"} {"last_load":1631142247936,"type":"file"}