{"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\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 read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\n# for dirname, _, filenames in os.walk('/kaggle/input'):\n#     for filename in filenames:\n#         print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom torchvision import transforms\nimport pytorch_lightning as pl\nfrom torch.optim.swa_utils import AveragedModel\nfrom pytorch_lightning.metrics.functional import accuracy\nfrom sklearn import metrics, model_selection, preprocessing\nfrom PIL import Image\nfrom collections import Counter,OrderedDict\nimport json\nimport torchvision\nimport time\nfrom albumentations import Compose,HorizontalFlip,VerticalFlip,ShiftScaleRotate,RandomCrop,MultiplicativeNoise","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# ResNet Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"class LitModel(pl.LightningModule):\n    def __init__(self,classify,n_cls=5,pretrained=False,t_data=None,v_data=None):\n        super().__init__()\n        self.classify = classify\n        self.n_cls = n_cls\n        self.pre_trained = pretrained\n        self.model = self.modified_model()\n        self.criterion = nn.CrossEntropyLoss()\n        self.learning_rate = 0.1\n        self.t_data = t_data\n        self.v_data = v_data\n        self.batch_size = 256\n\n        #addition linear layer\n        self.logits = nn.Linear(512,self.n_cls)\n\n        \n    def forward(self,x):\n      embeddings = self.model(x)\n      if self.classify:\n        logits = self.logits(embeddings)\n        return logits\n      else:\n        return embeddings\n        \n      \n    def modified_model(self):\n      model = torchvision.models.resnet50(pretrained=self.pre_trained)\n      model.fc = nn.Sequential(\n                         nn.Dropout(p=0.8),\n                         nn.Linear(2048, 512,bias=False),\n                         nn.BatchNorm1d(512))\n      return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lit_model = LitModel(True,5,False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#version 15 used this model\n# dicts = torch.load('/kaggle/input/exp1-models/epoch9-v0_best_val_loss.ckpt',map_location='cpu')\n\n#version 16 - using best_val_acc model\n# dicts = torch.load('/kaggle/input/exp1-models/epoch9_best_val_acc.ckpt',map_location='cpu')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# lit_model.load_state_dict(dicts['state_dict'])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# SwaResnet model"},{"metadata":{"trusted":true},"cell_type":"code","source":"class SWAResnet(pl.LightningModule):\n    def __init__(self,trained_model):\n        super().__init__()\n        self.model = trained_model\n        self.swa_model = AveragedModel(self.model)\n        \n        \n    def forward(self,x):\n        logit = self.swa_model(x)\n        return logit","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = SWAResnet(lit_model).load_from_checkpoint('/kaggle/input/exp1-models/epoch0.ckpt',trained_model=lit_model,map_location='cpu')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"final_model = model.swa_model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Submission"},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission_df = pd.read_csv(\"/kaggle/input/cassava-leaf-disease-classification/sample_submission.csv\")\npath = \"/kaggle/input/cassava-leaf-disease-classification/test_images/\"\n\npredictions = []\nimage_id = []\n\nfinal_model.eval()\n\nwith torch.no_grad():\n    for img_id in sample_submission_df.image_id:\n        \n        img_path = path + img_id\n        image = Image.open(img_path).convert('RGB')\n        \n        image = transforms.Resize(224)(image)\n        image = transforms.ToTensor()(image)\n        image = transforms.Normalize(mean=[0.485,0.456,0.406],\n                                    std = [0.229, 0.224, 0.225])(image)\n        \n        logits = final_model(image.unsqueeze(0))\n        probs,preds = torch.topk(F.softmax(logits,dim=1),1)\n        preds = preds.cpu().detach().numpy().flatten()[0]\n        predictions.append(preds)\n        image_id.append(img_id)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"assert len(predictions) == len(image_id)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"my_submission = pd.DataFrame({'image_id': image_id,\n                             'label': predictions})\nmy_submission.to_csv('submission.csv',index = False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"my_submission.head()","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}