{"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)\nfrom fastai.vision import *\nfrom fastai.metrics import error_rate\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\nprint(os.listdir(\"../input\"))\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(os.listdir(\"../input/aptos2019-blindness-detection\"))","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":"df_img=pd.read_csv('../input/aptos2019-blindness-detection/train.csv')\ndf_img.head(5)\nfile = '../input/aptos2019-blindness-detection/train_images/'+df_img.iloc[0,0]+'.png'\nprint(file)\npicture=plt.imread(file)\npicture.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"PATH = Path('../input/aptos2019-blindness-detection/')\ndata_dir = '../input/aptos2019-blindness-detection/'\ntrain_df = pd.read_csv(os.path.join(data_dir,'train.csv'))\nadd_extension = lambda x: str(x) + '.png'\nadd_dir = lambda x: os.path.join('train_images', x)\ntrain_df['id_code'] = train_df['id_code'].apply(add_extension)\ntrain_df['id_code'] = train_df['id_code'].apply(add_dir)\nprint(train_df.shape)\ndata = (ImageList.from_df(train_df,PATH)\n        #Where to find the data? \n        .split_by_rand_pct(0.20,seed=44)\n        #How to split in train/valid? -> randomly with the default 20% in valid\n        .label_from_df()\n        #How to label? -> use the second column of the csv file and split the tags by ' '\n        #Data augmentation? -> use tfms with a size of 128\n        .transform(get_transforms(do_flip=True,flip_vert= True,max_zoom=1.1, max_lighting=0.2, max_warp=0.2, ),size=500)\n        .databunch(bs=8)\n        .normalize(imagenet_stats))                          \n        #Finally -> use the defaults for conversion to databunch\ndata","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(data.classes)\ndata.show_batch(rows=3, figsize=(5,5))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls '../input/densenet201'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"kappa = KappaScore()\nkappa.weights = \"quadratic\"\nPath('/tmp/.cache/torch/checkpoints/').mkdir(exist_ok=True, parents=True)\n!cp ../input/densenet201/densenet201.pth /tmp/.cache/torch/checkpoints/densenet201-c1103571.pth\n\nlearn = cnn_learner(data, models.densenet201, metrics=[accuracy,kappa],model_dir='/kaggle',pretrained=True)\nlearn.summary()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.lr_find()\nlearn.recorder.plot()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lr = 1e-2\nlearn.fit_one_cycle(1, slice(lr))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"interp = ClassificationInterpretation.from_learner(learn)\nlosses,idxs = interp.top_losses()\nlen(data.valid_ds)==len(losses)==len(idxs)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"interp.plot_top_losses(9, figsize=(15,11))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.unfreeze()\nlearn.lr_find()\nlearn.recorder.plot()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.fit_one_cycle(10, slice(1e-6,1e-3))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.save(\"trained_model\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_df = pd.read_csv(PATH/'sample_submission.csv')\nsample_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.data.add_test(ImageList.from_df(sample_df,PATH,folder='test_images',suffix='.png'))\npreds,y = learn.get_preds(DatasetType.Test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_df.diagnosis = preds.argmax(1)\nsample_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_df.to_csv('submission.csv',index=False)","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}