{"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":"2023-06-15T06:27:45.891618Z","iopub.execute_input":"2023-06-15T06:27:45.892007Z","iopub.status.idle":"2023-06-15T06:27:45.907559Z","shell.execute_reply.started":"2023-06-15T06:27:45.891977Z","shell.execute_reply":"2023-06-15T06:27:45.905926Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Let's import the necessary libraries ","metadata":{}},{"cell_type":"code","source":"import zipfile\nimport tensorflow as tf\nfrom tensorflow.keras import models, layers\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport os\nimport shutil\nimport glob\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg","metadata":{"execution":{"iopub.status.busy":"2023-06-17T09:36:18.455124Z","iopub.execute_input":"2023-06-17T09:36:18.455588Z","iopub.status.idle":"2023-06-17T09:36:18.463120Z","shell.execute_reply.started":"2023-06-17T09:36:18.455551Z","shell.execute_reply":"2023-06-17T09:36:18.461857Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## First of all let's extract training and test data from the zip files.","metadata":{}},{"cell_type":"code","source":"zip_ref = zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/test1.zip\",\"r\")\ntest_data = zip_ref.extractall(\"/kaggle/working/\")\nzip_ref = zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/train.zip\", \"r\")\ntrain_data = zip_ref.extractall(\"/kaggle/working/\")\nzip_ref.close()","metadata":{"execution":{"iopub.status.busy":"2023-06-17T09:30:29.007604Z","iopub.execute_input":"2023-06-17T09:30:29.008617Z","iopub.status.idle":"2023-06-17T09:30:45.165404Z","shell.execute_reply.started":"2023-06-17T09:30:29.008584Z","shell.execute_reply":"2023-06-17T09:30:45.164355Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dir = \"/kaggle/working/train\"\ntest_dir = \"/kaggle/working/test1\"","metadata":{"execution":{"iopub.status.busy":"2023-06-17T09:30:45.167003Z","iopub.execute_input":"2023-06-17T09:30:45.167760Z","iopub.status.idle":"2023-06-17T09:30:45.172590Z","shell.execute_reply.started":"2023-06-17T09:30:45.167725Z","shell.execute_reply":"2023-06-17T09:30:45.171245Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Number of train images:\", len(os.listdir(train_dir)))\nprint(\"Number of test images:\", len(os.listdir(test_dir)))","metadata":{"execution":{"iopub.status.busy":"2023-06-17T09:30:45.175907Z","iopub.execute_input":"2023-06-17T09:30:45.176663Z","iopub.status.idle":"2023-06-17T09:30:45.207882Z","shell.execute_reply.started":"2023-06-17T09:30:45.176629Z","shell.execute_reply":"2023-06-17T09:30:45.206979Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### For train and test folders creating subfolders with their class names as cat and dog, so that will allow us to use an image data generator for further preprocessing of images.","metadata":{}},{"cell_type":"code","source":"def make_classes():\n    work_dir = train_dir\n    cat_sf = os.path.join(work_dir, 'cat')\n    dog_sf = os.path.join(work_dir, 'dog')\n    os.makedirs(cat_sf, exist_ok=True)\n    os.makedirs(dog_sf, exist_ok=True)\n    for img in glob.glob(work_dir + '/*.jpg'):\n        if \"cat\" in img:\n            shutil.move(os.path.join(work_dir, img), cat_sf)\n        else:\n            shutil.move(os.path.join(work_dir, img), dog_sf)\nmake_classes()","metadata":{"execution":{"iopub.status.busy":"2023-06-17T09:30:45.209196Z","iopub.execute_input":"2023-06-17T09:30:45.209511Z","iopub.status.idle":"2023-06-17T09:30:46.516707Z","shell.execute_reply.started":"2023-06-17T09:30:45.209483Z","shell.execute_reply":"2023-06-17T09:30:46.515454Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Let's see some images of cats and dogs from corresponding directories","metadata":{}},{"cell_type":"code","source":"nrows = 4\nncols = 4\n\npic_indx = 0","metadata":{"execution":{"iopub.status.busy":"2023-06-17T09:36:44.865274Z","iopub.execute_input":"2023-06-17T09:36:44.865621Z","iopub.status.idle":"2023-06-17T09:36:44.870612Z","shell.execute_reply.started":"2023-06-17T09:36:44.865594Z","shell.execute_reply":"2023-06-17T09:36:44.869594Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig = plt.gcf()\nfig.set_size_inches(ncols * 4, nrows * 4)\npic_indx +=8\n\ntrain_cat_dir = os.path.join(train_dir,\"cat\")\ntrain_dog_dir = os.path.join(train_dir, \"dog\")\nnext_cats_imgs = [os.path.join(train_cat_dir, img) for img in os.listdir(train_cat_dir)[pic_indx-8:pic_indx]]\nnext_dogs_imgs = [os.path.join(train_dog_dir, img) for img in os.listdir(train_dog_dir)[pic_indx-8:pic_indx]]\n\n\n\nfor i, img_path in enumerate(next_cats_imgs + next_dogs_imgs):\n    sp = plt.subplot(nrows, ncols , i+1)\n    sp.axis(\"off\")\n    \n    img = plt.imread(img_path)\n    plt.imshow(img)\n    \nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-06-17T09:48:32.448354Z","iopub.execute_input":"2023-06-17T09:48:32.448716Z","iopub.status.idle":"2023-06-17T09:48:33.952944Z","shell.execute_reply.started":"2023-06-17T09:48:32.448687Z","shell.execute_reply":"2023-06-17T09:48:33.952067Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Extraction of train and test images and performing image augmentation on them with the help of the image data generator.","metadata":{}},{"cell_type":"code","source":"train_datagen = ImageDataGenerator(rescale=1/255, \n                                   zoom_range=0.2,\n                                   horizontal_flip=True,\n                                   shear_range=0.2,\n                                   width_shift_range=0.2,\n                                   height_shift_range=0.2,\n                                   rotation_range=40,\n                                   validation_split=0.3)","metadata":{"execution":{"iopub.status.busy":"2023-06-17T11:31:30.937824Z","iopub.execute_input":"2023-06-17T11:31:30.938230Z","iopub.status.idle":"2023-06-17T11:31:30.943687Z","shell.execute_reply.started":"2023-06-17T11:31:30.938196Z","shell.execute_reply":"2023-06-17T11:31:30.942657Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_generator = train_datagen.flow_from_directory(train_dir, \n                                  target_size=(150, 150),\n                                  class_mode=\"binary\",\n                                  batch_size=250, \n                                  subset=\"training\"\n                             )\nvalidation_generator = train_datagen.flow_from_directory(\n                                  train_dir,\n                                  target_size=(150, 150),\n                                  class_mode=\"binary\",\n                                  batch_size=250, \n                                  subset=\"validation\"\n)","metadata":{"execution":{"iopub.status.busy":"2023-06-17T12:40:24.676953Z","iopub.execute_input":"2023-06-17T12:40:24.677669Z","iopub.status.idle":"2023-06-17T12:40:25.457110Z","shell.execute_reply.started":"2023-06-17T12:40:24.677635Z","shell.execute_reply":"2023-06-17T12:40:25.456140Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_datagen = ImageDataGenerator(rescale=1/255)\ntest_generator = test_datagen.flow_from_directory(\n    \"/kaggle/working/\", \n    class_mode=None, \n    target_size=(150, 150),\n    shuffle = False,\n    classes = ['test1']\n)","metadata":{"execution":{"iopub.status.busy":"2023-06-17T09:48:44.104574Z","iopub.execute_input":"2023-06-17T09:48:44.105161Z","iopub.status.idle":"2023-06-17T09:48:44.404774Z","shell.execute_reply.started":"2023-06-17T09:48:44.105124Z","shell.execute_reply":"2023-06-17T09:48:44.403811Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Building a model with 3 convolutional layers followed by max pooling layers, and 2 fully-connected layers.","metadata":{}},{"cell_type":"code","source":"model = models.Sequential([\n    layers.Conv2D(32, kernel_size=3, input_shape=(150, 150, 3), activation=\"relu\"),\n    layers.MaxPooling2D(2, 2),\n    layers.Conv2D(64, kernel_size=3, activation=\"relu\"),\n    layers.MaxPooling2D(2, 2),\n    layers.Conv2D(64, kernel_size=3, activation=\"relu\"),\n    layers.MaxPooling2D(2, 2),\n    layers.Conv2D(128, kernel_size=3, activation=\"relu\"),\n    layers.MaxPooling2D(2, 2),\n    layers.Conv2D(128, kernel_size=3, activation=\"relu\"),\n    layers.MaxPooling2D(2, 2),\n    layers.Flatten(),\n    layers.Dense(512, activation=\"relu\"),\n    layers.Dense(1, activation=\"sigmoid\")\n])","metadata":{"execution":{"iopub.status.busy":"2023-06-17T09:49:17.255607Z","iopub.execute_input":"2023-06-17T09:49:17.255983Z","iopub.status.idle":"2023-06-17T09:49:22.113772Z","shell.execute_reply.started":"2023-06-17T09:49:17.255955Z","shell.execute_reply":"2023-06-17T09:49:22.112765Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2023-06-17T09:49:22.115523Z","iopub.execute_input":"2023-06-17T09:49:22.115858Z","iopub.status.idle":"2023-06-17T09:49:22.157849Z","shell.execute_reply.started":"2023-06-17T09:49:22.115833Z","shell.execute_reply":"2023-06-17T09:49:22.157067Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer=\"adam\", loss=\"binary_crossentropy\", metrics=[\"accuracy\"])","metadata":{"execution":{"iopub.status.busy":"2023-06-17T09:49:22.158880Z","iopub.execute_input":"2023-06-17T09:49:22.159223Z","iopub.status.idle":"2023-06-17T09:49:22.189028Z","shell.execute_reply.started":"2023-06-17T09:49:22.159190Z","shell.execute_reply":"2023-06-17T09:49:22.188125Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class MyCallback(tf.keras.callbacks.Callback):\n    def on_epoch_end(self, epoch, logs={}):\n        if logs[\"accuracy\"] is not None and logs[\"val_accuracy\"] >= 0.99:\n            print(\"Training is finished...\")\n            self.model.stop_training = True","metadata":{"execution":{"iopub.status.busy":"2023-06-17T09:49:31.977225Z","iopub.execute_input":"2023-06-17T09:49:31.977571Z","iopub.status.idle":"2023-06-17T09:49:31.982885Z","shell.execute_reply.started":"2023-06-17T09:49:31.977545Z","shell.execute_reply":"2023-06-17T09:49:31.981952Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Training defined model and making predictions","metadata":{}},{"cell_type":"code","source":"history = model.fit(train_generator, validation_data=validation_generator, epochs=20, callbacks=[MyCallback()])","metadata":{"execution":{"iopub.status.busy":"2023-06-17T09:52:16.234786Z","iopub.execute_input":"2023-06-17T09:52:16.235167Z","iopub.status.idle":"2023-06-17T11:22:59.305704Z","shell.execute_reply.started":"2023-06-17T09:52:16.235138Z","shell.execute_reply":"2023-06-17T11:22:59.300717Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = model.predict(test_generator)","metadata":{"execution":{"iopub.status.busy":"2023-06-17T11:23:20.657808Z","iopub.execute_input":"2023-06-17T11:23:20.658184Z","iopub.status.idle":"2023-06-17T11:23:41.472320Z","shell.execute_reply.started":"2023-06-17T11:23:20.658153Z","shell.execute_reply":"2023-06-17T11:23:41.471298Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = [\"dog\" if i > 0.5 else \"cat\" for i in predictions]","metadata":{"execution":{"iopub.status.busy":"2023-06-17T11:23:41.477552Z","iopub.execute_input":"2023-06-17T11:23:41.479807Z","iopub.status.idle":"2023-06-17T11:23:41.540263Z","shell.execute_reply.started":"2023-06-17T11:23:41.479772Z","shell.execute_reply":"2023-06-17T11:23:41.538987Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## The visualization of the change in accuracy and loss of training and validation data by epoch","metadata":{}},{"cell_type":"code","source":"train_accuracy = history.history[\"accuracy\"]\ntrain_loss = history.history[\"loss\"]\n\nvalidation_accuracy = history.history[\"val_accuracy\"]\nvalidation_loss = history.history[\"val_loss\"]\n\nepochs = range(len(train_accuracy))\n\nplt.plot(epochs, train_accuracy, label=\"training\")\nplt.plot(epochs,validation_accuracy, label=\"validation\")\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-06-17T11:23:41.544222Z","iopub.execute_input":"2023-06-17T11:23:41.546360Z","iopub.status.idle":"2023-06-17T11:23:41.603598Z","shell.execute_reply.started":"2023-06-17T11:23:41.546326Z","shell.execute_reply":"2023-06-17T11:23:41.601223Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Creating submission file","metadata":{}},{"cell_type":"code","source":"submission_df = pd.read_csv(\"/kaggle/input/dogs-vs-cats/sampleSubmission.csv\")","metadata":{"execution":{"iopub.status.busy":"2023-06-17T11:23:41.606211Z","iopub.status.idle":"2023-06-17T11:23:41.612044Z","shell.execute_reply.started":"2023-06-17T11:23:41.608172Z","shell.execute_reply":"2023-06-17T11:23:41.608194Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_df[\"label\"] = predictions","metadata":{"execution":{"iopub.status.busy":"2023-06-17T11:23:41.615828Z","iopub.status.idle":"2023-06-17T11:23:41.618375Z","shell.execute_reply.started":"2023-06-17T11:23:41.618017Z","shell.execute_reply":"2023-06-17T11:23:41.618040Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_df.to_csv(\"submission.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2023-06-17T11:23:41.621621Z","iopub.status.idle":"2023-06-17T11:23:41.624682Z","shell.execute_reply.started":"2023-06-17T11:23:41.624430Z","shell.execute_reply":"2023-06-17T11:23:41.624454Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Building the model using transfer learning","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.applications.inception_v3 import InceptionV3\nfrom tensorflow.keras import layers, Model","metadata":{"execution":{"iopub.status.busy":"2023-06-17T11:29:24.986779Z","iopub.execute_input":"2023-06-17T11:29:24.987170Z","iopub.status.idle":"2023-06-17T11:29:24.991629Z","shell.execute_reply.started":"2023-06-17T11:29:24.987140Z","shell.execute_reply":"2023-06-17T11:29:24.990736Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pre_trained_model = InceptionV3(include_top=False,\n                               input_shape=(150, 150, 3))\nfor layer in pre_trained_model.layers:\n    layer.trainable = False","metadata":{"execution":{"iopub.status.busy":"2023-06-17T11:27:04.517979Z","iopub.execute_input":"2023-06-17T11:27:04.518903Z","iopub.status.idle":"2023-06-17T11:27:07.752971Z","shell.execute_reply.started":"2023-06-17T11:27:04.518862Z","shell.execute_reply":"2023-06-17T11:27:07.751989Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"last_layer = pre_trained_model.get_layer(\"mixed8\")\nlast_output = last_layer.output","metadata":{"execution":{"iopub.status.busy":"2023-06-17T11:27:31.935484Z","iopub.execute_input":"2023-06-17T11:27:31.935884Z","iopub.status.idle":"2023-06-17T11:27:31.943931Z","shell.execute_reply.started":"2023-06-17T11:27:31.935844Z","shell.execute_reply":"2023-06-17T11:27:31.942839Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x = layers.Flatten()(last_output)\nx = layers.Dense(1024, activation=\"relu\")(x)\nx = layers.Dropout(0.2)(x)\nx = layers.Dense(1, activation=\"sigmoid\")(x)\n\ntransfer_model = Model(pre_trained_model.input, x)\ntransfer_model.compile(optimizer=\"adam\", loss=\"binary_crossentropy\", metrics=[\"accuracy\"])","metadata":{"execution":{"iopub.status.busy":"2023-06-17T11:30:28.327132Z","iopub.execute_input":"2023-06-17T11:30:28.327501Z","iopub.status.idle":"2023-06-17T11:30:28.412793Z","shell.execute_reply.started":"2023-06-17T11:30:28.327471Z","shell.execute_reply":"2023-06-17T11:30:28.411865Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = transfer_model.fit(train_generator, epochs=20, validation_data=validation_generator, verbose=1)","metadata":{"execution":{"iopub.status.busy":"2023-06-17T11:32:38.613729Z","iopub.execute_input":"2023-06-17T11:32:38.614858Z","iopub.status.idle":"2023-06-17T12:32:28.226344Z","shell.execute_reply.started":"2023-06-17T11:32:38.614820Z","shell.execute_reply":"2023-06-17T12:32:28.225249Z"},"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))\n\nplt.plot(epochs, acc, 'r', label='Training accuracy')\nplt.plot(epochs, val_acc, 'b', label='Validation accuracy')\nplt.title('Training and validation accuracy')\nplt.legend(loc=0)\nplt.figure()\n\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-06-17T12:32:28.228215Z","iopub.execute_input":"2023-06-17T12:32:28.228668Z","iopub.status.idle":"2023-06-17T12:32:28.564320Z","shell.execute_reply.started":"2023-06-17T12:32:28.228634Z","shell.execute_reply":"2023-06-17T12:32:28.563379Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Another pretrained model","metadata":{}},{"cell_type":"code","source":"last_layer2 = pre_trained_model.get_layer(\"mixed7\")\nlast_output2 = last_layer2.output\n\nx2 = layers.Flatten()(last_output2)\nx2 = layers.Dense(1024, activation=\"relu\")(x2)\nx2 = layers.Dropout(0.2)(x2)\nx2 = layers.Dense(1, activation=\"sigmoid\")(x2)\n\ntransfer_model2 = Model(pre_trained_model.input, x2)\ntransfer_model2.compile(optimizer=\"adam\", loss=\"binary_crossentropy\", metrics=[\"accuracy\"])\n\nhistory = transfer_model2.fit(train_generator, epochs=10, validation_data=validation_generator, verbose=1)","metadata":{"execution":{"iopub.status.busy":"2023-06-17T12:40:30.096608Z","iopub.execute_input":"2023-06-17T12:40:30.096966Z","iopub.status.idle":"2023-06-17T13:11:06.546011Z","shell.execute_reply.started":"2023-06-17T12:40:30.096937Z","shell.execute_reply":"2023-06-17T13:11:06.544924Z"},"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))\n\nplt.plot(epochs, acc, 'r', label='Training accuracy')\nplt.plot(epochs, val_acc, 'b', label='Validation accuracy')\nplt.title('Training and validation accuracy')\nplt.legend(loc=0)\nplt.figure()\n\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-06-17T13:16:36.927055Z","iopub.execute_input":"2023-06-17T13:16:36.927449Z","iopub.status.idle":"2023-06-17T13:16:37.212282Z","shell.execute_reply.started":"2023-06-17T13:16:36.927418Z","shell.execute_reply":"2023-06-17T13:16:37.211318Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}