{"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\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":"import warnings\nwarnings.filterwarnings(\"ignore\")","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import zipfile\n\n# Will unzip the files so that you can see them..../input/dogs-vs-cats/test1.zip\nwith zipfile.ZipFile(\"../input/dogs-vs-cats/test1.zip\",\"r\") as z:\n    z.extractall(\".\")\n\nwith zipfile.ZipFile(\"../input/dogs-vs-cats/train.zip\",\"r\") as z:\n    z.extractall(\".\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Understanding the data","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import cv2\nimport matplotlib.pyplot as plt\npath = \"/kaggle/working/train\"\nimage_name = os.listdir(path)\nimage_name[:10]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img = cv2.imread(os.path.join(path, image_name[7]))\nimg = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\nprint(img.shape)\nplt.imshow(img)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Implementing Fast.Ai library","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from fastai.vision import *","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"path = Path('/kaggle/working/train')\npath","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fn_paths = [path/name for name in image_name]; fn_paths[:2]\n#str(fn_path)\n#fn_path = [path/image_name]\ncategory = str(fn_paths[17]).split('.')[0]\ncategory[22:]\n#if category == 'dog':\n#    print(1)\n#else:\n#    print(0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"tfms = get_transforms(do_flip=True)\nbs = 64","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# **The dataset requires that we classify all dogs to 1 and  cats to 0**","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_labels(filename):\n    category = str(filename).split('.')[0]\n    if category[22:] == 'dog':\n        return 1\n    else:\n        return 0\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data = ImageDataBunch.from_name_func(path, fn_paths, label_func=get_labels,valid_pct=0.2, ds_tfms=tfms, size=224,bs=bs)\ndata = data.normalize(imagenet_stats)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.show_batch(rs=3, figsize=(7,8))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.classes, data.c, len(data.train_ds), len(data.valid_ds)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Creating a pretrained Resnet-34 DNN that was trained on imagenet dataset","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"learn = cnn_learner(data, models.resnet34, metrics=error_rate)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Training the head network to identify dogs and cats","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.fit_one_cycle(4)\nlearn.recorder.plot_losses()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.save('stage-1')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.load('stage-1');","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.unfreeze()\nlearn.lr_find()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.recorder.plot()\nlearn.recorder.plot_lr()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.fit_one_cycle(2, max_lr=slice(1e-5,2e-4))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.save('stage-2')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.load('stage-2');","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"interp = ClassificationInterpretation.from_learner(learn)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Obsevering the Losses","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"interp.plot_confusion_matrix()","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":"path = Path('/kaggle/working/train')\nlearn.export()\nlearn = load_learner(path)\n#path = '/kaggle/working/test1'\n#learn = load_learner(learn.load('stage-2'),test=ImageItemList.from_folder(path))\n#preds = learn.get_preds(ds_type=DatasetType.Test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_path = Path('/kaggle/working/test1')\nlearn = load_learner(path, test=ImageList.from_folder(test_path))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = learn.get_preds(ds_type=DatasetType.Test)\npreds","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y = np.argmax(to_np(preds[0]),axis=1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Comparison of predicted output with the input of the test data","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"n= 0\ny[n]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img = ImageList.from_folder(test_path)\n#learn.predict(img)\nimg[n]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_img_name = os.listdir(test_path)\ntest_img_name[:10]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Submission","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"ID = pd.Series(test_img_name)\nlabel = pd.Series(y)\nsubmit = pd.DataFrame({ 'id': ID, 'label': label })\nsubmit.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submit.to_csv('submission.csv', index=False)","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}