{"cells":[{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import torch\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch.nn.functional as F\nfrom torch import nn\nfrom torchvision import datasets, transforms ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\") # To use to cuba GPU","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"transform = transforms.Compose([transforms.Resize((28,28)),\n                               transforms.ToTensor(),\n                               transforms.Normalize((0.5,), (0.5,))\n                               ])\ntraining_dataset = datasets.MNIST(root='./data_1', train=True, download=True, transform=transform)\nvalidation_dataset = datasets.MNIST(root='./data_1', train=False, download=True, transform=transform)\n\ntraining_loader = torch.utils.data.DataLoader(training_dataset, batch_size=100, shuffle=True)\nvalidation_loader = torch.utils.data.DataLoader(validation_dataset, batch_size = 100, shuffle=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def im_convert(tensor):\n  image = tensor.cpu().clone().detach().numpy() # Just use cpu in this case as it is not compatible with gpu\n  image = image.transpose(1, 2, 0)\n  image = image * np.array((0.5, 0.5, 0.5)) + np.array((0.5, 0.5, 0.5))\n  image = image.clip(0, 1)\n  return image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dataiter = iter(training_loader)\nimages, labels = dataiter.next()\nfig = plt.figure(figsize=(25, 4))\n\nfor idx in np.arange(20):\n  ax = fig.add_subplot(2, 10, idx+1, xticks=[], yticks=[])\n  plt.imshow(im_convert(images[idx]))\n  ax.set_title([labels[idx].item()])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n\n\nmodel = nn.Sequential(nn.Linear(784, 128),\n                      nn.ReLU(),\n                      nn.Linear(128, 64),\n                      nn.ReLU(),\n                      nn.Linear(64, 10),\n                      nn.LogSoftmax(dim=1))\nprint(model)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = model.to(device)\nmodel","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"criterion = nn.NLLLoss()\nimages, labels = next(iter(training_loader))\nimages = images.view(images.shape[0], -1)\nimages = images.to(device)\nlabels = labels.to(device)\nlogps = model(images) #log probabilities\nloss = criterion(logps, labels)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from torch import optim\nfrom time import time\n\noptimizer = optim.SGD(model.parameters(), lr=0.003, momentum=0.9)\ntime0 = time()\nepochs = 15\nfor e in range(epochs):\n    running_loss = 0\n    for images, labels in training_loader:\n        # Flatten MNIST images into a 784 long vector\n        images = images.view(images.shape[0], -1)\n        images = images.to(device)\n        labels = labels.to(device)\n        # Training pass\n        optimizer.zero_grad()\n        \n        output = model(images)\n        loss = criterion(output, labels)\n        \n        #This is where the model learns by backpropagating\n        loss.backward()\n        \n        #And optimizes its weights here\n        optimizer.step()\n        \n        running_loss += loss.item()\n    else:\n        print(\"Epoch {} - Training loss: {}\".format(e, running_loss/len(training_loader)))\n\nprint(\"\\nTraining Time (in minutes) =\",(time()-time0)/60)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"images, labels = next(iter(validation_loader))\n\nimg = images[0].view(1, 784) \nimg = img.to(device)\nlabels = labels.to(device)\nwith torch.no_grad():\n    logps = model(img)\n\nps = torch.exp(logps)\nprobab = list(ps.numpy()[0])\nprint(\"Predicted Digit =\", probab.index(max(probab)))\n#view_classify(img.view(1, 28, 28), ps)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"correct_count, all_count = 0, 0\nfor images,labels in validation_loader:\n    images = images.to(device)\n    labels = labels.to(device)\n    for i in range(len(labels)):\n        img = images[i].view(1, 784)\n        with torch.no_grad():\n            logps = model(img)\n\n    \n        ps = torch.exp(logps)\n        probab = list(ps.numpy()[0])\n        pred_label = probab.index(max(probab))\n        true_label = labels.numpy()[i]\n        if(true_label == pred_label):\n          correct_count += 1\n        all_count += 1\n\nprint(\"Number Of Images Tested =\", all_count)\nprint(\"\\nModel Accuracy =\", (correct_count/all_count))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}