{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\nimport matplotlib.pyplot as plt\nimport os\n# for dirname, _, filenames in os.walk('/kaggle/input'):\n#     for filename in filenames:\n#         print(os.path.join(dirname, filename))\nfrom skimage import io\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"# importing pytorch modules\nimport torch\nimport torch.nn.functional as F\nimport torch.nn as nn\nfrom torch import optim\nimport torchvision\nimport torchvision.datasets as datasets\nimport torchvision.transforms as transforms\nfrom torch.utils.data import DataLoader, Dataset\nfrom torchvision import models\nfrom time import time","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"tic=time()\nprint(\"Time module testing\")\ntac=time()\nprint(\"duration: \", tac-tic)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"torch.tensor([0], dtype = torch.long)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class DatasetCUSTOM(Dataset):\n    \n    def __init__(self, image_path, label_path, transform=None):\n        self.image_path= image_path\n        self.labels= pd.read_csv(label_path)\n        self.transform = transform\n        \n    def __len__(self):\n        return len(self.labels)\n    \n    def __getitem__(self, idx):\n            \n        img_name= os.path.join(self.image_path, self.labels.iloc[idx,0])\n        image= io.imread(img_name+\".png\")\n        image=np.array(image).astype(np.uint8)\n        label = self.labels.iloc[idx,1] \n        if self.transform is not None:\n            image = self.transform(image)\n            \n        return image, label","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"transform_train=transforms.Compose([\n    transforms.ToPILImage(),\n    transforms.Resize((229,229)),\n    transforms.ToTensor(),\n    transforms.Normalize((0.485,0.456,0.406),(0.229,0.224, 0.225)),\n    ])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"images = pd.read_csv(\"../input/aptos2019-blindness-detection/train.csv\")[\"id_code\"]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import cv2","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.mkdir(\"train_images_229\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for image in images:\n    img = cv2.imread(\"../input/aptos2019-blindness-detection/train_images/\" + image + \".png\")\n    img = cv2.resize(img, (229,229))\n    cv2.imwrite(\"./train_images_229/\" + image + \".png\", img)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size = 64\ntrainset=DatasetCUSTOM(\"./train_images_229/\",\n                       \"../input/aptos2019-blindness-detection/train.csv\",\n                       transform=transform_train\n                       )\ntrainloader=DataLoader(trainset,batch_size=batch_size,shuffle=True)\ndataiter=iter(trainloader)\ntic=time()\nimages, labels=dataiter.next()\ntac=time()\nprint(\"Dataiter time:\", tac-tic)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(len(trainset))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(images.shape)\nnpimg=np.array(images[1])\nimg=np.transpose(npimg,(2,1,0))\nprint(img.shape)\nplt.imshow(img)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class LeNet(nn.Module):\n    def __init__(self):\n        super(LeNet, self).__init__()\n        self.cnn_model= nn.Sequential(\n            nn.Conv2d(3,6,5), #(28,28,1)------>(24,24,6)\n            nn.ReLU(),\n            nn.MaxPool2d(2, stride=2), # (24,24,6)------>(12,12,6)\n            nn.Conv2d(6,16,5), # (12,12,6)-------->(8,8,16)\n            nn.ReLU(),\n            nn.MaxPool2d(2, stride=2),\n            nn.Conv2d(16,32,3),\n            nn.ReLU(),\n            nn.MaxPool2d(2, stride=2),\n            nn.Conv2d(32,32,3),\n            nn.ReLU(),\n            nn.MaxPool2d(2, stride=2),\n            nn.Conv2d(32,32,3),\n            nn.ReLU(),\n            nn.MaxPool2d(2, stride=2)\n            )\n            \n        self.fc_model=nn.Sequential(\n            nn.Linear(800,120),\n            nn.ReLU(),\n            nn.Linear(120,84),\n            nn.ReLU(),\n            nn.Linear(84,5),\n            nn.Softmax()\n            )\n            \n        \n    def forward(self,x):\n#         print(x.shape)\n        x = self.cnn_model(x)\n        x = nn.Flatten()(x)\n        x = self.fc_model(x)\n#         print(x.shape)\n        return x","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Modifying the number of neurons in output layer**"},{"metadata":{},"cell_type":"markdown","source":"**Have a look at the modified model**"},{"metadata":{"trusted":true},"cell_type":"code","source":"def evaluation(dataloader, model):\n    correct, total=0,0\n    for data in dataloader:\n        inputs, labels= data\n        inputs, labels= inputs.to(device), labels.to(device)\n        output= model(inputs)\n        _, pred = torch.max(output,1)\n        total+= labels.size()\n        correct+= (pred==labels).sum().item()\n    return 100*correct/total\n        ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"device=\"cuda\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model=LeNet().to(device)\nloss_fn=nn.CrossEntropyLoss()\nopt=optim.Adam(model.parameters(), lr=0.0001)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for param in model.parameters():\n    if param.requires_grad:\n        print(param.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"loss_per_epoch=[]\nloss_arr=[]\nmax_epochs=10\nn_iters= np.ceil(3662/batch_size)\nfor epoch in range(max_epochs):\n    for i, data in enumerate(trainloader,0):\n        inputs, labels= data\n        inputs, labels= inputs.cuda(), labels.cuda()\n#         print(inputs.shape)\n        opt.zero_grad()\n        outputs = model(inputs)\n        loss=loss_fn(outputs, labels)\n        loss_arr.append(loss)\n        loss.backward()\n        opt.step()\n        del inputs, labels, outputs\n        torch.cuda.empty_cache()\n        if i% 500==0:\n            print(\"Epoch:%d, Iteration: %d/%d, Loss: %0.2f\" %(epoch,i,n_iters,loss.item()))\n    loss_per_epoch.append(loss.item())\nplt.plot(loss_arr,'r')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Evaluating the model**"},{"metadata":{"trusted":true},"cell_type":"code","source":"images = pd.read_csv(\"../input/aptos2019-blindness-detection/train.csv\")[\"id_code\"]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import zipfile\nzf = zipfile.ZipFile('train_images_229.zip', mode='w')\nfor image in images:\n    zf.write(\"./train_images_229/\" + image + \".png\")\n    os.remove(\"./train_images_229/\" + image + \".png\")\nzf.close()","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":1}