{"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\nfrom PIL import Image\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import cv2","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":"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#         if torch.is_tensor(idx):\n#             idx=idx.tolist()\n            \n        img_name= os.path.join(self.image_path, self.labels.iloc[idx,0])\n        image= Image.open(img_name+\".png\")\n        image=np.array(image).astype(np.uint8)\n#         print(image.shape)\n#         image=np.transpose(image,(2,0,1)).astype(np.uint8)\n#         image=torch.Tensor(image)\n#         print(image.dtype, image.shape)\n        label= self.labels.iloc[idx,1].toTensor()\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((28,28)),\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_name = pd.read_csv(\"../input/aptos2019-blindness-detection/train.csv\")[\"id_code\"]\nos.mkdir(\"../input/train_images_229\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for image in images_name:\n    img = cv2.imread(\"../input/aptos2019-blindness-detection/train_images/\" + image + \".png\")\n    img = cv2.resize(img, (229,229))\n    cv2.imwrite(\"../input/train_images_229/\" + image + \".png\", img)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.listdir(\"../input/train_images_229/\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size = 128\ntrainset=DatasetCUSTOM(\"../input/train_images_229/\",\n                       \"../input/aptos2019-blindness-detection/train.csv\",\n                       transform=transform_train\n                       )\ntrainloader=DataLoader(trainset,batch_size=batch_size,shuffle=False)\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":"images, labels=iter(trainloader).next()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(labels.size()[0])\nnpimg=np.array(images[1])\nimg=np.transpose(npimg,(2,1,0))\nplt.imshow(img)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = models.resnet50(pretrained=True)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Modifying the number of neurons in output layer**"},{"metadata":{"trusted":true},"cell_type":"code","source":"for param in model.parameters():\n    param.requires_grad=False","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"num_classes=5\nfinal_in_features=model.fc.in_features\nmodel.fc=nn.Linear(final_in_features,num_classes)\nprint(model.fc)","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":{},"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()[0]\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=model.to(device)\nloss_fn=nn.CrossEntropyLoss()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"opt=optim.Adam(model.parameters(), lr=0.001)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size= 128\ntrainloader=DataLoader(trainset,batch_size=batch_size,shuffle=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.train()\nloss_per_epoch=[]\nloss_arr=[]\nmax_epochs=16\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% 2==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_per_epoch,'r')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Evaluating the model**"},{"metadata":{"trusted":true},"cell_type":"code","source":"model.eval()\nprint(\"Training Accuracy:\", evaluation(trainloader,model))","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}