{"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\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 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":"os.listdir(\"/kaggle/input/dogs-vs-cats-redux-kernels-edition/\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import zipfile","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip\", \"r\") as z:\n    z.extractall(\".\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip\", \"r\") as z:\n    z.extractall(\".\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(os.listdir(\"/kaggle/working/train/\")), len(os.listdir(\"/kaggle/working/test\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"path_train_data = \"/kaggle/working/train/\"\nfilenames = os.listdir(path_train_data)\ncategories = []\n\nfor i in filenames:\n    categ = i.split(\".\")[0]\n    if categ == \"dog\":\n        categories.append(1)\n    else:\n        categories.append(0)\n        \ntrain_df = pd.DataFrame({\n    \"filename\" : filenames,\n    \"category\" : categories\n})","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_df[\"category\"] = train_df[\"category\"].replace({0 : \"cat\", 1 : \"dog\"})","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":"from sklearn.model_selection import train_test_split","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train, df_validation = train_test_split(train_df, test_size = 0.2, random_state = 42)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train.shape, df_validation.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rotation_range= 15,\n                                                                rescale= 1./255,\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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_generator = train_datagen.flow_from_dataframe(dataframe= df_train,\n                                                   directory= path_train_data,\n                                                   x_col= \"filename\",\n                                                   y_col= \"category\",\n                                                   target_size= (128, 128),\n                                                   class_mode= \"binary\",\n                                                   batch_size= 15)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"validation_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale= 1./255)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"validation_generator = validation_datagen.flow_from_dataframe(dataframe= df_validation,\n                                                             directory= path_train_data,\n                                                             x_col= \"filename\",\n                                                             y_col= \"category\",\n                                                             target_size= (128,128),\n                                                             class_mode= \"binary\",\n                                                             batch_size= 15)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def build_model():\n    model = tf.keras.models.Sequential()\n    \n    model.add(tf.keras.layers.Conv2D(32, (3,3), activation = \"relu\", input_shape = (128,128,3)))\n    model.add(tf.keras.layers.BatchNormalization())\n    model.add(tf.keras.layers.MaxPool2D(pool_size = (2,2)))\n    model.add(tf.keras.layers.Dropout(0.25))\n    \n    model.add(tf.keras.layers.Conv2D(64, (3,3), activation = \"relu\"))\n    model.add(tf.keras.layers.BatchNormalization())\n    model.add(tf.keras.layers.MaxPool2D(pool_size = (2,2)))\n    model.add(tf.keras.layers.Dropout(0.25))\n    \n    model.add(tf.keras.layers.Conv2D(128, (3,3), activation = \"relu\"))\n    model.add(tf.keras.layers.BatchNormalization())\n    model.add(tf.keras.layers.MaxPool2D(pool_size = (2,2)))\n    model.add(tf.keras.layers.Dropout(0.25))\n    \n    model.add(tf.keras.layers.Flatten())\n    model.add(tf.keras.layers.Dense(512, activation = \"relu\"))\n    model.add(tf.keras.layers.BatchNormalization())\n    model.add(tf.keras.layers.Dropout(0.25))\n    model.add(tf.keras.layers.Dense(2, activation = \"softmax\"))\n    \n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = build_model()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(loss = \"binary_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":"total_train = df_train.shape[0]\ntotal_validate = df_validation.shape[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"total_train, total_validate","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"reduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor=\"val_loss\", factor=0.1, patience=3,\n                                                verbose=1, min_lr= 0.0001)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit_generator(train_generator,\n                             epochs= 10, validation_data= validation_generator,\n                             validation_steps= total_validate // 15,\n                             steps_per_epoch= total_train // 15,\n                             callbacks=[reduce_lr])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_file = os.listdir(\"/kaggle/working/test/\")\n\ntest_df = pd.DataFrame({\n    \"filename\" : test_file\n})\n\ntest_size = test_df.shape[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_gen = tf.keras.preprocessing.image.ImageDataGenerator(rescale= 1./255)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_generator = test_gen.flow_from_dataframe(dataframe= test_df,\n                                             directory= \"/kaggle/working/test/\",\n                                             x_col= \"filename\",\n                                             y_col= None,\n                                             class_mode= None,\n                                             target_size= (128,128),\n                                             batch_size= 15)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred = model.predict_generator(test_generator)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred = np.argmax(pred, axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_df = pd.DataFrame(data= pred)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_df.index += 1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_df = pred_df.reset_index()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_df.columns = [\"id\", \"label\"]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_df.tail()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_df.to_csv(\"Dogs Vs Cats CNN 1.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}