{"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":"881055b5d1b6edc20d4f578b01ae57b126dc87f9"},"cell_type":"markdown","source":"## Load general packages"},{"metadata":{"_uuid":"5f16a6a0848f46d8d551ee76c22dd761c8190f46","trusted":true,"collapsed":true},"cell_type":"code","source":"%matplotlib inline\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\nfrom PIL import ImageFile \nimport numpy as np\nimport os \nimport cv2\nfrom tqdm import tqdm_notebook\nfrom random import shuffle\nimport pandas as pd\nimport random\nfrom tqdm import tqdm\nimport seaborn as sns\nimport math","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"b732a5082bcd1b3986fcad10e0fffb842017e86a"},"cell_type":"markdown","source":"## Load Keras packages"},{"metadata":{"trusted":true,"_uuid":"64ebeb06a96cb0643ae24bd0f277360a9cd2eacd","collapsed":true},"cell_type":"code","source":"import keras\nfrom keras import applications\nfrom keras import optimizers\nfrom keras import backend as K\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D,GlobalMaxPooling2D\nfrom keras.layers import Activation, Dropout, Flatten, Dense\nfrom keras.constraints import maxnorm\nfrom keras.optimizers import SGD\nfrom keras.utils import np_utils\nfrom keras.callbacks import Callback,ModelCheckpoint\nfrom keras.applications import VGG16\nfrom keras.applications import ResNet50\nfrom keras.models import load_model\nfrom keras.preprocessing.image import load_img","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"cba4b4b3e9743e6a8ec11eb02b2ea25ec8f1c118"},"cell_type":"markdown","source":"## Intialize variables\nThe image size is 224.The images are stored in two folders, train and test and there are two image classes: Dog and Cat.\nMy plan is to use all training data (25,000 images) of which 20,000 imgaes for  traning and 5000 for valdation of the models.\nWe will use a subset of the training data set (20,000 images). From the training set,80% will be used for training, 20% for validation."},{"metadata":{"trusted":true,"_uuid":"977057f5a6c4a36864ad0cca7c094dafaea07c9e","collapsed":true},"cell_type":"code","source":"batch_size = 32\nepochs = 20\nnum_classes = 2\nnum_t_samples = 20000\nnum_v_samples = 5000\npath='../input/dogs-vs-cats-redux-kernels-edition/'\ndir= '../input/dogscats/data/data/'\ntrain_data_path = path+'train/'\ntest_data_path =  path+'test/'\ntrain_data_dir = dir+'train/'\nvalidation_data_dir=dir+'validation/'\ntest_dir='../input/dogscatstest/test1/test1/'\nimg_size=224","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a38dda5fcb6fcd84600d34d13a1f0ee87790ebfd","collapsed":true},"cell_type":"code","source":"#Process training data to make it ready for fitting.\ntrain_datagen = ImageDataGenerator(rescale=1. / 255,shear_range=0.2,zoom_range=0.2,horizontal_flip=True)\ntrain_generator = train_datagen.flow_from_directory(train_data_dir,target_size=(img_size, img_size),\n                                                    batch_size=batch_size,class_mode='categorical')\ntest_datagen = ImageDataGenerator(rescale=1./255)\ntest_generator = test_datagen.flow_from_directory(test_dir,target_size=(img_size, img_size),batch_size=batch_size,\n                                                  class_mode='categorical',shuffle=False)\nfilename=test_generator.filenames","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"5a1a10e706a2e64d20c35755f24b90f4c21b1706"},"cell_type":"code","source":"model=load_model('../input/resnet50-all/resnet50_model.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"cab76c493a0abd0fba89c9ecfda1b032a220009e","collapsed":true},"cell_type":"code","source":"test_generator.reset()\npred=model.predict_generator(test_generator,steps=math.ceil(test_generator.samples/test_generator.batch_size),verbose=1)\npredicted_class_indices=np.argmax(pred,axis=1)\nlabels = (train_generator.class_indices)\nlabels = dict((v,k) for k,v in labels.items())\npredictions = [labels[k] for k in predicted_class_indices]\nnew_preds=[]\nfor i in range(len(predictions)):\n    if predictions[i]=='dogs':\n        new_preds.append('dog')\n    else:\n        new_preds.append('cat')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"6e35e0031c1cd135ebfd0211e267ced20ceaaa65","collapsed":true},"cell_type":"code","source":"predicted_class_indices","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"14e8789d42def9c714aea66b322ea968b0adb3ce"},"cell_type":"code","source":"def display_testdata(testdata,filenames):\n    f, ax = plt.subplots(5,5, figsize=(15,15))\n    i=0\n    for a,b in zip(testdata,filenames):\n        pred_label=a\n        fname=b\n        title = 'Prediction :{}'.format(pred_label)   \n        original = load_img('{}/{}'.format(test_dir,fname))\n        ax[i//5,i%5].axis('off')\n        ax[i//5,i%5].set_title(title)\n        ax[i//5,i%5].imshow(original)\n        i=i+1\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8fec05fd31d40c4350b6d23900b195d6cc9af6d3","collapsed":true},"cell_type":"code","source":"display_testdata(new_preds[11100:11125],filename[11100:11125])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"80b2f159942f3b1cc52fec7c5cda9bc0ddf83836"},"cell_type":"code","source":"def create_submission():\n    labels=[]\n    file_index=[]\n    for a,b in zip(predicted_class_indices,filename):\n        pred_label=a\n        fname=b[5:]\n        fname=fname.split('.')[0]\n        labels.append(pred_label)\n        file_index.append(fname)\n    results=pd.DataFrame({\"id\":file_index,\n                      \"label\":labels})\n    results.to_csv(\"submission.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"00c7d72553c9d588016d41a2090b5302da9b94f4","collapsed":true},"cell_type":"code","source":"create_submission()","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}