{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"collapsed":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)\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\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"4a6048726b4d97d54a36ca6c1a5d6bda3eb0fb15"},"cell_type":"markdown","source":"**First lets import all fastai needed tools**"},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","collapsed":true,"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"from fastai.imports import *\nfrom fastai.transforms import *\nfrom fastai.conv_learner import *\nfrom fastai.model import *\nfrom fastai.dataset import *\nfrom fastai.sgdr import *\nfrom fastai.plots import *","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"18252607c60288ab98a2af5f3a498298b4ddfbb4"},"cell_type":"markdown","source":"**Now we know that the train and test images are split across two folders lets categorically define them**"},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"0c2fde209400ab27443f56d37ea64994e7f83345"},"cell_type":"code","source":"train='../input/dogs-vs-cats-redux-kernels-edition/train'\ntest='../input/dogs-vs-cats-redux-kernels-edition/test'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"502213ee17bdbced0b4d1689d9ea019146160ade"},"cell_type":"markdown","source":"**We will use a csv to get the Image data object so first lets get all the details of the training dataset on to a csv**"},{"metadata":{"trusted":true,"_uuid":"fd94dcba51d08c54f6221ab9dc725ebccccb82a6","collapsed":true},"cell_type":"code","source":"data = []\nfor files in sorted(os.listdir(train)):\n    data.append((files))\n\ndf = pd.DataFrame(data, columns=['img'])\ndf['tag']=df['img'].astype(str).str[:3]\ndf['tag'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"b975743ab1220e8c41369e395a0b87558753b585"},"cell_type":"markdown","source":"**Lets store this dataframe as a csv somewhere**"},{"metadata":{"trusted":true,"_uuid":"f87ccbfb3570bde673ffe1d03fdf754008b38056","collapsed":true},"cell_type":"code","source":"!mkdir ./data\ndf.to_csv('./data/catdog.csv',index=False)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"9550c9ac379381c90d97825cb9844ef4f6847162"},"cell_type":"markdown","source":"**Lets get a validation sample that is 20% of all training data should be marked as validation which will be used to validate how our DL model looks**"},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"a5b8ba8a1eda9c69e0ca27b65780732bb27a49a5"},"cell_type":"code","source":"label_csv = './data/catdog.csv'\nn = len(list(open(label_csv)))-1\nval_idxs = get_cv_idxs(n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4907e39261e43676a1fe7f960b00c27d98be385b","collapsed":true},"cell_type":"code","source":"import gc\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"9181e50c14c764f8318c83b9b831f737af367f66"},"cell_type":"markdown","source":"**Lets create a  data object using really cool fastai API**"},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"3fdb571ed66967b27b90f3685fc2dbf723cf986e"},"cell_type":"code","source":"PATH=''","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"782b96aa4f58a6834b83d24dd4d8245cc0bab10f"},"cell_type":"code","source":"arch=resnet34\nsz=224\ndata = ImageClassifierData.from_csv(PATH,train,label_csv,tfms=tfms_from_model(arch, sz),test_name=test)\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"be4ad7f16c8ca615ca7c12c24061274dd27a02d7"},"cell_type":"markdown","source":"**Now we don't have the model(Resnet34) we will use for transfer learning in this instance set up as fastai/pytorch expect it to be so lets do that**"},{"metadata":{"trusted":true,"_uuid":"b9979ab2eeeea5639590bbf77a51d0b1de6a0ae2","collapsed":true},"cell_type":"code","source":"#import pathlib\n#data.path = pathlib.Path('.')\nfrom os.path import expanduser, join, exists\nfrom os import makedirs\ncache_dir = expanduser(join('~', '.torch'))\nif not exists(cache_dir):\n    makedirs(cache_dir)\nmodels_dir = join(cache_dir, 'models')\nif not exists(models_dir):\n    makedirs(models_dir)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8a55c65856e8516e3b95a404f0b464721871bfc6","collapsed":true},"cell_type":"code","source":"!ls ~/.torch   #Now we have a .torch/models directory in the root folder ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"7964d71c5358fc3ce66513af75351602fba4f3ab"},"cell_type":"code","source":"#Lets copy the weights to the folder\n\n!cp ../input/resnet34/resnet34.pth /tmp/.torch/models/resnet34-333f7ec4.pth\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c6866cdf900d3f2ea7374f0faf55c064298b9d7c","collapsed":true},"cell_type":"code","source":"#Change the true path of the model\nimport pathlib\ndata.Path = pathlib.Path('.')","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"7c3da21dc37e3aca334f1e0186db96a7575865b0"},"cell_type":"markdown","source":"**Now we  pre-compute the weights of Resnet34 and fit the model**"},{"metadata":{"trusted":true,"_uuid":"98e66a8f4a72940d64cdb0dd725b64fc9a29f5e4","collapsed":true},"cell_type":"code","source":"#learn = ConvLearner.pretrained(arch, data, precompute=True)\n#learn.fit(0.01, 2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"c53ce0c6e227b15302e8c9c7e8b8d776e98a3c85"},"cell_type":"code","source":"#gc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b3742ad69675da34a3a077c52a7805be56123ac3","collapsed":true},"cell_type":"code","source":"#Two more epochs\n#learn.fit(0.01, 2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"5260944dfcb710c52ee58637feda9389b4189e9a"},"cell_type":"code","source":"#gc.collect()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"baac5e68d597a269e40c36a5625a7b6f64aed0a4"},"cell_type":"markdown","source":"**Lets quickly look at the predictions before delving deeper into the details **"},{"metadata":{"trusted":true,"_uuid":"8a1e9da408e07729495839762c14522ea211a28c","collapsed":true},"cell_type":"code","source":"#log_preds, y = learn.TTA(is_test=True)\n#probs = np.mean(np.exp(log_preds),0)\n#ds=pd.DataFrame(probs)\n#ds.columns=data.classes\n#ds.insert(0,'id',[o.rsplit('/', 1)[1] for o in data.test_ds.fnames])\n#subm=pd.DataFrame()\n#subm['id']=ds['id']\n#subm['cat']=ds['cat']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b72e288cc0207cfcc2017eae8a462740fe14c4bd","collapsed":true},"cell_type":"code","source":"#subm=pd.DataFrame()\n#subm['id']=ds['id']\n#subm['cat']=ds['cat']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"cd2fd7282331fbfad581e3f8cab3326e7053c8e3"},"cell_type":"code","source":"#subm.to_csv('../workingsubmission.csv',index=False)","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-output":true,"trusted":true,"_uuid":"a1135bd97f03485a4c9eeb5f24958967f3a7f39d","collapsed":true},"cell_type":"code","source":"#subm.to_csv('./data/submission.gz',compression='gzip',index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a8df39522ac2b15ddead1d67f079cd825980807e","collapsed":true},"cell_type":"code","source":"#!ls ./data","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d3dc7b9c84f77c15664c0bb92786da2a940320b7","collapsed":true},"cell_type":"code","source":"#subm","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"5103b9ef279bdad2b1a2fe50b498053542963ef3"},"cell_type":"code","source":"","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}