{"cells":[{"metadata":{},"cell_type":"markdown","source":"### Dogs vs cats using fast ai v3\n\nI wanted to make this notebook as a reference for end to end submission to the competition.\nOptimisation is yet to be done.","execution_count":null},{"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\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":{},"cell_type":"markdown","source":"### Unzip files and put them in path","execution_count":null},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"from fastai.vision import *","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Config.data_path()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"path = Config.data_path()/'dogs_vs_cats'\npath.mkdir(parents=True, exist_ok=True)\npath","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# unzip test and train to path\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        if ('zip' in filename):\n            file = os.path.join(dirname, filename)\n            !unzip -q -n {file} -d {path}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!dir {path}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!dir {path}/'train'\n\n# observation: we can use the first part of the file name before the dot to extract the labels","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_path = path/'train'\ntest_path = path/'test'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from fastai.metrics import error_rate\nnp.random.seed(42)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Fnames","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"fnames = get_image_files(train_path)\nfnames[:5]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Creating image databunch from lists","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"categories = []\nfilenames = os.listdir(train_path)\n\nfor filename in filenames:\n    if('dog.' in filename):\n        categories.append(1)\n    else:\n        categories.append(0)\n\n# 1 for dogs\n# 0 for cats","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import warnings\nwarnings.filterwarnings('ignore')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data = ImageDataBunch.from_lists(train_path, fnames, ds_tfms=get_transforms(), size=224, bs=64, labels=categories)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.classes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.show_batch(rows=3,figsize=(7,6))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Using a CNN","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"learn = cnn_learner(data, models.resnet34, metrics=error_rate)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.fit_one_cycle(4)\n# PIL.UnidentifiedImageError: cannot identify image file '/root/.fastai/data/dogs_vs_cats/train/dog.2370.jpg'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.save('stage1-dogsvscats')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Getting test data","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"test_images = get_image_files(test_path)\ntest_images[:5]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.DataFrame(os.listdir(test_path), columns=['ids'])\nsubmission['label'] = 0\nsubmission['id'] = 1","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Prediction","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"count = 0\nfor imgpath in test_images:\n    img = open_image(imgpath)\n    pred = learn.predict(img)\n    if(str(pred[0]) != '1'):\n        submission['label'][count] = 0\n    else:\n        submission['label'][count] = 1\n    count = count +1\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Submission","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"submission","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"count = 0\nfor imgpath in test_images:\n    submission['id'][count] = count + 1\n    count  = count + 1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission[['id', 'label']].to_csv('submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!dir /kaggle/working","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#!mv outputs.csv /kaggle/working","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}