{"cells":[{"metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","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 the files in the input directory\n\nimport os, sys\nprint(os.listdir(\"../input/aptos2019-blindness-detection/\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"%reload_ext autoreload\n%autoreload 2\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from zipfile import ZipFile\nfrom fastai.vision import *\nfrom fastai.metrics import error_rate\nfrom fastai.callbacks import *\nimport cv2","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"bs = 64\n\n!ls","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# copy pretrained weights for resnet50 to the folder fastai will search by default\nPath('/tmp/.cache/torch/checkpoints/').mkdir(exist_ok=True, parents=True)\n!cp '../input/resnet50/resnet50.pth' '/tmp/.cache/torch/checkpoints/resnet50-19c8e357.pth'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n#doc(ImageDataBunch)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"PATH = Path('../input/aptos2019-blindness-detection')\n\ndf_train = pd.read_csv(PATH/'train.csv', dtype={'id_code':str, 'diagnosis':int})\ndf_test = pd.read_csv(PATH/'test.csv')\ndf_train['zc'] = 0\ndf_train['zc'].loc[(df_train['diagnosis']==0)] = 0\ndf_train['zc'].loc[~(df_train['diagnosis']==0)]= 1\ndf_train['oc'] = 0\ndf_train['oc'].loc[(df_train['diagnosis']==1)] = 0\ndf_train['oc'].loc[~(df_train['diagnosis']==1)]= 1\ndf_train['tc'] = 0\ndf_train['tc'].loc[(df_train['diagnosis']==2)] = 0\ndf_train['tc'].loc[~(df_train['diagnosis']==2)]= 1\ndf_train['thc'] = 0\ndf_train['thc'].loc[(df_train['diagnosis']==3)] = 0\ndf_train['thc'].loc[~(df_train['diagnosis']==3)]= 1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(df_train.head(5))\ndf_train.diagnosis.value_counts()\ndf_train.hist()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# # create Stratified validation split (12.50%)\n# #fastai does not include stratify option in train test data split, however according to the lecturer, \n# #imbalance classifiers will be handle by the deep learning quite well, not sure this is true in this case\n# from sklearn.model_selection import StratifiedKFold\n# cv = StratifiedKFold(n_splits=8, random_state=42)\n# tr_ids, val_ids = next(cv.split(df_train.id_code, df_train.diagnosis))\n# print(len(tr_ids), len(val_ids))\n# _ = df_train.loc[val_ids].hist()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# print(val_ids)\n# print(tr_ids)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# import zipfile\n# with zipfile.ZipFile('./train_images.zip', 'r') as zip_ref:\n#     zip_ref.extractall('./train_images')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# with zipfile.ZipFile('./test_images.zip', 'r') as zip_ref:\n#     zip_ref.extractall('./test_images')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# def crop_image_from_gray(img,tol=7):\n#     if img.ndim ==2:\n#         mask = img>tol\n#         return img[np.ix_(mask.any(1),mask.any(0))]\n#     elif img.ndim==3:\n#         gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n#         mask = gray_img>tol\n        \n#         check_shape = img[:,:,0][np.ix_(mask.any(1),mask.any(0))].shape[0]\n#         if (check_shape == 0): # image is too dark so that we crop out everything,\n#             return img # return original image\n#         else:\n#             img1=img[:,:,0][np.ix_(mask.any(1),mask.any(0))]\n#             img2=img[:,:,1][np.ix_(mask.any(1),mask.any(0))]\n#             img3=img[:,:,2][np.ix_(mask.any(1),mask.any(0))]\n#     #         print(img1.shape,img2.shape,img3.shape)\n#             img = np.stack([img1,img2,img3],axis=-1)\n#     #         print(img.shape)\n#         return img\n    \n# IMG_SIZE = 512\n\n# def _load_format(path, convert_mode, after_open)->Image:\n#     image = cv2.imread(path)\n#     image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n#     image = crop_image_from_gray(image)\n#     image = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\n#     image=cv2.addWeighted ( image,4, cv2.GaussianBlur( image , (0,0), 10) ,-4 ,128)\n                    \n#     return Image(pil2tensor(image, np.float32).div_(255)) #return fastai Image format\n\n# vision.data.open_image = _load_format","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# create image data bunch\n# create first image list using datafram, than split train and valid dataset according to stratified indx and lst lable imagelist with classes\ndata = ImageDataBunch.from_df('./', \n                              df=df_train, \n                              valid_pct=0.2,\n#                               folder=\"../input/aptos2015/resizedtrain15\",\n                              folder=\"../input/aptos2019-blindness-detection/train_images\",\n                              suffix=\".png\",\n                              ds_tfms=get_transforms(flip_vert=True, max_warp=0),\n                              size=224,\n                              bs=128, \n                              num_workers=32,\n                             label_col='zc').normalize(imagenet_stats)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#create data using fastai ImageDataBunch function, create from image list with lable.\n#simple data augmentation with flip and rotate since this is an eyeball image, the image is normalized using default imagenet_stats, another possible \n#option would be use the aptos19_stats, which not sure how to derive from yet\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# data.show_batch(rows=3, figsize=(7,6))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.classes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"kappa = KappaScore()\nkappa.weights = \"quadratic\"\nlearnz = cnn_learner(data, models.resnet50, metrics=[error_rate, kappa],\n                    callback_fns = [\n                                partial(EarlyStoppingCallback, monitor='kappa_score', min_delta=0.001, patience=2),\n                                partial(ReduceLROnPlateauCallback),\n#                               partial(GradientClipping, clip=0.2),\n                                partial(SaveModelCallback, every = 'improvement', monitor='kappa_score', name='bestmodel')],\n                    model_dir=\"/tmp/model/\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learnz.lr_find()\nlearnz.recorder.plot(suggestion=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learnz.fit_one_cycle(10,1e-2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learnz.unfreeze()\nlearnz.fit_one_cycle(15,slice(1.32e-6,1.32e-3))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_df = pd.read_csv('../input/aptos2019-blindness-detection/sample_submission.csv')\nsample_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learnz.data.add_test(ImageList.from_df(sample_df,'../input/aptos2019-blindness-detection',folder='test_images',suffix='.png'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds,y = learnz.get_preds(ds_type=DatasetType.Test)\nsample_df.diagnosis = preds.argmax(1)\nsample_df.diagnosis.value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# log_preds,y = learn2.TTA(ds_type=DatasetType.Test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# sample_df.diagnosis = np.argmax(log_preds.numpy(), axis=1)\n# sample_df.head(50)\n# sample_df.diagnosis.hist()\n# sample_df.diagnosis.value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# sample_df.to_csv('submission.csv',index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!mv {learnz.model_dir}/*.pth .\nos.listdir()","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.7.3"}},"nbformat":4,"nbformat_minor":1}