{"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","execution":{"iopub.status.busy":"2022-08-30T08:09:59.550237Z","iopub.execute_input":"2022-08-30T08:09:59.550943Z","iopub.status.idle":"2022-08-30T08:09:59.601923Z","shell.execute_reply.started":"2022-08-30T08:09:59.550760Z","shell.execute_reply":"2022-08-30T08:09:59.600291Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers, models, optimizers\nfrom keras.layers import Dense, MaxPool2D, Conv2D, Dropout, Flatten, GlobalAveragePooling2D, BatchNormalization, Activation, MaxPooling2D\nfrom keras.models import Sequential\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt","metadata":{"execution":{"iopub.status.busy":"2022-08-30T08:09:59.604660Z","iopub.execute_input":"2022-08-30T08:09:59.605462Z","iopub.status.idle":"2022-08-30T08:10:08.227497Z","shell.execute_reply.started":"2022-08-30T08:09:59.605420Z","shell.execute_reply":"2022-08-30T08:10:08.225997Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Extract Data","metadata":{}},{"cell_type":"code","source":"import zipfile\ntrain_zip='../input/dogs-vs-cats-redux-kernels-edition/train.zip'\nzip_ref=zipfile.ZipFile(train_zip,'r').extractall('./')\n\ntest_zip = '../input/dogs-vs-cats-redux-kernels-edition/test.zip'\nzip_ref=zipfile.ZipFile(test_zip,'r').extractall('./')\n","metadata":{"execution":{"iopub.status.busy":"2022-08-30T08:10:08.233514Z","iopub.execute_input":"2022-08-30T08:10:08.237426Z","iopub.status.idle":"2022-08-30T08:10:37.546613Z","shell.execute_reply.started":"2022-08-30T08:10:08.237377Z","shell.execute_reply":"2022-08-30T08:10:37.545195Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\ntrain_filenames = os.listdir('./train')\ntest_filenames = os.listdir('./test')","metadata":{"execution":{"iopub.status.busy":"2022-08-30T08:10:37.550618Z","iopub.execute_input":"2022-08-30T08:10:37.551275Z","iopub.status.idle":"2022-08-30T08:10:37.599396Z","shell.execute_reply.started":"2022-08-30T08:10:37.551228Z","shell.execute_reply":"2022-08-30T08:10:37.597985Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create DataFrame for ImageDataGenerator\ntrain = pd.DataFrame(columns=['path', 'label'])\ntrain['path'] = train_filenames\ntrain['label'] = train['path'].str[0:3]","metadata":{"execution":{"iopub.status.busy":"2022-08-30T08:10:37.601986Z","iopub.execute_input":"2022-08-30T08:10:37.602494Z","iopub.status.idle":"2022-08-30T08:10:37.946238Z","shell.execute_reply.started":"2022-08-30T08:10:37.602451Z","shell.execute_reply":"2022-08-30T08:10:37.940732Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()","metadata":{"execution":{"iopub.status.busy":"2022-08-30T08:10:37.948452Z","iopub.execute_input":"2022-08-30T08:10:37.949201Z","iopub.status.idle":"2022-08-30T08:10:38.003073Z","shell.execute_reply.started":"2022-08-30T08:10:37.949158Z","shell.execute_reply":"2022-08-30T08:10:38.001093Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.label.value_counts().plot.bar() # Balanced Data","metadata":{"execution":{"iopub.status.busy":"2022-08-30T08:10:38.005621Z","iopub.execute_input":"2022-08-30T08:10:38.012022Z","iopub.status.idle":"2022-08-30T08:10:38.399738Z","shell.execute_reply.started":"2022-08-30T08:10:38.011964Z","shell.execute_reply":"2022-08-30T08:10:38.398319Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\ntrain_datagen = ImageDataGenerator(rescale=1/255.0, validation_split=0.2)","metadata":{"execution":{"iopub.status.busy":"2022-08-30T08:10:38.401687Z","iopub.execute_input":"2022-08-30T08:10:38.402526Z","iopub.status.idle":"2022-08-30T08:10:38.412867Z","shell.execute_reply.started":"2022-08-30T08:10:38.402482Z","shell.execute_reply":"2022-08-30T08:10:38.411241Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"width, height = 150, 150\ntrainDatagen = train_datagen.flow_from_dataframe(train, directory = './train', x_col='path', y_col='label', classes=['cat', 'dog' ],\n                                           target_size=(width,height), class_mode = 'categorical', batch_size = 16,\n                                           subset='training')\n\nvalDatagen = train_datagen.flow_from_dataframe(train, directory = './train', x_col='path', y_col='label', classes=['cat','dog'],\n                                           target_size=(width,height), class_mode = 'categorical', batch_size = 16,\n                                           subset='validation')","metadata":{"execution":{"iopub.status.busy":"2022-08-30T09:22:33.979897Z","iopub.execute_input":"2022-08-30T09:22:33.980334Z","iopub.status.idle":"2022-08-30T09:22:34.538330Z","shell.execute_reply.started":"2022-08-30T09:22:33.980304Z","shell.execute_reply":"2022-08-30T09:22:34.536685Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x, y = trainDatagen.next()\nx.shape, y.shape","metadata":{"execution":{"iopub.status.busy":"2022-08-30T09:22:35.329561Z","iopub.execute_input":"2022-08-30T09:22:35.329959Z","iopub.status.idle":"2022-08-30T09:22:35.382413Z","shell.execute_reply.started":"2022-08-30T09:22:35.329930Z","shell.execute_reply":"2022-08-30T09:22:35.381053Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(15,15))\nfor i in range(9):\n    img, label = trainDatagen.next()\n    plt.subplot(331+i)\n    plt.imshow(img[0])\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-08-30T09:22:36.012322Z","iopub.execute_input":"2022-08-30T09:22:36.013362Z","iopub.status.idle":"2022-08-30T09:22:37.951986Z","shell.execute_reply.started":"2022-08-30T09:22:36.013306Z","shell.execute_reply":"2022-08-30T09:22:37.950478Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Test Data","metadata":{}},{"cell_type":"code","source":"test = pd.DataFrame(columns=['path'])\ntest['path'] = test_filenames\ntest.head()","metadata":{"execution":{"iopub.status.busy":"2022-08-30T08:10:41.094970Z","iopub.execute_input":"2022-08-30T08:10:41.095334Z","iopub.status.idle":"2022-08-30T08:10:41.121696Z","shell.execute_reply.started":"2022-08-30T08:10:41.095287Z","shell.execute_reply":"2022-08-30T08:10:41.120050Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_datagen = ImageDataGenerator(rescale=1/255.0)\nwidth, height = 150, 150\ntestDatagen = test_datagen.flow_from_dataframe(test, directory = './test', x_col='path', class_mode= None,\n                                           target_size=(width,height), batch_size = 16, shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2022-08-30T08:10:41.123411Z","iopub.execute_input":"2022-08-30T08:10:41.124757Z","iopub.status.idle":"2022-08-30T08:10:41.277766Z","shell.execute_reply.started":"2022-08-30T08:10:41.124718Z","shell.execute_reply":"2022-08-30T08:10:41.276040Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Training and Prediction","metadata":{}},{"cell_type":"code","source":"model = models.Sequential()\nmodel.add(layers.Conv2D(64,(3,3),activation='relu',input_shape=(150,150,3)))\nmodel.add(layers.MaxPooling2D((2,2)))\n \nmodel.add(layers.Conv2D(64,(3,3),activation='relu'))\nmodel.add(layers.MaxPooling2D((2,2)))\nmodel.add(layers.BatchNormalization())\nmodel.add(layers.Dropout(0.3))\n    \nmodel.add(layers.Conv2D(128,(3,3),activation='relu'))\nmodel.add(layers.MaxPooling2D((2,2)))\n \nmodel.add(layers.Conv2D(128,(3,3),activation='relu'))\nmodel.add(layers.MaxPooling2D((2,2)))\nmodel.add(layers.BatchNormalization())\nmodel.add(layers.Dropout(0.3))\n\nmodel.add(layers.Flatten())\n\nmodel.add(layers.Dense(256,activation='relu'))\nmodel.add(layers.Dense(2,activation='softmax'))\n\nmodel.compile(loss=\"categorical_crossentropy\",optimizer=optimizers.Adam(learning_rate=1e-4),metrics=['acc'])\n \nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-08-30T09:31:27.415495Z","iopub.execute_input":"2022-08-30T09:31:27.415924Z","iopub.status.idle":"2022-08-30T09:31:27.543315Z","shell.execute_reply.started":"2022-08-30T09:31:27.415895Z","shell.execute_reply":"2022-08-30T09:31:27.542008Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(trainDatagen, steps_per_epoch = len(trainDatagen), epochs=10, validation_data = valDatagen, validation_steps=len(valDatagen), shuffle=True)","metadata":{"execution":{"iopub.status.busy":"2022-08-30T09:31:29.542516Z","iopub.execute_input":"2022-08-30T09:31:29.543017Z","iopub.status.idle":"2022-08-30T09:45:04.662162Z","shell.execute_reply.started":"2022-08-30T09:31:29.542984Z","shell.execute_reply":"2022-08-30T09:45:04.660729Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n%matplotlib inline \nplt.plot(history.history[\"acc\"])\nplt.plot(history.history[\"val_acc\"])\nplt.title(\"Model accuracy\")\nplt.ylabel(\"Accuracy\")\nplt.xlabel(\"Epoch\")\nplt.legend([\"Train\",\"Test\"],loc=\"upper left\")\nplt.show()\n\nplt.plot(history.history[\"loss\"])\nplt.plot(history.history[\"val_loss\"])\nplt.title(\"Model loss\")\nplt.ylabel(\"loss\")\nplt.xlabel(\"Epoch\")\nplt.legend([\"Train\",\"Test\"],loc=\"upper left\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-08-30T09:45:35.441905Z","iopub.execute_input":"2022-08-30T09:45:35.442329Z","iopub.status.idle":"2022-08-30T09:45:35.992711Z","shell.execute_reply.started":"2022-08-30T09:45:35.442299Z","shell.execute_reply":"2022-08-30T09:45:35.991257Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = model.predict(testDatagen, batch_size=32, verbose =1)\npredictions","metadata":{"execution":{"iopub.status.busy":"2022-08-30T09:45:38.207170Z","iopub.execute_input":"2022-08-30T09:45:38.207603Z","iopub.status.idle":"2022-08-30T09:46:19.336289Z","shell.execute_reply.started":"2022-08-30T09:45:38.207560Z","shell.execute_reply":"2022-08-30T09:46:19.334897Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.read_csv('../input/dogs-vs-cats-redux-kernels-edition/sample_submission.csv')\nsubmission['label'] = predictions[:,0]\nsubmission.to_csv('submission.csv', index=False)\nsubmission.head()","metadata":{"execution":{"iopub.status.busy":"2022-08-30T09:47:31.349971Z","iopub.execute_input":"2022-08-30T09:47:31.350450Z","iopub.status.idle":"2022-08-30T09:47:31.395841Z","shell.execute_reply.started":"2022-08-30T09:47:31.350390Z","shell.execute_reply":"2022-08-30T09:47:31.394644Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}