{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\nfrom zipfile import ZipFile\nimport matplotlib.pyplot as plt\nfrom keras.applications.inception_resnet_v2 import InceptionResNetV2\nfrom keras.layers import Dense, Dropout, InputLayer\nfrom keras import Sequential\nfrom keras.callbacks import EarlyStopping, LearningRateScheduler","execution_count":null,"outputs":[]},{"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[:10]:\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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train_dir = '/kaggle/input/dogs-vs-cats/train.zip'\nos.mkdir('/kaggle/working/tmp')\nwith ZipFile(train_dir) as zipfile:\n    zipfile.extractall('/kaggle/working/tmp')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"filenames = []\nclass_name = []\nfor name in os.listdir('/kaggle/working/tmp/train'):\n    filenames.append(name)\n    class_name.append(name.split('.')[0])\ntrain_df = pd.DataFrame(dict({'filename' : filenames, 'class' : class_name}))                    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dataset = ImageDataGenerator(rescale = 1 / 255.0,\n                                  rotation_range = 15,\n                                  width_shift_range=0.1,\n                                  height_shift_range=0.1,\n                                  shear_range = 0.1,\n                                  zoom_range = 0.1,\n                                  horizontal_flip = True)\ntrain_generator = train_dataset.flow_from_dataframe(train_df[:23000],\n                                                  '/kaggle/working/tmp/train',\n                                                   x_col = 'filename',\n                                                   y_col = 'class',\n                                                   batch_size = 128,\n                                                   class_mode = 'categorical')\n\nvalidation_dataset = ImageDataGenerator(rescale = 1 / 255.0,\n                                  rotation_range = 15,\n                                  width_shift_range=0.1,\n                                  height_shift_range=0.1,\n                                  shear_range = 0.1,\n                                  zoom_range = 0.1,\n                                  horizontal_flip = True)\nvalidation_generator = train_dataset.flow_from_dataframe(train_df[23000:],\n                                                  '/kaggle/working/tmp/train',\n                                                   x_col = 'filename',\n                                                   y_col = 'class',\n                                                   batch_size = 128,\n                                                   class_mode = 'categorical')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class_to_indices = train_generator.class_indices\nindices_to_class ={class_to_indices[key]:key for key in class_to_indices.keys()}\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(12, 12))\nfor i in range(0, 15):\n    plt.subplot(3, 5, i+1)\n    for X_batch, Y_batch in train_generator:\n        image = X_batch[0]\n        plt.xticks([])\n        plt.yticks([])\n        plt.xlabel(indices_to_class[np.argmax(Y_batch[0])])\n        plt.imshow(image)\n        break\nplt.tight_layout()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base_model = InceptionResNetV2(input_shape = (256, 256, 3), include_top = False, pooling = 'avg')\nbase_model.trainable = False\nmodel = Sequential()\nmodel.add(base_model)\nmodel.add(Dropout(0.7))\nmodel.add(Dense(2, activation = 'softmax'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def scheduler(epoch):\n    return 0.001 * np.exp(0.1 *  epoch)\n\nlearning_callback = LearningRateScheduler(scheduler)\nearly_stop_callback = EarlyStopping(monitor='val_loss', patience = 2)\nmy_callback = [learning_callback, early_stop_callback]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit_generator(train_generator, epochs = 10, validation_data=validation_generator, callbacks = my_callback)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_dir = '/kaggle/input/dogs-vs-cats/test1.zip'\nwith ZipFile(test_dir) as zipfile:\n    zipfile.extractall('/kaggle/working/tmp')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"filenames = []\nclass_name = []\nfor name in os.listdir('/kaggle/working/tmp/test1'):\n    filenames.append(name)\n    class_name.append(name.split('.')[0])\ntest_df = pd.DataFrame(dict({'filename' : filenames}))                      ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_dataset = ImageDataGenerator(rescale = 1 / 255.0)\ntest_generator = test_dataset.flow_from_dataframe(test_df,\n                                                  '/kaggle/working/tmp/test1',\n                                                   x_col = 'filename',\n                                                   y_col = None,\n                                                   batch_size = 1,\n                                                   class_mode = None)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"prediction = model.predict_generator(test_generator)\nprediction = np.argmax(prediction, axis = 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.DataFrame({'id' : test_generator.filenames, 'label' : prediction})\nsubmission['id'] = submission['id'].apply(lambda x : int(x.split('.')[0]))\nsubmission = submission.sort_values(by = 'id')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.to_csv('submission.csv', index = False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}