{"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":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport os\nimport zipfile","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-07-17T20:38:38.513487Z","iopub.execute_input":"2023-07-17T20:38:38.513791Z","iopub.status.idle":"2023-07-17T20:38:40.194097Z","shell.execute_reply.started":"2023-07-17T20:38:38.513764Z","shell.execute_reply":"2023-07-17T20:38:40.193101Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nimport tensorflow as tf\nfrom keras.models import Sequential, Model\nfrom keras.layers import Dense, Conv2D, MaxPool2D, Dropout, Flatten\nfrom keras.applications.vgg16 import VGG16, preprocess_input\nfrom PIL import Image\nfrom keras.preprocessing.image import ImageDataGenerator\n\nbatch_size = 128","metadata":{"execution":{"iopub.status.busy":"2023-07-17T20:38:40.196567Z","iopub.execute_input":"2023-07-17T20:38:40.197316Z","iopub.status.idle":"2023-07-17T20:38:50.329337Z","shell.execute_reply.started":"2023-07-17T20:38:40.197280Z","shell.execute_reply":"2023-07-17T20:38:50.328265Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"os.listdir(\"/kaggle/input/dogs-vs-cats\")","metadata":{"execution":{"iopub.status.busy":"2023-07-17T20:38:50.331994Z","iopub.execute_input":"2023-07-17T20:38:50.333073Z","iopub.status.idle":"2023-07-17T20:38:50.344184Z","shell.execute_reply.started":"2023-07-17T20:38:50.333033Z","shell.execute_reply":"2023-07-17T20:38:50.343139Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_zip_path = \"/kaggle/input/dogs-vs-cats/train.zip\"\ntest_zip_path = \"/kaggle/input/dogs-vs-cats/test1.zip\"\nunzipped_Path = \"/kaggle/working/training/\"\n\nwith zipfile.ZipFile(train_zip_path, 'r') as zip_:\n    zip_.extractall(unzipped_Path)\n    \nwith zipfile.ZipFile(test_zip_path, 'r') as zip_:\n    zip_.extractall(unzipped_Path)","metadata":{"execution":{"iopub.status.busy":"2023-07-17T20:38:50.345592Z","iopub.execute_input":"2023-07-17T20:38:50.347076Z","iopub.status.idle":"2023-07-17T20:39:08.531793Z","shell.execute_reply.started":"2023-07-17T20:38:50.347042Z","shell.execute_reply":"2023-07-17T20:39:08.530697Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"images = os.listdir('/kaggle/working/training/train')\nimages_ = os.listdir('/kaggle/working/training/test1')\n\ntrain_Data = pd.DataFrame({'Image': image, 'Category': 0 if image.split(\".\")[0] == 'cat' else 1} for image in images)\ntest_Data = pd.DataFrame({'Image': image} for image in images_)\n\ntrain_Data","metadata":{"execution":{"iopub.status.busy":"2023-07-17T20:39:08.535713Z","iopub.execute_input":"2023-07-17T20:39:08.536141Z","iopub.status.idle":"2023-07-17T20:39:08.637583Z","shell.execute_reply.started":"2023-07-17T20:39:08.536102Z","shell.execute_reply":"2023-07-17T20:39:08.636640Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig = plt.figure(1, figsize=(16, 16))\n\nfor i in range(16):\n    plt.subplot(4, 4, i+1)\n    plt.imshow(Image.open(unzipped_Path + 'train/' + train_Data['Image'][i]))\n    \nplt.tight_layout\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-07-17T20:39:08.639161Z","iopub.execute_input":"2023-07-17T20:39:08.639539Z","iopub.status.idle":"2023-07-17T20:39:11.832636Z","shell.execute_reply.started":"2023-07-17T20:39:08.639504Z","shell.execute_reply":"2023-07-17T20:39:11.831450Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig = plt.figure(1, figsize=(16, 16))\n\nfor i in range(16):\n    plt.subplot(4, 4, i+1)\n    plt.imshow(Image.open(unzipped_Path + 'train/' + train_Data.query(\"Category == 1\").Image.values[i]))\n    \nplt.tight_layout\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-07-17T20:39:11.834244Z","iopub.execute_input":"2023-07-17T20:39:11.834863Z","iopub.status.idle":"2023-07-17T20:39:15.571571Z","shell.execute_reply.started":"2023-07-17T20:39:11.834775Z","shell.execute_reply":"2023-07-17T20:39:15.568947Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig = plt.figure(1, figsize=(16, 16))\n\nfor i in range(16):\n    plt.subplot(4, 4, i+1)\n    plt.imshow(Image.open(unzipped_Path + 'train/' + train_Data.query(\"Category == 0\").Image.values[i]))\n    \nplt.tight_layout\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-07-17T20:39:15.572860Z","iopub.execute_input":"2023-07-17T20:39:15.579508Z","iopub.status.idle":"2023-07-17T20:39:18.695152Z","shell.execute_reply.started":"2023-07-17T20:39:15.579470Z","shell.execute_reply":"2023-07-17T20:39:18.694106Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_model = VGG16(\n    weights = \"imagenet\", \n    input_shape = (224, 224, 3),\n    include_top = False\n)\n\n\nfor layers in base_model.layers:\n    layers.trainable = False\n\n\ndef vgg16_pretrained():\n    \n    model = Sequential(\n        [\n            base_model,\n            \n            Conv2D(128, (3,3), activation = \"relu\"),\n            MaxPool2D(),\n            Dropout(0.3),\n            \n            Flatten(),\n            \n            Dense(100, activation = \"relu\"),\n            Dropout(0.3),\n            \n            Dense(64, activation = \"relu\"),\n            Dense(2, activation = \"softmax\")\n        ]\n    )\n    \n    return model\n\ntf.keras.backend.clear_session()\n\ntrain_data, val_data = train_test_split(train_Data, \n                                        test_size = 0.2, \n                                        stratify = train_Data[\"Category\"], \n                                        random_state = 42)","metadata":{"execution":{"iopub.status.busy":"2023-07-17T20:39:18.696720Z","iopub.execute_input":"2023-07-17T20:39:18.697326Z","iopub.status.idle":"2023-07-17T20:39:24.668058Z","shell.execute_reply.started":"2023-07-17T20:39:18.697291Z","shell.execute_reply":"2023-07-17T20:39:24.667018Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_datagen = ImageDataGenerator(preprocessing_function = preprocess_input)\nval_datagen = ImageDataGenerator(preprocessing_function = preprocess_input)","metadata":{"execution":{"iopub.status.busy":"2023-07-17T20:39:24.669438Z","iopub.execute_input":"2023-07-17T20:39:24.669793Z","iopub.status.idle":"2023-07-17T20:39:24.676951Z","shell.execute_reply.started":"2023-07-17T20:39:24.669760Z","shell.execute_reply":"2023-07-17T20:39:24.674426Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data['Category'] = train_data['Category'].astype(str)\nval_data['Category'] = val_data['Category'].astype(str)\n\ntrain_generator = train_datagen.flow_from_dataframe(\n    dataframe = train_data,\n    directory = unzipped_Path + \"train/\",\n    x_col = \"Image\",\n    y_col = \"Category\",\n    class_mode = \"categorical\",\n    target_size = (224, 224),\n    batch_size = batch_size,\n    seed = 42,\n)\n\nval_generator = val_datagen.flow_from_dataframe(\n    dataframe = val_data,\n    directory = unzipped_Path + \"train/\",\n    x_col = \"Image\",\n    y_col = \"Category\",\n    class_mode = \"categorical\",\n    target_size = (224, 224),\n    batch_size = batch_size,\n    seed = 42,\n    shuffle = False\n)","metadata":{"execution":{"iopub.status.busy":"2023-07-17T20:39:24.678301Z","iopub.execute_input":"2023-07-17T20:39:24.679334Z","iopub.status.idle":"2023-07-17T20:39:25.025127Z","shell.execute_reply.started":"2023-07-17T20:39:24.679295Z","shell.execute_reply":"2023-07-17T20:39:25.024225Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = vgg16_pretrained()\n\nmodel.compile(loss = \"categorical_crossentropy\", optimizer = \"adam\", metrics = \"accuracy\")\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2023-07-17T20:39:25.026451Z","iopub.execute_input":"2023-07-17T20:39:25.027287Z","iopub.status.idle":"2023-07-17T20:39:25.225042Z","shell.execute_reply.started":"2023-07-17T20:39:25.027252Z","shell.execute_reply":"2023-07-17T20:39:25.224210Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(train_generator, epochs=10, batch_size=batch_size, validation_data=val_generator)","metadata":{"execution":{"iopub.status.busy":"2023-07-17T20:39:25.226198Z","iopub.execute_input":"2023-07-17T20:39:25.226575Z","iopub.status.idle":"2023-07-17T21:02:48.126523Z","shell.execute_reply.started":"2023-07-17T20:39:25.226538Z","shell.execute_reply":"2023-07-17T21:02:48.125478Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_datagen = ImageDataGenerator(preprocessing_function = preprocess_input)\n\ntest_generator = test_datagen.flow_from_dataframe(\n    dataframe = test_Data,\n    directory = unzipped_Path + \"test1/\",\n    x_col = \"Image\",\n    y_col = None,\n    class_mode = None,\n    target_size = (224, 224),\n    batch_size = batch_size,\n    seed = 42,\n    shuffle = False\n)","metadata":{"execution":{"iopub.status.busy":"2023-07-17T21:03:44.981164Z","iopub.execute_input":"2023-07-17T21:03:44.981538Z","iopub.status.idle":"2023-07-17T21:03:45.117188Z","shell.execute_reply.started":"2023-07-17T21:03:44.981505Z","shell.execute_reply":"2023-07-17T21:03:45.116292Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_preds = model.predict(test_generator)","metadata":{"execution":{"iopub.status.busy":"2023-07-17T21:03:48.142549Z","iopub.execute_input":"2023-07-17T21:03:48.142983Z","iopub.status.idle":"2023-07-17T21:04:49.789519Z","shell.execute_reply.started":"2023-07-17T21:03:48.142938Z","shell.execute_reply":"2023-07-17T21:04:49.788508Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predicted_classes = np.argmax(test_preds, axis=1)\n","metadata":{"execution":{"iopub.status.busy":"2023-07-17T21:05:12.994419Z","iopub.execute_input":"2023-07-17T21:05:12.995103Z","iopub.status.idle":"2023-07-17T21:05:12.999661Z","shell.execute_reply.started":"2023-07-17T21:05:12.995068Z","shell.execute_reply":"2023-07-17T21:05:12.998639Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig = plt.figure(1, figsize=(16, 16))\n\nfor i in range(81):\n    plt.subplot(9, 9, i+1)\n    plt.imshow(Image.open(unzipped_Path + 'test1/' + test_Data['Image'][i]))\n    plt.title(f\"Predicted as {'dog' if predicted_classes[i] == 1 else 'cat'}\", fontsize=8)\n    \nplt.tight_layout\nplt.show","metadata":{"execution":{"iopub.status.busy":"2023-07-17T21:05:23.993650Z","iopub.execute_input":"2023-07-17T21:05:23.994931Z","iopub.status.idle":"2023-07-17T21:05:38.097718Z","shell.execute_reply.started":"2023-07-17T21:05:23.994887Z","shell.execute_reply":"2023-07-17T21:05:38.096880Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}