{"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)\nimport tensorflow as tf\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\nimport zipfile\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\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":"### Unzipping the data\n"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"local_zip_train_path = '../input/dogs-vs-cats/train.zip'\nzip_train_file = zipfile.ZipFile(local_zip_train_path, 'r')\nzip_train_file.extractall('../kaggle/working')\nzip_train_file.close()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"local_zip_test_path = '../input/dogs-vs-cats/test1.zip'\nzip_test_file = zipfile.ZipFile(local_zip_test_path, 'r')\nzip_test_file.extractall('../kaggle/working')\nzip_test_file.close()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(os.listdir('../kaggle/working'))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Preparing Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"filenames = os.listdir('../kaggle/working/train')\n\nclass_categ = []\n\nfor file in filenames:\n    \n    categ_str = file.split('.')[0]\n    \n    if categ_str == 'dog':\n        class_categ.append('cat')\n    else:\n        class_categ.append('dog')\n\ndata_frame = pd.DataFrame({'file_name': filenames, 'category': class_categ})\ndata_frame","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Splitting Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\ndf_train, df_validate =  train_test_split(data_frame, test_size = 0.2, random_state = 0)\n\ndf_train = df_train.reset_index(drop=True)\ndf_validate = df_validate.reset_index(drop=True)\n\ntraining_data_size = df_train.shape[0]\nvalidation_data_size = df_validate.shape[0]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## CNN - Arch"},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.layers import Conv2D, BatchNormalization, MaxPool2D, Dropout, Flatten, Dense\nmodel = tf.keras.models.Sequential()\n\nmodel.add(Conv2D(32, (3, 3), activation='relu', input_shape=(128, 128, 3)))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(128, (3, 3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(512, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(1024, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(1, activation='sigmoid'))\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer=tf.keras.optimizers.Adam(), loss= 'binary_crossentropy', metrics= ['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\ntrain_datagen =  ImageDataGenerator(rescale=1./255, \n                                    rotation_range=15,\n                                    shear_range=0.1,\n                                    zoom_range=0.2,\n                                    horizontal_flip=True,\n                                    width_shift_range=0.1,\n                                    height_shift_range=0.1)\n\nvalidate_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_gen = train_datagen.flow_from_dataframe(df_train,  '../kaggle/working/train',x_col='file_name', y_col='category', batch_size= 64,target_size=(128,128), class_mode='binary')\nval_gen = validate_datagen.flow_from_dataframe(df_validate,  '../kaggle/working/train',x_col='file_name', y_col='category', batch_size= 32,target_size=(128,128), class_mode='binary')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"total_train = df_train.shape[0]\ntotal_validate = df_validate.shape[0]\nbatch_size = 256\nEPOCHS_ = 15","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_history = model.fit_generator(train_gen, \n                                    validation_data=val_gen, \n                                    epochs=EPOCHS_, \n                                    steps_per_epoch=total_train // batch_size, \n                                    validation_steps=total_validate // batch_size)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Save model weights"},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save_weights('model.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from matplotlib import pyplot as plt\n\nfig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 12))\nax1.plot(model_history.history['loss'], color='b', label=\"Training loss\")\nax1.plot(model_history.history['val_loss'], color='r', label=\"validation loss\")\nax1.set_xticks(np.arange(1, 15, 1))\nax1.set_yticks(np.arange(0, 1, 0.1))\n\nax2.plot(model_history.history['accuracy'], color='b', label=\"Training accuracy\")\nax2.plot(model_history.history['val_accuracy'], color='r',label=\"Validation accuracy\")\nax2.set_xticks(np.arange(1, 15, 1))\n\nlegend = plt.legend(loc='best', shadow=True)\nplt.tight_layout()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Testing Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"test_filenames = os.listdir(\"../kaggle/working/test1\")\ntest_df = pd.DataFrame({\n    'filename': test_filenames\n})\nnb_samples = test_df.shape[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_gen = ImageDataGenerator(rescale=1./255)\ntest_generator = test_gen.flow_from_dataframe(\n    test_df, \n    \"../kaggle/working/test1/\", \n    x_col='filename',\n    y_col=None,\n    class_mode=None,\n    target_size=(128,128),\n    batch_size=batch_size,\n    shuffle=False\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predict = model.predict_generator(test_generator, steps=np.ceil(nb_samples/batch_size))\npredict","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['category'] = predict >= 0.5\ntest_df['category']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['category'].value_counts().plot.bar()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission_df = test_df.copy()\nsubmission_df['id'] = submission_df['filename'].str.split('.').str[0]\nsubmission_df['label'] = submission_df['category']\nsubmission_df.drop(['filename', 'category'], axis=1, inplace=True)\nsubmission_df.to_csv('submission.csv', index=False)","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}