{"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_minor":4,"nbformat":4,"cells":[{"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 20GB 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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 1. Preparation of Data and Exploratory Data Analysis","metadata":{}},{"cell_type":"code","source":"import os\nimport zipfile\nimport random\nimport tensorflow as tf\nimport shutil\nimport numpy as np\nfrom tensorflow.keras.optimizers import RMSprop\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.regularizers import l2\nfrom shutil import copyfile\nfrom os import getcwd","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"local_zip = '../input/dogs-vs-cats-redux-kernels-edition/train.zip'\n\nzip_ref = zipfile.ZipFile(local_zip, 'r')\n\nzip_ref.extractall('/kaggle/working/')\nzip_ref.close()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_dir = '/kaggle/working/'\ntrain_dir = os.path.join(base_dir, 'train')\ntrain_img_names = os.listdir(train_dir)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_img_names[:10]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('total training images :', len(train_img_names ))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"categories= list()\nfor image in train_img_names:\n    category = image.split(\".\")[0]\n    if category == \"dog\":\n        categories.append(\"dog\")\n    else:\n        categories.append(\"cat\")\ndf= pd.DataFrame({\"Image\":train_img_names, \"Category\": categories})","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport seaborn as sns\nimport random\nplt.figure(figsize=(12,10))\nsns.countplot(data=df, x=\"Category\",palette=\"magma\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample = random.choice(train_img_names)\nplt.imshow(plt.imread((\"/kaggle/working/train/\"+sample)))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample = random.choice(train_img_names)\nplt.imshow(plt.imread((\"/kaggle/working/train/\"+sample)))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\ntrain,validation= train_test_split(df, test_size=0.1)\ntrain = train.reset_index(drop=True)\nvalidation = validation.reset_index(drop=True)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"validation","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(13,10))\nsns.countplot(data=train, x=\"Category\",palette=\"viridis\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(13,10))\nsns.countplot(data=validation, x=\"Category\",palette=\"plasma\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# All images will be rescaled by 1./255.\ntrain_datagen = ImageDataGenerator( rescale = 1.0/255. )\n\n\n# --------------------\n# Flow training images in batches of 20 using train_datagen generator\n# --------------------\ntrain_generator = train_datagen.flow_from_dataframe(train,\n                                                    directory=\"./train\",\n                                                    x_col='Image',\n                                                    y_col='Category',\n                                                    batch_size=20,\n                                                    class_mode='binary',\n                                                    target_size=(150, 150))   ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"validation_datagen  = ImageDataGenerator( rescale = 1.0/255.)\nvalidation_generator =  validation_datagen.flow_from_dataframe(validation,\n                                                            directory=\"./train\",\n                                                              x_col='Image',\n                                                             y_col='Category',\n                                                              batch_size=20,\n                                                              class_mode  = 'binary',\n                                                              target_size = (150, 150))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 2. Building a Small Model from Scratch","metadata":{}},{"cell_type":"code","source":"import tensorflow\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D\nfrom tensorflow.keras.layers import MaxPool2D\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.layers import Dense, Dropout, BatchNormalization\nfrom tensorflow.keras.callbacks import EarlyStopping\nmodel = Sequential()\nmodel.add(Conv2D(filters=32, kernel_size=3,activation=\"relu\", input_shape=(150,150,3)))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D(pool_size=2, strides=2))\nmodel.add(Conv2D(filters=64, kernel_size=3,activation=\"relu\"))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D(pool_size=2, strides=2))\nmodel.add(Conv2D(filters=128, kernel_size=3, activation=\"relu\"))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D(pool_size=2, strides=2))\nmodel.add(Conv2D(filters=256, kernel_size=3, activation=\"relu\"))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D(pool_size=2, strides=2))\nmodel.add(Conv2D(filters=256, kernel_size=3, activation=\"relu\"))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D(pool_size=2, strides=2))\nmodel.add(Flatten())\nmodel.add(Dense(units=1024, activation=\"relu\"))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(units=1, activation=\"sigmoid\"))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer=RMSprop(lr=0.001), loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"callback=EarlyStopping(monitor=\"val_loss\", patience=2)\ncallback_lr = tensorflow.keras.callbacks.ReduceLROnPlateau(monitor='val_acc', patience=2, factor=0.5, min_lr=0.00001)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n\nhistory=model.fit(train_generator, validation_data=validation_generator, \n                  epochs=8, callbacks=[callback,callback_lr])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 3. Performance Evaluation of the Training","metadata":{}},{"cell_type":"code","source":"pd.DataFrame(model.history.history)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sns.set_style(\"darkgrid\")\npd.DataFrame(model.history.history).plot(figsize=(15,10))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"acc      = history.history[     'accuracy' ]\nval_acc  = history.history[ 'val_accuracy' ]\nloss     = history.history[    'loss' ]\nval_loss = history.history['val_loss' ]\n\nepochs   = range(len(acc)) # Get number of epochs\n\n#------------------------------------------------\n# Plot training and validation accuracy per epoch\n#------------------------------------------------\nplt.plot  ( epochs,     acc )\nplt.plot  ( epochs, val_acc )\nplt.title ('Training and validation accuracy')\nplt.figure()\n\n#------------------------------------------------\n# Plot training and validation loss per epoch\n#------------------------------------------------\nplt.plot  ( epochs,     loss )\nplt.plot  ( epochs, val_loss )\nplt.title ('Training and validation loss'   )","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 4. Preparing Test Data and Submission","metadata":{}},{"cell_type":"code","source":"# Extracting the zip file\n\ntest_zip = '../input/dogs-vs-cats-redux-kernels-edition/test.zip'\nzip_ref = zipfile.ZipFile(test_zip, 'r')\nzip_ref.extractall('/kaggle/working')\nzip_ref.close()\n\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_dir = '/kaggle/working/test/'\ntest_images = os.listdir(os.path.join(test_dir))\ntest_images[:10]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df = pd.DataFrame({'Image': test_images})\ntest_df.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_datagen = ImageDataGenerator(rescale=1./255)\ntest_generator = test_datagen.flow_from_dataframe(test_df,\n                                                  directory=\"/kaggle/working/test\",\n                                                 x_col=\"Image\",\n                                                 y_col=None,\n                                                  class_mode  = None,\n                                                 target_size=(150,150),\n                                                shuffle = True,\n                                                batch_size=20)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = model.predict(test_generator,steps = np.ceil(12500/20))\npredictions","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df[\"category\"]=pd.DataFrame(predictions, columns=[\"category\"])\ntest_df","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def labelizor(prediction):\n    if prediction > 0.5:\n        return 1\n    else:\n        return 0","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df[\"category\"] = test_df[\"category\"].apply(labelizor)\ntest_df","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(13,10))\nsns.countplot(data=test_df, x=\"category\",palette=\"magma\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df=test_df.reset_index()\ntest_df","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df=test_df.rename(columns={\"index\": \"id\"})\ntest_df","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_df=test_df.copy()\nsubmission_df.drop(\"Image\", axis=1, inplace=True)\nsubmission_df","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_df.to_csv('submission.csv', index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}