{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"},{"sourceId":5441,"databundleVersionId":38425,"sourceType":"competition"},{"sourceId":791828,"sourceType":"datasetVersion","datasetId":119698},{"sourceId":1003830,"sourceType":"datasetVersion","datasetId":550917}],"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import warnings\nwarnings.filterwarnings('ignore')\n\nimport zipfile\n\nimport os\nfrom os import makedirs, listdir\n\nfrom shutil import copyfile\n\nfrom random import seed, random\n\nimport numpy as np\nimport pandas as pd\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom matplotlib.image import imread \nfrom PIL import Image \n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report,confusion_matrix,ConfusionMatrixDisplay\n\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential \nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.layers import Dense,MaxPooling2D,Dropout,Flatten,BatchNormalization,Conv2D\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau,EarlyStopping\n\nimport cv2","metadata":{"_kg_hide-output":true,"execution":{"iopub.status.busy":"2024-10-22T13:24:12.692541Z","iopub.execute_input":"2024-10-22T13:24:12.692916Z","iopub.status.idle":"2024-10-22T13:24:12.700650Z","shell.execute_reply.started":"2024-10-22T13:24:12.692882Z","shell.execute_reply":"2024-10-22T13:24:12.699729Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_path = \"../input/dogs-vs-cats/test1.zip\"\ntest_path  = \"../input/dogs-vs-cats/train.zip\"\n\nfiles = \"/kaggle/working/\"\n\nwith zipfile.ZipFile(train_path, 'r') as zipp:\n    zipp.extractall(files)\n    \nwith zipfile.ZipFile(test_path, 'r') as zipp:\n    zipp.extractall(files)","metadata":{"execution":{"iopub.status.busy":"2024-10-22T13:24:13.857253Z","iopub.execute_input":"2024-10-22T13:24:13.857670Z","iopub.status.idle":"2024-10-22T13:24:25.087392Z","shell.execute_reply.started":"2024-10-22T13:24:13.857632Z","shell.execute_reply":"2024-10-22T13:24:25.086540Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_dir = \"../working/train/\"\n\nfilenames = os.listdir(image_dir)\nlabels    = [x.split(\".\")[0] for x in filenames]\n\ndata = pd.DataFrame({\"filename\": filenames, \"label\": labels})\n\ndata.head()","metadata":{"execution":{"iopub.status.busy":"2024-10-22T13:24:25.088958Z","iopub.execute_input":"2024-10-22T13:24:25.089268Z","iopub.status.idle":"2024-10-22T13:24:25.124178Z","shell.execute_reply.started":"2024-10-22T13:24:25.089236Z","shell.execute_reply":"2024-10-22T13:24:25.123157Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data.shape","metadata":{"execution":{"iopub.status.busy":"2024-10-22T13:24:27.018953Z","iopub.execute_input":"2024-10-22T13:24:27.019743Z","iopub.status.idle":"2024-10-22T13:24:27.026329Z","shell.execute_reply.started":"2024-10-22T13:24:27.019695Z","shell.execute_reply":"2024-10-22T13:24:27.025247Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = data[:2000]\ndata.shape","metadata":{"execution":{"iopub.status.busy":"2024-10-22T13:24:27.588521Z","iopub.execute_input":"2024-10-22T13:24:27.588850Z","iopub.status.idle":"2024-10-22T13:24:27.594729Z","shell.execute_reply.started":"2024-10-22T13:24:27.588818Z","shell.execute_reply":"2024-10-22T13:24:27.593687Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize = (20,20)) \nplt.subplots_adjust(hspace = 0.4)\n\n\nfor i in range(5):\n    plt.subplot(10, 14,i + 1)  \n    \n    filename = 'train/' + 'dog.' + str(i) + '.jpg'\n    image    = imread(filename)\n    \n    plt.imshow(image)\n    plt.title('Dog',fontsize = 12)\n    plt.axis('off')\n\nplt.show()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2024-10-22T13:24:28.739505Z","iopub.execute_input":"2024-10-22T13:24:28.740146Z","iopub.status.idle":"2024-10-22T13:24:29.435902Z","shell.execute_reply.started":"2024-10-22T13:24:28.740103Z","shell.execute_reply":"2024-10-22T13:24:29.434919Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize = (20,20))\nplt.subplots_adjust(hspace = 0.4)\n\n\nfor i in range(5):\n    plt.subplot(1,5,i + 1)\n    \n    filename = 'train/' + 'cat.' + str(i) + '.jpg'\n    image    = imread(filename)\n    \n    plt.imshow(image)\n    plt.title('Cat',fontsize = 12)\n    plt.axis('off')\n\nplt.show()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2024-10-22T13:24:31.001253Z","iopub.execute_input":"2024-10-22T13:24:31.002195Z","iopub.status.idle":"2024-10-22T13:24:32.040056Z","shell.execute_reply.started":"2024-10-22T13:24:31.002149Z","shell.execute_reply":"2024-10-22T13:24:32.039138Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels = data['label']\n\nX_train, X_temp = train_test_split(data, test_size = 0.2, stratify = labels, random_state = 42)\n\nlabel_test_val = X_temp['label']\n\nX_test, X_val = train_test_split(X_temp, test_size = 0.5, stratify = label_test_val, random_state = 42)\n\nprint('The shape of train data',X_train.shape)\nprint('The shape of test data',X_test.shape)\nprint('The shape of validation data',X_val.shape)","metadata":{"execution":{"iopub.status.busy":"2024-10-22T13:24:35.482294Z","iopub.execute_input":"2024-10-22T13:24:35.482696Z","iopub.status.idle":"2024-10-22T13:24:35.497797Z","shell.execute_reply.started":"2024-10-22T13:24:35.482658Z","shell.execute_reply":"2024-10-22T13:24:35.496890Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_size    = 128\nimage_channel = 3 \nbat_size      = 32 ","metadata":{"execution":{"iopub.status.busy":"2024-10-22T13:24:36.235190Z","iopub.execute_input":"2024-10-22T13:24:36.235548Z","iopub.status.idle":"2024-10-22T13:24:36.239924Z","shell.execute_reply.started":"2024-10-22T13:24:36.235514Z","shell.execute_reply":"2024-10-22T13:24:36.239002Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_datagen = ImageDataGenerator(rescale = 1./255)\ntest_datagen  = ImageDataGenerator(rescale = 1./255)","metadata":{"execution":{"iopub.status.busy":"2024-10-22T13:24:39.867605Z","iopub.execute_input":"2024-10-22T13:24:39.868001Z","iopub.status.idle":"2024-10-22T13:24:39.873327Z","shell.execute_reply.started":"2024-10-22T13:24:39.867965Z","shell.execute_reply":"2024-10-22T13:24:39.872306Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_generator = train_datagen.flow_from_dataframe(X_train, directory = 'train/', x_col = 'filename', y_col = 'label',batch_size = bat_size, \n                                                    target_size = (image_size, image_size)\n                                                   )\n\nval_generator = test_datagen.flow_from_dataframe(X_val, directory = 'train/', x_col = 'filename', y_col = 'label', batch_size = bat_size,\n                                                 target_size = (image_size, image_size), shuffle = False\n                                                )\n\ntest_generator = test_datagen.flow_from_dataframe(X_test, directory = 'train/', x_col = 'filename', y_col = 'label', batch_size = bat_size,\n                                                  target_size = (image_size, image_size), shuffle = False\n                                                 )","metadata":{"execution":{"iopub.status.busy":"2024-10-22T13:24:44.019164Z","iopub.execute_input":"2024-10-22T13:24:44.019826Z","iopub.status.idle":"2024-10-22T13:24:44.060189Z","shell.execute_reply.started":"2024-10-22T13:24:44.019784Z","shell.execute_reply":"2024-10-22T13:24:44.059395Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_gen = train_datagen.flow_from_directory('/kaggle/working/dataset_dogs_vs_cats/train/', \n                                              class_mode = 'binary', target_size = (image_size, image_size), batch_size = bat_size,\n                                             )\n\nval_gen = test_datagen.flow_from_directory('/kaggle/working/dataset_dogs_vs_cats/test/', \n                                          class_mode='binary', batch_size = bat_size, target_size = (image_size, image_size), shuffle = False\n                                         )","metadata":{"execution":{"iopub.status.busy":"2024-10-22T13:24:45.772370Z","iopub.execute_input":"2024-10-22T13:24:45.773224Z","iopub.status.idle":"2024-10-22T13:24:46.467424Z","shell.execute_reply.started":"2024-10-22T13:24:45.773173Z","shell.execute_reply":"2024-10-22T13:24:46.466490Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(32,(3,3),activation = 'relu',input_shape = (image_size, image_size, image_channel))) \nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size = (2, 2)))\nmodel.add(Dropout(0.2))\n\nmodel.add(Conv2D(64,(3,3),activation = 'relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size = (2, 2)))\nmodel.add(Dropout(0.2))\n\nmodel.add(Flatten())\nmodel.add(Dense(512,activation = 'relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.2))\n\nmodel.add(Dense(2,activation = 'softmax')) \n\nmodel.summary()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2024-10-22T13:24:47.846068Z","iopub.execute_input":"2024-10-22T13:24:47.846850Z","iopub.status.idle":"2024-10-22T13:24:48.010491Z","shell.execute_reply.started":"2024-10-22T13:24:47.846807Z","shell.execute_reply":"2024-10-22T13:24:48.009692Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"learning_rate_reduction = ReduceLROnPlateau(monitor = 'val_accuracy', patience = 2, factor = 0.5,min_lr = 0.00001, verbose = 1)\nearly_stoping           = EarlyStopping(monitor = 'val_loss',patience = 2,restore_best_weights = True,verbose = 0)","metadata":{"execution":{"iopub.status.busy":"2024-10-22T13:24:49.483774Z","iopub.execute_input":"2024-10-22T13:24:49.484482Z","iopub.status.idle":"2024-10-22T13:24:49.489532Z","shell.execute_reply.started":"2024-10-22T13:24:49.484438Z","shell.execute_reply":"2024-10-22T13:24:49.488531Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer = 'adam',loss = 'binary_crossentropy', metrics = ['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-10-22T13:24:50.754726Z","iopub.execute_input":"2024-10-22T13:24:50.755490Z","iopub.status.idle":"2024-10-22T13:24:50.763995Z","shell.execute_reply.started":"2024-10-22T13:24:50.755452Z","shell.execute_reply":"2024-10-22T13:24:50.763151Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(train_generator, validation_data = val_generator, \n                    callbacks = [learning_rate_reduction], epochs = 10\n                   )","metadata":{"_kg_hide-output":true,"execution":{"iopub.status.busy":"2024-10-22T13:24:51.445257Z","iopub.execute_input":"2024-10-22T13:24:51.445620Z","iopub.status.idle":"2024-10-22T13:25:25.656385Z","shell.execute_reply.started":"2024-10-22T13:24:51.445586Z","shell.execute_reply":"2024-10-22T13:25:25.655421Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"error = pd.DataFrame(history.history)\n\nplt.figure(figsize = (18,5),dpi = 200)\nsns.set_style('darkgrid')\n\nplt.subplot(121)\nplt.title('Model Accuracy/Loss',fontsize = 15)\nplt.xlabel('Epochs',fontsize = 12)\nplt.plot(error['loss'])\nplt.plot(error['accuracy'])\n\nplt.subplot(122)\nplt.title('Validation Accuracy/Loss',fontsize = 15)\nplt.xlabel('Epochs',fontsize = 12)\nplt.plot(error['val_loss'])\nplt.plot(error['val_accuracy'])\n\nplt.show()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2024-10-22T13:25:48.535014Z","iopub.execute_input":"2024-10-22T13:25:48.535414Z","iopub.status.idle":"2024-10-22T13:25:49.325236Z","shell.execute_reply.started":"2024-10-22T13:25:48.535370Z","shell.execute_reply":"2024-10-22T13:25:49.324239Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"loss,acc = model.evaluate(train_generator,batch_size = bat_size, verbose = 0)\n\nprint('The accuracy of the model for training data is:',acc * 100)\nprint('The Loss of the model for training data is:',loss)\n\nloss,acc = model.evaluate(val_generator,batch_size = bat_size, verbose = 0)\n\nprint('The accuracy of the model for validation data is:',acc * 100)\nprint('The Loss of the model for validation data is:',loss)","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2024-10-22T13:25:53.192732Z","iopub.execute_input":"2024-10-22T13:25:53.193842Z","iopub.status.idle":"2024-10-22T13:25:55.755521Z","shell.execute_reply.started":"2024-10-22T13:25:53.193788Z","shell.execute_reply":"2024-10-22T13:25:55.754413Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"result = model.predict(test_generator,batch_size = bat_size, verbose = 0)\n\ny_pred = np.argmax(result, axis = 1)\n\ny_true = test_generator.labels\n\nloss,acc = model.evaluate(test_generator, batch_size = bat_size, verbose = 0)\n\nprint('The accuracy of the model for testing data is:',acc * 100)\nprint('The Loss of the model for testing data is:',loss)","metadata":{"execution":{"iopub.status.busy":"2024-10-22T13:25:58.911727Z","iopub.execute_input":"2024-10-22T13:25:58.912530Z","iopub.status.idle":"2024-10-22T13:26:00.204628Z","shell.execute_reply.started":"2024-10-22T13:25:58.912487Z","shell.execute_reply":"2024-10-22T13:26:00.203708Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels = ['Cat','Dog']\nprint(classification_report(y_true, y_pred,target_names = labels))","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2024-10-22T13:26:02.107518Z","iopub.execute_input":"2024-10-22T13:26:02.108177Z","iopub.status.idle":"2024-10-22T13:26:02.123121Z","shell.execute_reply.started":"2024-10-22T13:26:02.108136Z","shell.execute_reply":"2024-10-22T13:26:02.122204Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def pred_single(path):\n    img = imread(path)\n    \n    resized_image = cv2.resize(img, (image_size, image_size))\n    resized_image = np.expand_dims(resized_image, axis = 0)  \n    \n    rescaled_image = resized_image / 255.0  \n\n    predictions = model.predict(rescaled_image)\n\n    predicted_class = np.argmax(predictions)\n    \n    if predicted_class == 0:\n        pred = 'cat'\n    else:\n        pred='dog'\n        \n    return [img, pred]","metadata":{"execution":{"iopub.status.busy":"2024-10-22T13:26:03.946719Z","iopub.execute_input":"2024-10-22T13:26:03.947099Z","iopub.status.idle":"2024-10-22T13:26:03.953722Z","shell.execute_reply.started":"2024-10-22T13:26:03.947062Z","shell.execute_reply":"2024-10-22T13:26:03.952664Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cat = '/kaggle/input/microsoft-catsvsdogs-dataset/PetImages/Cat'\ndog = '/kaggle/input/microsoft-catsvsdogs-dataset/PetImages/Dog'\n\nimgs  = []\npreds = []\n\nfor index in [0, 1, 10, 100, 1000]:\n    img_path_cat = cat + '/' + str(index) + '.jpg'\n    img_path_dog = dog + '/' + str(index) + '.jpg'\n    \n    cat_output = pred_single(img_path_cat)\n    dog_output = pred_single(img_path_dog)\n    \n    imgs.append(cat_output[0])\n    preds.append(cat_output[1])\n    \n    imgs.append(dog_output[0])\n    preds.append(dog_output[1])","metadata":{"execution":{"iopub.status.busy":"2024-10-22T13:26:05.354874Z","iopub.execute_input":"2024-10-22T13:26:05.355754Z","iopub.status.idle":"2024-10-22T13:26:06.231371Z","shell.execute_reply.started":"2024-10-22T13:26:05.355711Z","shell.execute_reply":"2024-10-22T13:26:06.230237Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize = (20,20)) \nplt.subplots_adjust(hspace = 0.4)\n\nfor i in range(5):\n    plt.subplot(1, 5,i + 1) \n    plt.imshow(imgs[i])\n    plt.title(f'{preds[i]}',fontsize = 12)\n    plt.axis('off')\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-10-22T13:26:08.267435Z","iopub.execute_input":"2024-10-22T13:26:08.267823Z","iopub.status.idle":"2024-10-22T13:26:09.347053Z","shell.execute_reply.started":"2024-10-22T13:26:08.267787Z","shell.execute_reply":"2024-10-22T13:26:09.346180Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in range(5):\n    plt.subplot(1, 5,i + 1)\n    plt.imshow(imgs[i + 5])\n    plt.title(f'{preds[i + 5]}',fontsize = 12)\n    plt.axis('off')\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-10-22T13:26:14.179787Z","iopub.execute_input":"2024-10-22T13:26:14.180133Z","iopub.status.idle":"2024-10-22T13:26:14.866050Z","shell.execute_reply.started":"2024-10-22T13:26:14.180102Z","shell.execute_reply":"2024-10-22T13:26:14.865092Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"confusion_mtx = confusion_matrix(y_true, y_pred) \n\nf,ax = plt.subplots(figsize = (8,4),dpi = 200)\nsns.heatmap(confusion_mtx, annot = True, linewidths = 0.1, cmap = \"gist_yarg_r\", linecolor = \"black\", fmt = '.0f', \n            ax = ax,cbar = False, xticklabels = labels, yticklabels = labels)\n\nplt.xlabel(\"Predicted Label\",fontsize = 10)\nplt.ylabel(\"True Label\",fontsize = 10)\nplt.title(\"Confusion Matrix\",fontsize = 13)\n\nplt.show()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2024-10-22T13:26:21.516170Z","iopub.execute_input":"2024-10-22T13:26:21.516567Z","iopub.status.idle":"2024-10-22T13:26:21.775623Z","shell.execute_reply.started":"2024-10-22T13:26:21.516531Z","shell.execute_reply":"2024-10-22T13:26:21.774735Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}