{"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\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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd \nimport tensorflow as tf\nfrom keras.preprocessing.image import ImageDataGenerator, load_img\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, Activation, BatchNormalization\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport random\nimport os","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# **Data Preprocessing**"},{"metadata":{"trusted":true},"cell_type":"code","source":"# !unzip /kaggle/input/dogs-vs-cats/train.zip\n# !unzip /kaggle/input/dogs-vs-cats/test1.zip","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"train size: \", len(os.listdir('train')))\nprint(\"test size: \", len(os.listdir('test1')))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Visualization"},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nimg = tf.keras.preprocessing.image.load_img('test1/10924.jpg')\nplt.imshow(img)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Splitting data with flow from dataframe"},{"metadata":{"trusted":true},"cell_type":"code","source":"### category assigning\n\nfilenames = os.listdir(\"train\")\ncategories = []\n\nfor filename in filenames:\n    category = filename.split('.')[0]\n    if category == 'dog':\n        categories.append(1)\n    else:\n        categories.append(0)\n\ndf = pd.DataFrame({\n    'filename': filenames,\n    'category': categories\n})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df[\"category\"] = df[\"category\"].replace({0: 'cat', 1: 'dog'}) \n\ndf.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df, valid_df = train_test_split(df, test_size=0.20, random_state=220)\ntrain_df = train_df.reset_index(drop=True)\nvalid_df = valid_df.reset_index(drop=True)\n\nvalid_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"BATCH_SIZE = 64\n\nIMAGE_HEIGHT=128\nIMAGE_WIDTH=128\nIMAGE_SIZE=(IMAGE_WIDTH, IMAGE_HEIGHT)\n\n\n### Train\n\ntrain_datagen = ImageDataGenerator(rotation_range=15,\n                                   rescale=1./255,\n                                   zoom_range=0.2,\n                                   horizontal_flip=True,\n                                   width_shift_range=0.1,\n                                   height_shift_range=0.1\n                                  )\n\n\ntrain_generator = train_datagen.flow_from_dataframe(train_df, \n                                                    \"train/\", \n                                                    x_col='filename',\n                                                    y_col='category',\n                                                    target_size=IMAGE_SIZE,\n                                                    class_mode='binary',\n                                                    batch_size=BATCH_SIZE\n                                                   )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## Valid - no augmentation\n\nvalid_datagen = ImageDataGenerator(rescale=1./255)\n\nvalid_generator = valid_datagen.flow_from_dataframe(valid_df, \n                                                    \"train/\", \n                                                    x_col='filename',\n                                                    y_col='category',\n                                                    target_size=IMAGE_SIZE,\n                                                    class_mode='binary',\n                                                    batch_size=BATCH_SIZE\n                                                   )","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Simple CNN Modeling"},{"metadata":{"trusted":true},"cell_type":"code","source":"model = tf.keras.models.Sequential([\n    tf.keras.layers.Conv2D(16, (3,3), input_shape=(128, 128, 3)),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.Activation('relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    \n    tf.keras.layers.Conv2D(32, (3,3)),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.Activation('relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    \n    tf.keras.layers.Conv2D(64, (3,3)),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.Activation('relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    \n    tf.keras.layers.Flatten(),\n    tf.keras.layers.Dropout(0.2),\n    \n    tf.keras.layers.Dense(512, activation='relu'),\n    tf.keras.layers.Dense(1, activation='sigmoid')\n])\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer = tf.keras.optimizers.RMSprop(lr=0.01), \n              loss='binary_crossentropy', \n              metrics = ['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"earlystop = tf.keras.callbacks.EarlyStopping(patience=10)\n\nEPOCHS = 50\n\nhistory = model.fit(train_generator, \n                    epochs=EPOCHS,\n                    validation_data=valid_generator,\n                    callbacks=[earlystop]\n                   )","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}