{"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\n\nfrom fastai.vision.all import *\n\n# learning by doing: referenced from https://github.com/fastai/fastbook/blob/master/06_multicat.ipynb\n\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"# get and define the paths\ncassavaPath = '../input/cassava-leaf-disease-classification/'\ncassavaOutputPath = './'\n\ncassavaModelPath = '../input/cassavleafdiseaseclassificationpretrained/'\n\n# load in the data\ndf = pd.read_csv(cassavaPath+'train.csv')\ndf['label'] = df['label'].astype(str)\n\n# check if it looks legit\ndf.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# quick check how the data is distributed\ndf['label'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#define the path to the input files and to the respective labels\ndef get_x(r): return cassavaPath+'train_images/'+r['image_id']\ndef get_y(r): return r['label']\n\ndblock = DataBlock(blocks=(ImageBlock, CategoryBlock),\n                   splitter=RandomSplitter(), #use the default random splitter to split between train and test set\n                   get_x=get_x,\n                   get_y=get_y,\n                   item_tfms=Resize(600),\n                   batch_tfms=aug_transforms())\n\n# just to check how the dataset looks like\ndsets = dblock.datasets(df)\ndsets.train[0]\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# use dataloaders to prepare the pytorch batches\ndls = dblock.dataloaders(df)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# quick check how the batches look like and if the labels match with the input data\ndls.show_batch(nrows=3, ncols=3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# kaggle notebook does not have the ressources. I trained it with my Azure DSVM. Code is here for reference\n\n#learn = cnn_learner(dls, resnet34, metrics=error_rate)\n#learn.fine_tune(7, base_lr=3e-3) #epoch number and learn rate are a wild guess. I'm still a beginner # ;)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# kaggle notebook does not have the ressources. I trained it with my Azure DSVM. Code is here for reference\n\n#learn.export('CassavaDiseaseModelResnet34.pkl') ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# kaggle notebook does not have the ressources. I trained it with my Azure DSVM. Code is here for reference. \n# This is to check how good/bad the model performs on the test set. To be honest a lot of confusions ... does not perform so well.\n# possibly this could be improved by having a form of segmentation pre-processing ... ? So that the model really focuses on the plants and not on soil and sky.\n\n#interp = ClassificationInterpretation.from_learner(learn)\n#interp.plot_confusion_matrix(figsize=(5,5))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# kaggle notebook does not have the ressources. I trained it with my Azure DSVM. Code is here for reference. \n# Just to check how some examples look like\n\n#learn.show_results()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# load my pre-trained model. commented code above in case someone wants to reproduce it\n\nlearn = load_learner(cassavaModelPath+'CassavaDiseaseModelResnet34.pkl')\n# move the model in the output folder (the first submission failed. Not sure if it is related to the access to the pretrained model)\nlearn.export(cassavaOutputPath+'CassavaDiseaseModelResnet34.pkl')\nlearn = load_learner(cassavaOutputPath+'CassavaDiseaseModelResnet34.pkl')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('Computing predictions...')\ntest_files = get_image_files(cassavaPath+'test_images')\n\n\npredictions_ResultArray = [None for tempX in range(len(test_files))]\npredictions_InputArray = [None for tempX in range(len(test_files))]\n\nfor test_idx in range(0,len(test_files)):\n    predictions = learn.predict(test_files[test_idx])\n    head, tail = os.path.split(test_files[test_idx])\n    predictions_ResultArray[test_idx] = int(predictions[0])\n    predictions_InputArray[test_idx] = tail\n     \nnp.savetxt(cassavaOutputPath+'submission.csv', np.rec.fromarrays([predictions_InputArray, predictions_ResultArray]), fmt=['%s', '%d'], delimiter=',', header='image_id,label', comments='')\n    \n\n    \n!head submission.csv","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# double check if the newly generated output file matches the template result file\n\ndf_sample_submission = pd.read_csv('../input/cassava-leaf-disease-classification/sample_submission.csv')\ndf_exact_submission = pd.read_csv(cassavaOutputPath+'submission.csv')\n\n#print(df_sample_submission)\n#print(df_exact_submission)\n\nprint(df_sample_submission.compare(df_exact_submission))\n\nprint(df_sample_submission.equals(df_exact_submission))\n","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}