{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":14774,"databundleVersionId":875431,"sourceType":"competition"},{"sourceId":10040,"sourceType":"datasetVersion","datasetId":6979}],"dockerImageVersionId":27938,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"%reload_ext autoreload\n%autoreload 2\n%matplotlib inline","metadata":{"execution":{"iopub.status.busy":"2024-01-07T21:35:06.189159Z","iopub.execute_input":"2024-01-07T21:35:06.189443Z","iopub.status.idle":"2024-01-07T21:35:06.282878Z","shell.execute_reply.started":"2024-01-07T21:35:06.189401Z","shell.execute_reply":"2024-01-07T21:35:06.281977Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from fastai import *\nfrom fastai.vision import *\nimport pandas as pd\nimport matplotlib.pyplot as plt","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-01-07T21:35:09.466190Z","iopub.execute_input":"2024-01-07T21:35:09.466521Z","iopub.status.idle":"2024-01-07T21:35:09.550006Z","shell.execute_reply.started":"2024-01-07T21:35:09.466463Z","shell.execute_reply":"2024-01-07T21:35:09.549113Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nif not os.path.exists('/tmp/.cache/torch/checkpoints/'):\n        os.makedirs('/tmp/.cache/torch/checkpoints/')\n!cp '../input/resnet50/resnet50.pth' '/tmp/.cache/torch/checkpoints/resnet50-19c8e357.pth'\n","metadata":{"execution":{"iopub.status.busy":"2024-01-07T21:35:35.516989Z","iopub.execute_input":"2024-01-07T21:35:35.517305Z","iopub.status.idle":"2024-01-07T21:35:36.845109Z","shell.execute_reply.started":"2024-01-07T21:35:35.517260Z","shell.execute_reply":"2024-01-07T21:35:36.844148Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nos.listdir('../input')\n","metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","execution":{"iopub.status.busy":"2024-01-07T21:36:17.881202Z","iopub.execute_input":"2024-01-07T21:36:17.881580Z","iopub.status.idle":"2024-01-07T21:36:17.968032Z","shell.execute_reply.started":"2024-01-07T21:36:17.881524Z","shell.execute_reply":"2024-01-07T21:36:17.967081Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Make sure cudnn is enabled:', torch.backends.cudnn.enabled)","metadata":{"execution":{"iopub.status.busy":"2024-01-07T21:36:30.205324Z","iopub.execute_input":"2024-01-07T21:36:30.205617Z","iopub.status.idle":"2024-01-07T21:36:30.290842Z","shell.execute_reply.started":"2024-01-07T21:36:30.205574Z","shell.execute_reply":"2024-01-07T21:36:30.289961Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def seed_everything(seed):\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.backends.cudnn.deterministic = True\n\nSEED = 999\nseed_everything(SEED)","metadata":{"execution":{"iopub.status.busy":"2024-01-07T21:36:38.424258Z","iopub.execute_input":"2024-01-07T21:36:38.424551Z","iopub.status.idle":"2024-01-07T21:36:38.509640Z","shell.execute_reply.started":"2024-01-07T21:36:38.424507Z","shell.execute_reply":"2024-01-07T21:36:38.508979Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_image_dir = os.path.join('..', 'input/aptos2019-blindness-detection/')\ntrain_dir = os.path.join(base_image_dir,'train_images/')\ndf = pd.read_csv(os.path.join(base_image_dir, 'train.csv'))\ndf['path'] = df['id_code'].map(lambda x: os.path.join(train_dir,'{}.png'.format(x)))\ndf = df.drop(columns=['id_code'])\ndf = df.sample(frac=1).reset_index(drop=True) #shuffle dataframe\ndf.head(10)","metadata":{"execution":{"iopub.status.busy":"2024-01-07T21:36:41.442575Z","iopub.execute_input":"2024-01-07T21:36:41.442952Z","iopub.status.idle":"2024-01-07T21:36:41.696304Z","shell.execute_reply.started":"2024-01-07T21:36:41.442898Z","shell.execute_reply":"2024-01-07T21:36:41.695540Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len_df = len(df)\nprint(f\"There are {len_df} images\")","metadata":{"execution":{"iopub.status.busy":"2024-01-07T21:36:49.699325Z","iopub.execute_input":"2024-01-07T21:36:49.699629Z","iopub.status.idle":"2024-01-07T21:36:49.794588Z","shell.execute_reply.started":"2024-01-07T21:36:49.699592Z","shell.execute_reply":"2024-01-07T21:36:49.793838Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"This is actually very small. The [previous competition](https://kaggle.com/c/diabetic-retinopathy-detection) had ~35k images, which supports the idea that pretraining on that dataset may be quite beneficial.","metadata":{}},{"cell_type":"markdown","source":"The dataset is highly imbalanced, with many samples for level 0, and very little for the rest of the levels.","metadata":{}},{"cell_type":"code","source":"df['diagnosis'].hist(figsize = (10, 5))","metadata":{"execution":{"iopub.status.busy":"2024-01-07T21:37:03.550570Z","iopub.execute_input":"2024-01-07T21:37:03.550898Z","iopub.status.idle":"2024-01-07T21:37:04.009170Z","shell.execute_reply.started":"2024-01-07T21:37:03.550853Z","shell.execute_reply":"2024-01-07T21:37:04.008077Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Let's look at an example image:","metadata":{}},{"cell_type":"code","source":"from PIL import Image\n\nim = Image.open(df['path'][1])\nwidth, height = im.size\nprint(width,height) \nim.show()","metadata":{"execution":{"iopub.status.busy":"2024-01-07T21:37:07.053054Z","iopub.execute_input":"2024-01-07T21:37:07.053364Z","iopub.status.idle":"2024-01-07T21:37:07.799802Z","shell.execute_reply.started":"2024-01-07T21:37:07.053320Z","shell.execute_reply":"2024-01-07T21:37:07.798751Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(np.asarray(im))","metadata":{"execution":{"iopub.status.busy":"2024-01-07T21:37:10.576253Z","iopub.execute_input":"2024-01-07T21:37:10.576601Z","iopub.status.idle":"2024-01-07T21:37:11.462876Z","shell.execute_reply.started":"2024-01-07T21:37:10.576551Z","shell.execute_reply":"2024-01-07T21:37:11.461487Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"The images are actually quite big. We will resize to a much smaller size.","metadata":{}},{"cell_type":"code","source":"bs = 64 #smaller batch size is better for training, but may take longer\nsz=224","metadata":{"execution":{"iopub.status.busy":"2024-01-07T21:37:19.335554Z","iopub.execute_input":"2024-01-07T21:37:19.335869Z","iopub.status.idle":"2024-01-07T21:37:19.420799Z","shell.execute_reply.started":"2024-01-07T21:37:19.335824Z","shell.execute_reply":"2024-01-07T21:37:19.419818Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tfms = get_transforms(do_flip=True,flip_vert=True,max_rotate=360,max_warp=0,max_zoom=1.1,max_lighting=0.1,p_lighting=0.5)\nsrc = (ImageList.from_df(df=df,path='./',cols='path') #get dataset from dataset\n        .split_by_rand_pct(0.2) #Splitting the dataset\n        .label_from_df(cols='diagnosis',label_cls=FloatList) #obtain labels from the level column\n      )\ndata= (src.transform(tfms,size=sz,resize_method=ResizeMethod.SQUISH,padding_mode='zeros') #Data augmentation\n        .databunch(bs=bs,num_workers=4) #DataBunch\n        .normalize(imagenet_stats) #Normalize     \n       )","metadata":{"execution":{"iopub.status.busy":"2024-01-07T21:38:27.664211Z","iopub.execute_input":"2024-01-07T21:38:27.664508Z","iopub.status.idle":"2024-01-07T21:38:43.427339Z","shell.execute_reply.started":"2024-01-07T21:38:27.664465Z","shell.execute_reply":"2024-01-07T21:38:43.426690Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data.show_batch(rows=3, figsize=(7,6))","metadata":{"execution":{"iopub.status.busy":"2024-01-07T21:39:20.807194Z","iopub.execute_input":"2024-01-07T21:39:20.807492Z","iopub.status.idle":"2024-01-07T21:40:06.952610Z","shell.execute_reply.started":"2024-01-07T21:39:20.807450Z","shell.execute_reply":"2024-01-07T21:40:06.951769Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import cohen_kappa_score\ndef quadratic_kappa(y_hat, y):\n    return torch.tensor(cohen_kappa_score(torch.round(y_hat), y, weights='quadratic'),device='cuda:0')","metadata":{"execution":{"iopub.status.busy":"2024-01-07T21:40:18.972336Z","iopub.execute_input":"2024-01-07T21:40:18.972686Z","iopub.status.idle":"2024-01-07T21:40:19.065170Z","shell.execute_reply.started":"2024-01-07T21:40:18.972614Z","shell.execute_reply":"2024-01-07T21:40:19.064154Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"learn = cnn_learner(data, base_arch=models.resnet50, metrics = [quadratic_kappa])","metadata":{"execution":{"iopub.status.busy":"2024-01-07T21:40:22.316298Z","iopub.execute_input":"2024-01-07T21:40:22.316597Z","iopub.status.idle":"2024-01-07T21:40:24.164953Z","shell.execute_reply.started":"2024-01-07T21:40:22.316551Z","shell.execute_reply":"2024-01-07T21:40:24.164263Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"learn.lr_find()\nlearn.recorder.plot(suggestion=True)","metadata":{"execution":{"iopub.status.busy":"2024-01-07T21:40:34.996073Z","iopub.execute_input":"2024-01-07T21:40:34.996376Z","iopub.status.idle":"2024-01-07T21:47:57.093938Z","shell.execute_reply.started":"2024-01-07T21:40:34.996332Z","shell.execute_reply":"2024-01-07T21:47:57.093101Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Here we can see that the loss decreases fastest around `lr=1e-2` so that is what we will use to train:","metadata":{}},{"cell_type":"code","source":"learn.fit_one_cycle(4,max_lr = 1e-2)","metadata":{"execution":{"iopub.status.busy":"2024-01-07T21:53:50.143762Z","iopub.execute_input":"2024-01-07T21:53:50.144094Z","iopub.status.idle":"2024-01-07T22:12:13.428475Z","shell.execute_reply.started":"2024-01-07T21:53:50.144050Z","shell.execute_reply":"2024-01-07T22:12:13.427406Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"learn.recorder.plot_losses()\nlearn.recorder.plot_metrics()","metadata":{"execution":{"iopub.status.busy":"2024-01-07T22:17:21.219604Z","iopub.execute_input":"2024-01-07T22:17:21.219977Z","iopub.status.idle":"2024-01-07T22:17:22.009011Z","shell.execute_reply.started":"2024-01-07T22:17:21.219924Z","shell.execute_reply":"2024-01-07T22:17:22.007914Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"learn.unfreeze()\nlearn.lr_find()\nlearn.recorder.plot(suggestion=True)","metadata":{"execution":{"iopub.status.busy":"2024-01-07T22:17:33.203820Z","iopub.execute_input":"2024-01-07T22:17:33.204119Z","iopub.status.idle":"2024-01-07T22:24:13.761256Z","shell.execute_reply.started":"2024-01-07T22:17:33.204077Z","shell.execute_reply":"2024-01-07T22:24:13.760036Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"learn.fit_one_cycle(6, max_lr=slice(1e-6,1e-3))","metadata":{"execution":{"iopub.status.busy":"2024-01-07T22:24:19.008052Z","iopub.execute_input":"2024-01-07T22:24:19.008362Z","iopub.status.idle":"2024-01-07T22:51:30.577614Z","shell.execute_reply.started":"2024-01-07T22:24:19.008317Z","shell.execute_reply":"2024-01-07T22:51:30.576761Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"learn.recorder.plot_losses()\nlearn.recorder.plot_metrics()","metadata":{"execution":{"iopub.status.busy":"2024-01-07T22:51:37.407062Z","iopub.execute_input":"2024-01-07T22:51:37.407376Z","iopub.status.idle":"2024-01-07T22:51:38.122793Z","shell.execute_reply.started":"2024-01-07T22:51:37.407329Z","shell.execute_reply":"2024-01-07T22:51:38.121665Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"learn.export()\nlearn.save('stage-2')","metadata":{"execution":{"iopub.status.busy":"2024-01-07T22:51:49.601062Z","iopub.execute_input":"2024-01-07T22:51:49.601359Z","iopub.status.idle":"2024-01-07T22:51:50.606688Z","shell.execute_reply.started":"2024-01-07T22:51:49.601316Z","shell.execute_reply":"2024-01-07T22:51:50.605780Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Let's evaluate our model:","metadata":{}},{"cell_type":"code","source":"interp = ClassificationInterpretation.from_learner(learn)\n\nlosses,idxs = interp.top_losses()\n\nlen(data.valid_ds)==len(losses)==len(idxs)","metadata":{"execution":{"iopub.status.busy":"2024-01-07T22:51:54.045984Z","iopub.execute_input":"2024-01-07T22:51:54.046322Z","iopub.status.idle":"2024-01-07T22:52:50.972273Z","shell.execute_reply.started":"2024-01-07T22:51:54.046261Z","shell.execute_reply":"2024-01-07T22:52:50.971240Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#interp.plot_confusion_matrix(figsize=(12,12), dpi=60)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"valid_preds = learn.get_preds(ds_type=DatasetType.Valid)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport os\nimport scipy as sp\nfrom functools import partial\nfrom sklearn import metrics\nfrom collections import Counter\nimport json","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class OptimizedRounder(object):\n    def __init__(self):\n        self.coef_ = 0\n\n    def _kappa_loss(self, coef, X, y):\n        X_p = np.copy(X)\n        for i, pred in enumerate(X_p):\n            if pred < coef[0]:\n                X_p[i] = 0\n            elif pred >= coef[0] and pred < coef[1]:\n                X_p[i] = 1\n            elif pred >= coef[1] and pred < coef[2]:\n                X_p[i] = 2\n            elif pred >= coef[2] and pred < coef[3]:\n                X_p[i] = 3\n            else:\n                X_p[i] = 4\n\n        ll = metrics.cohen_kappa_score(y, X_p, weights='quadratic')\n        return -ll\n\n    def fit(self, X, y):\n        loss_partial = partial(self._kappa_loss, X=X, y=y)\n        initial_coef = [0.5, 1.5, 2.5, 3.5]\n        self.coef_ = sp.optimize.minimize(loss_partial, initial_coef, method='nelder-mead')\n        print(-loss_partial(self.coef_['x']))\n\n    def predict(self, X, coef):\n        X_p = np.copy(X)\n        for i, pred in enumerate(X_p):\n            if pred < coef[0]:\n                X_p[i] = 0\n            elif pred >= coef[0] and pred < coef[1]:\n                X_p[i] = 1\n            elif pred >= coef[1] and pred < coef[2]:\n                X_p[i] = 2\n            elif pred >= coef[2] and pred < coef[3]:\n                X_p[i] = 3\n            else:\n                X_p[i] = 4\n        return X_p\n\n    def coefficients(self):\n        return self.coef_['x']","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"optR = OptimizedRounder()\noptR.fit(valid_preds[0],valid_preds[1])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"coefficients = optR.coefficients()\nprint(coefficients)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from fastai.core import *\nfrom fastai.basic_data import *\nfrom fastai.basic_train import *\nfrom fastai.torch_core import *\ndef _tta_only(learn:Learner, ds_type:DatasetType=DatasetType.Valid, num_pred:int=10) -> Iterator[List[Tensor]]:\n    \"Computes the outputs for several augmented inputs for TTA\"\n    dl = learn.dl(ds_type)\n    ds = dl.dataset\n    old = ds.tfms\n    aug_tfms = [o for o in learn.data.train_ds.tfms]\n    try:\n        pbar = master_bar(range(num_pred))\n        for i in pbar:\n            ds.tfms = aug_tfms\n            yield get_preds(learn.model, dl, pbar=pbar)[0]\n    finally: ds.tfms = old\n\nLearner.tta_only = _tta_only\n\ndef _TTA(learn:Learner, beta:float=0, ds_type:DatasetType=DatasetType.Valid, num_pred:int=10, with_loss:bool=False) -> Tensors:\n    \"Applies TTA to predict on `ds_type` dataset.\"\n    preds,y = learn.get_preds(ds_type)\n    all_preds = list(learn.tta_only(ds_type=ds_type, num_pred=num_pred))\n    avg_preds = torch.stack(all_preds).mean(0)\n    if beta is None: return preds,avg_preds,y\n    else:            \n        final_preds = preds*beta + avg_preds*(1-beta)\n        if with_loss: \n            with NoneReduceOnCPU(learn.loss_func) as lf: loss = lf(final_preds, y)\n            return final_preds, y, loss\n        return final_preds, y\n\nLearner.TTA = _TTA","metadata":{"execution":{"iopub.status.busy":"2024-01-07T23:14:09.649274Z","iopub.execute_input":"2024-01-07T23:14:09.649564Z","iopub.status.idle":"2024-01-07T23:14:09.749215Z","shell.execute_reply.started":"2024-01-07T23:14:09.649523Z","shell.execute_reply":"2024-01-07T23:14:09.748303Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_df = pd.read_csv('../input/aptos2019-blindness-detection/sample_submission.csv')\nsample_df.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"learn.data.add_test(ImageList.from_df(sample_df,'../input/aptos2019-blindness-detection',folder='test_images',suffix='.png'))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"preds,y = learn.TTA(ds_type=DatasetType.Test)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_predictions = optR.predict(preds, coefficients)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_df.diagnosis = test_predictions.astype(int)\nsample_df.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_df.to_csv('submission.csv',index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}