{"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\nimport matplotlib.pyplot as plt # 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, shutil\nfor 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 5GB 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":{"trusted":true},"cell_type":"code","source":"#hide\n!pip install -Uqq fastbook\nimport fastbook\nfastbook.setup_book()\n\nfrom fastai.vision.widgets import *\nfrom fastai.data.all import *\nfrom fastai.vision.core import *\nfrom fastbook import *\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Directory Paths\nflower_path = '/kaggle/input/104-flowers-garden-of-eden/jpeg-512x512'\nTRAIN_DIR  = flower_path + '/train/'\nVAL_DIR  = flower_path + '/val'\nTEST_DIR  = flower_path + '/test/'\nNew_TRAIN_DIR = flower_path + '/train1/'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"flowers = DataBlock(\n    blocks=(ImageBlock, CategoryBlock), \n    get_items=get_image_files, \n    splitter=RandomSplitter(valid_pct=0.2, seed=42),\n    get_y=parent_label,\n    item_tfms=Resize(128))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dls = flowers.dataloaders(TRAIN_DIR, batch_size=32)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dls.train.show_batch(max_n=4, nrows=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn = cnn_learner(dls, resnet18, metrics=error_rate)\nlearn.fine_tune(4)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"interp = ClassificationInterpretation.from_learner(learn)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"correct = 0\ntotal = len(learn.dls.valid_ds)\ncorrect = (interp.targs == interp.preds.argmax(axis = 1)).sum()\naccuracy = correct.float()/total","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"accuracy","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"interp.plot_top_losses(6, nrows=6)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Base model achieved a benchmark of 78.2%. Next we try Augmentations along with Cross Validation set.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"flowers = flowers.new(\n    item_tfms=RandomResizedCrop(224, min_scale=0.5),\n    batch_tfms=aug_transforms())\ndls = flowers.dataloaders(TRAIN_DIR, batch_size = 32)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn = cnn_learner(dls, resnet18, metrics=error_rate)\nlearn.fine_tune(10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"interp = ClassificationInterpretation.from_learner(learn)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"correct = 0\ntotal = len(learn.dls.valid_ds)\ncorrect = (interp.targs == interp.preds.argmax(axis = 1)).sum()\naccuracy = correct.float()/total","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"accuracy","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Data Augmentation gave us significant improvement in accuracy from 78 to 89.37%","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_ids = []\npredictions = []\nfor dirname, _, filenames in os.walk(TEST_DIR):\n    for filename in filenames:\n          k = plt.imread(os.path.join(dirname,filename))\n          pred = learn.predict(k)[1]\n          predictions.append(pred)\n          test_ids.append(filename.split(\".\")[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Write the submission file\nnp.savetxt(\n    '/kaggle/working/submission.csv',\n    np.rec.fromarrays([test_ids, predictions]),\n    fmt=['%s', '%d'],\n    delimiter=',',\n    header='id,label',\n    comments='',\n)","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}