{"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":"gpu","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30762,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# 1- Import Libraries","metadata":{}},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pandas as pd\nimport random as rnd\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nfrom sklearn.model_selection import train_test_split\n\nimport keras\nfrom keras.models import Sequential\nfrom keras.utils import to_categorical\nfrom keras.preprocessing.image import load_img\nfrom keras.layers import Flatten, Dense, Dropout\nfrom keras.layers import Conv2D, MaxPool2D, BatchNormalization, Activation\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\nprint(os.listdir(\"/kaggle/input/dogs-vs-cats\"))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:09:41.147486Z","iopub.execute_input":"2024-12-04T18:09:41.147734Z","iopub.status.idle":"2024-12-04T18:09:53.744810Z","shell.execute_reply.started":"2024-12-04T18:09:41.147708Z","shell.execute_reply":"2024-12-04T18:09:53.743962Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 2- Data-Constants","metadata":{}},{"cell_type":"code","source":"FAST_RUN = False\nIMAGE_WIDTH=128\nIMAGE_HEIGHT=128\nIMAGE_CHANNELS=3\nIMAGE_SIZE=(IMAGE_WIDTH, IMAGE_HEIGHT)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:09:53.746371Z","iopub.execute_input":"2024-12-04T18:09:53.746843Z","iopub.status.idle":"2024-12-04T18:09:53.751022Z","shell.execute_reply.started":"2024-12-04T18:09:53.746814Z","shell.execute_reply":"2024-12-04T18:09:53.750012Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 3- Load DataSet","metadata":{}},{"cell_type":"code","source":"# import zipfile\n\n# zip_files = ['test1', 'train']\n\n# for zip_file in zip_files:\n#     with zipfile.ZipFile(f\"../input/dogs-vs-cats/{zip_file}.zip\", \"r\") as z:\n#         z.extractall(\".\")\n#         print(f\"{zip_file} unzipped\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:09:53.752161Z","iopub.execute_input":"2024-12-04T18:09:53.752497Z","iopub.status.idle":"2024-12-04T18:09:53.779382Z","shell.execute_reply.started":"2024-12-04T18:09:53.752457Z","shell.execute_reply":"2024-12-04T18:09:53.778637Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"> ## Extract Compressed Files","metadata":{}},{"cell_type":"code","source":"import zipfile\n\npath = \"/kaggle/input/dogs-vs-cats\"\nfor zip_file in os.listdir(path)[:2]:\n    zipfile.ZipFile(f\"{path}/{zip_file}\", 'r').extractall(\".\")\n#     print(f\"{path}/{zip_file}\")\n    print(f\"{zip_file} unzipped\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:09:53.781773Z","iopub.execute_input":"2024-12-04T18:09:53.782126Z","iopub.status.idle":"2024-12-04T18:10:09.462090Z","shell.execute_reply.started":"2024-12-04T18:09:53.782089Z","shell.execute_reply":"2024-12-04T18:10:09.461196Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 4- Data Preprocessing","metadata":{}},{"cell_type":"markdown","source":"> ## Label Encoding","metadata":{}},{"cell_type":"code","source":"train_images = os.listdir(\"/kaggle/working/train\")\nCATEGORIES = []\n\nfor image_name in train_images:\n    class_name = image_name.split('.')[0]  # cat.588.jpg\n    CATEGORIES.append(0 if class_name=='cat' else 1)\n\ndf = pd.DataFrame({\"train_images\": train_images, \"CATEGORIES\": CATEGORIES})","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:10:09.463282Z","iopub.execute_input":"2024-12-04T18:10:09.463947Z","iopub.status.idle":"2024-12-04T18:10:09.497242Z","shell.execute_reply.started":"2024-12-04T18:10:09.463904Z","shell.execute_reply":"2024-12-04T18:10:09.496634Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"> ## Show DataFrame","metadata":{}},{"cell_type":"code","source":"df.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:10:09.498115Z","iopub.execute_input":"2024-12-04T18:10:09.498375Z","iopub.status.idle":"2024-12-04T18:10:09.514422Z","shell.execute_reply.started":"2024-12-04T18:10:09.498348Z","shell.execute_reply":"2024-12-04T18:10:09.513642Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.tail()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:10:09.515668Z","iopub.execute_input":"2024-12-04T18:10:09.516037Z","iopub.status.idle":"2024-12-04T18:10:09.524242Z","shell.execute_reply.started":"2024-12-04T18:10:09.515996Z","shell.execute_reply":"2024-12-04T18:10:09.523280Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.describe()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:10:09.525308Z","iopub.execute_input":"2024-12-04T18:10:09.525900Z","iopub.status.idle":"2024-12-04T18:10:09.547230Z","shell.execute_reply.started":"2024-12-04T18:10:09.525846Z","shell.execute_reply":"2024-12-04T18:10:09.546256Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df[\"CATEGORIES\"].value_counts()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:10:09.548238Z","iopub.execute_input":"2024-12-04T18:10:09.548477Z","iopub.status.idle":"2024-12-04T18:10:09.558147Z","shell.execute_reply.started":"2024-12-04T18:10:09.548453Z","shell.execute_reply":"2024-12-04T18:10:09.557279Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"> ## Visualize The Data","metadata":{}},{"cell_type":"code","source":"df[\"CATEGORIES\"].value_counts().plot.bar()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:10:09.561005Z","iopub.execute_input":"2024-12-04T18:10:09.561292Z","iopub.status.idle":"2024-12-04T18:10:09.718704Z","shell.execute_reply.started":"2024-12-04T18:10:09.561252Z","shell.execute_reply":"2024-12-04T18:10:09.717845Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"> ## *From our data we have 12500 cats and 12500 dogs*","metadata":{}},{"cell_type":"markdown","source":"> ## Show Dimensions Of Images","metadata":{}},{"cell_type":"code","source":"shapes = []\n\nfor image in df[\"train_images\"]:\n    path = os.path.join(\"/kaggle/working/train\",image)\n    image_array = plt.imread(path)\n    shapes.append(image_array.shape)\n    \nprint(pd.Series(shapes).value_counts())\n\nindex = np.argmin(shapes)\nprint(f\"\\nThe Minimum Dimension is ==> {shapes[index]}\\n\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:10:09.720046Z","iopub.execute_input":"2024-12-04T18:10:09.720376Z","iopub.status.idle":"2024-12-04T18:10:37.426842Z","shell.execute_reply.started":"2024-12-04T18:10:09.720338Z","shell.execute_reply":"2024-12-04T18:10:37.426026Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"> ## **See sample image**\n","metadata":{}},{"cell_type":"code","source":"sample = rnd.choice(train_images)\nimage = load_img(os.path.join(\"/kaggle/working/train\", sample))\nprint(type(image))\nplt.imshow(image)\nplt.axis(\"off\")\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:10:37.428120Z","iopub.execute_input":"2024-12-04T18:10:37.429031Z","iopub.status.idle":"2024-12-04T18:10:37.600338Z","shell.execute_reply.started":"2024-12-04T18:10:37.428982Z","shell.execute_reply":"2024-12-04T18:10:37.599643Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"> # Prepare data\n> Because we will use image genaretor with class_mode=\"categorical\". We need to convert column category into string. Then imagenerator will convert it one-hot encoding which is good for our classification.\n> So we will convert 1 to dog and 0 to cat","metadata":{}},{"cell_type":"code","source":"df[\"CATEGORIES\"] = df[\"CATEGORIES\"].replace({0: 'cat', 1: 'dog'})","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:10:37.601228Z","iopub.execute_input":"2024-12-04T18:10:37.601569Z","iopub.status.idle":"2024-12-04T18:10:37.611112Z","shell.execute_reply.started":"2024-12-04T18:10:37.601532Z","shell.execute_reply":"2024-12-04T18:10:37.610050Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"> # Split Data","metadata":{}},{"cell_type":"code","source":"train_df, valid_df = train_test_split(df, test_size=0.20, random_state=42)\n\ntrain_df = train_df.reset_index(drop=True)\nvalid_df = valid_df.reset_index(drop=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:10:37.612325Z","iopub.execute_input":"2024-12-04T18:10:37.612631Z","iopub.status.idle":"2024-12-04T18:10:37.630919Z","shell.execute_reply.started":"2024-12-04T18:10:37.612601Z","shell.execute_reply":"2024-12-04T18:10:37.630046Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"> # Show tarin DataFrame","metadata":{}},{"cell_type":"code","source":"train_df['CATEGORIES'].value_counts()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:10:37.631933Z","iopub.execute_input":"2024-12-04T18:10:37.632184Z","iopub.status.idle":"2024-12-04T18:10:37.641056Z","shell.execute_reply.started":"2024-12-04T18:10:37.632160Z","shell.execute_reply":"2024-12-04T18:10:37.640127Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_df['CATEGORIES'].value_counts().plot.bar()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:10:37.642048Z","iopub.execute_input":"2024-12-04T18:10:37.642338Z","iopub.status.idle":"2024-12-04T18:10:37.833705Z","shell.execute_reply.started":"2024-12-04T18:10:37.642303Z","shell.execute_reply":"2024-12-04T18:10:37.833108Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"> # Show valid DataFrame","metadata":{}},{"cell_type":"code","source":"valid_df['CATEGORIES'].value_counts()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:10:37.834578Z","iopub.execute_input":"2024-12-04T18:10:37.834856Z","iopub.status.idle":"2024-12-04T18:10:37.841813Z","shell.execute_reply.started":"2024-12-04T18:10:37.834810Z","shell.execute_reply":"2024-12-04T18:10:37.840925Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"valid_df['CATEGORIES'].value_counts().plot.bar()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:10:37.842858Z","iopub.execute_input":"2024-12-04T18:10:37.843154Z","iopub.status.idle":"2024-12-04T18:10:38.041926Z","shell.execute_reply.started":"2024-12-04T18:10:37.843129Z","shell.execute_reply":"2024-12-04T18:10:38.041052Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"> # Data Augmentation","metadata":{}},{"cell_type":"code","source":"total_train = train_df.shape[0]\ntotal_validate = valid_df.shape[0]\nbatch_size=15","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:10:38.042989Z","iopub.execute_input":"2024-12-04T18:10:38.043253Z","iopub.status.idle":"2024-12-04T18:10:38.048009Z","shell.execute_reply.started":"2024-12-04T18:10:38.043227Z","shell.execute_reply":"2024-12-04T18:10:38.047121Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"> ## Train Generator","metadata":{}},{"cell_type":"code","source":"df.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:10:38.049055Z","iopub.execute_input":"2024-12-04T18:10:38.049282Z","iopub.status.idle":"2024-12-04T18:10:38.062269Z","shell.execute_reply.started":"2024-12-04T18:10:38.049259Z","shell.execute_reply":"2024-12-04T18:10:38.061089Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_datagen = ImageDataGenerator(\n    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\n)\n\ntrain_generator = train_datagen.flow_from_dataframe(\n    train_df, \n    \"/kaggle/working/train\", \n    x_col='train_images',\n    y_col='CATEGORIES',\n    target_size=IMAGE_SIZE,\n    class_mode='categorical',\n    batch_size=batch_size\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:10:38.063523Z","iopub.execute_input":"2024-12-04T18:10:38.063798Z","iopub.status.idle":"2024-12-04T18:10:38.234020Z","shell.execute_reply.started":"2024-12-04T18:10:38.063773Z","shell.execute_reply":"2024-12-04T18:10:38.233394Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"> # Valid Generator","metadata":{}},{"cell_type":"code","source":"valid_datagen = ImageDataGenerator(rescale=1./255)\n\nvalid_generator = valid_datagen.flow_from_dataframe(\n    valid_df, \n    \"/kaggle/working/train\", \n    x_col='train_images',\n    y_col='CATEGORIES',\n    target_size=IMAGE_SIZE,\n    class_mode='categorical',\n    batch_size=batch_size\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:10:38.235107Z","iopub.execute_input":"2024-12-04T18:10:38.235463Z","iopub.status.idle":"2024-12-04T18:10:38.282426Z","shell.execute_reply.started":"2024-12-04T18:10:38.235426Z","shell.execute_reply":"2024-12-04T18:10:38.281804Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"> # See how our generator work","metadata":{}},{"cell_type":"code","source":"example_df = train_df.sample(n=1) # take 1 image-sample\nprint(example_df, \"\\n\")\n\nexample_df= example_df.reset_index(drop=True)\nprint(example_df, \"\\n\")\n\nexample_generator = train_datagen.flow_from_dataframe(\n    example_df, \n    \"/kaggle/working/train\", \n    x_col='train_images',\n    y_col='CATEGORIES',\n    target_size=IMAGE_SIZE,\n    class_mode='categorical'\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:10:38.283621Z","iopub.execute_input":"2024-12-04T18:10:38.283893Z","iopub.status.idle":"2024-12-04T18:10:38.294785Z","shell.execute_reply.started":"2024-12-04T18:10:38.283849Z","shell.execute_reply":"2024-12-04T18:10:38.293854Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"> # Show Generated Images from One-Image","metadata":{}},{"cell_type":"code","source":"plt.figure(figsize=(12, 12))\nfor i in range(0, 15):\n    plt.subplot(5, 3, i+1)\n    for X_batch, Y_batch in example_generator:\n        image = X_batch[0]\n        plt.imshow(image)\n        plt.axis('off')\n        break\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:10:38.296087Z","iopub.execute_input":"2024-12-04T18:10:38.296326Z","iopub.status.idle":"2024-12-04T18:10:39.338732Z","shell.execute_reply.started":"2024-12-04T18:10:38.296299Z","shell.execute_reply":"2024-12-04T18:10:39.337808Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 5- Build The Model","metadata":{}},{"cell_type":"markdown","source":"![image](https://i.imgur.com/ebkMGGu.jpg)","metadata":{}},{"cell_type":"markdown","source":"> * **Input Layer**: It represent input image data. It will reshape image into single diminsion array. Example your image is 64x64 = 4096, it will convert to (4096,1) array.\n> * **Conv Layer**: This layer will extract features from image.\n> * **Pooling Layer**: This layerreduce the spatial volume of input image after convolution.\n> * **Fully Connected Layer**: It connect the network from a layer to another layer\n> * **Output Layer**: It is the predicted values layer.","metadata":{}},{"cell_type":"markdown","source":"> # Fit Model","metadata":{}},{"cell_type":"code","source":"model = Sequential([\n    Conv2D(32, (3, 3), activation='relu', input_shape=(IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_CHANNELS)),\n#     BatchNormalization(),\n    MaxPool2D(pool_size=(4,4)),\n    Dropout(rate=0.25),\n    \n    Conv2D(64, (3, 3), activation='relu'),\n    BatchNormalization(),\n    MaxPool2D(pool_size=(4,4)),\n    Dropout(rate=0.25),\n    \n    Conv2D(128, (3, 3), activation='relu'),\n    BatchNormalization(),\n    MaxPool2D(pool_size=(4,4)),\n    Dropout(rate=0.25),\n    \n    Flatten(),\n    \n    Dense(512, activation='relu'),\n    Dropout(rate=0.5),\n\n    Dense(2, activation='softmax') # 2 because we have cat and dog classes\n\n])\n\n# Compile\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\n# Summary of Model\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:10:39.339744Z","iopub.execute_input":"2024-12-04T18:10:39.340030Z","iopub.status.idle":"2024-12-04T18:10:40.153773Z","shell.execute_reply.started":"2024-12-04T18:10:39.340003Z","shell.execute_reply":"2024-12-04T18:10:40.152999Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"> ## Callbacks","metadata":{}},{"cell_type":"code","source":"from keras.callbacks import EarlyStopping, ReduceLROnPlateau","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:10:40.155082Z","iopub.execute_input":"2024-12-04T18:10:40.155446Z","iopub.status.idle":"2024-12-04T18:10:40.278763Z","shell.execute_reply.started":"2024-12-04T18:10:40.155420Z","shell.execute_reply":"2024-12-04T18:10:40.277926Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"> ### Early Stop\n> To prevent over fitting we will stop the learning after 10 epochs and val_loss value not decreased","metadata":{}},{"cell_type":"code","source":"earlystop = EarlyStopping(patience=5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:10:40.279825Z","iopub.execute_input":"2024-12-04T18:10:40.280285Z","iopub.status.idle":"2024-12-04T18:10:40.288245Z","shell.execute_reply.started":"2024-12-04T18:10:40.280255Z","shell.execute_reply":"2024-12-04T18:10:40.287287Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"> ### Learning Rate Reduction\n> We will reduce the learning rate when then accuracy not increase for 2 steps","metadata":{}},{"cell_type":"code","source":"learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', \n                                            patience=2, \n                                            verbose=1, \n                                            factor=0.5, \n                                            min_lr=0.00001)\n\ncallbacks = [earlystop, learning_rate_reduction]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:10:40.292195Z","iopub.execute_input":"2024-12-04T18:10:40.292424Z","iopub.status.idle":"2024-12-04T18:10:40.299398Z","shell.execute_reply.started":"2024-12-04T18:10:40.292401Z","shell.execute_reply":"2024-12-04T18:10:40.298517Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"epochs = 3 if FAST_RUN else 10\n\nhistory = model.fit(train_generator,\n                    epochs=epochs,\n                    validation_data=valid_generator,\n#                     validation_steps=total_validate//batch_size, # 5000//15  = 333\n#                     steps_per_epoch=total_train//batch_size,     # 20000//15 = 1333\n                    callbacks=callbacks)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:10:40.300244Z","iopub.execute_input":"2024-12-04T18:10:40.300478Z","iopub.status.idle":"2024-12-04T18:26:27.693334Z","shell.execute_reply.started":"2024-12-04T18:10:40.300454Z","shell.execute_reply":"2024-12-04T18:26:27.692399Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"> # Visualize The Performance","metadata":{}},{"cell_type":"code","source":"accuracy = history.history[\"accuracy\"]\nval_accuracy = history.history[\"val_accuracy\"]\n\nloss = history.history[\"loss\"]\nval_loss = history.history[\"val_loss\"]\n\nepochs = range(len(accuracy))\n\nplt.figure(figsize=(12,6))\n\nplt.subplot(1,2,1)\nplt.plot(epochs, accuracy, 'bo', label=\"Train_Acc\")\nplt.plot(epochs, val_accuracy, 'r', label=\"val_Acc\")\nplt.legend(loc='best', shadow=True)\n\nplt.subplot(1,2,2)\nplt.plot(epochs, loss, 'bo', label=\"Train_Loss\")\nplt.plot(epochs, val_loss, 'r', label=\"val_Loss\")\nplt.legend(loc='best', shadow=True)\n\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:26:27.694592Z","iopub.execute_input":"2024-12-04T18:26:27.694868Z","iopub.status.idle":"2024-12-04T18:26:28.041659Z","shell.execute_reply.started":"2024-12-04T18:26:27.694840Z","shell.execute_reply":"2024-12-04T18:26:28.040813Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"> # The Epochs = 10 Only. We Can Increase The number of Epochs to Reach Suitable Accuracy.","metadata":{}},{"cell_type":"markdown","source":"> # Prepare Testing Data","metadata":{}},{"cell_type":"code","source":"test_file_names = os.listdir(\"/kaggle/working/test1\")\ntest_df = pd.DataFrame({'file_name': test_file_names})\n\ntotal_testing = test_df.shape[0]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:26:28.042906Z","iopub.execute_input":"2024-12-04T18:26:28.043569Z","iopub.status.idle":"2024-12-04T18:26:28.054939Z","shell.execute_reply.started":"2024-12-04T18:26:28.043526Z","shell.execute_reply":"2024-12-04T18:26:28.054129Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"> # Test The Model","metadata":{}},{"cell_type":"markdown","source":"> # Create Testing Generator","metadata":{}},{"cell_type":"code","source":"test_gen = ImageDataGenerator(rescale=1./255)\ntest_generator = test_gen.flow_from_dataframe(\n    test_df, \n    \"/kaggle/working/test1\", \n    x_col='file_name',\n    y_col=None,\n    class_mode=None,\n    target_size=IMAGE_SIZE,\n    batch_size=batch_size,\n    shuffle=False\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:26:28.055861Z","iopub.execute_input":"2024-12-04T18:26:28.056206Z","iopub.status.idle":"2024-12-04T18:26:28.147019Z","shell.execute_reply.started":"2024-12-04T18:26:28.056169Z","shell.execute_reply":"2024-12-04T18:26:28.146443Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"> # Predict","metadata":{}},{"cell_type":"code","source":"predictions = model.predict(test_generator)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:26:28.148049Z","iopub.execute_input":"2024-12-04T18:26:28.148366Z","iopub.status.idle":"2024-12-04T18:26:44.036094Z","shell.execute_reply.started":"2024-12-04T18:26:28.148329Z","shell.execute_reply":"2024-12-04T18:26:44.035349Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"> For categoral classication the prediction will come with probability of each category. So we will pick the category that have the highest probability with numpy average max","metadata":{}},{"cell_type":"code","source":"test_df[\"CATEGORIES\"] = np.argmax(predictions, axis=1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:26:44.037289Z","iopub.execute_input":"2024-12-04T18:26:44.038087Z","iopub.status.idle":"2024-12-04T18:26:44.043090Z","shell.execute_reply.started":"2024-12-04T18:26:44.038042Z","shell.execute_reply":"2024-12-04T18:26:44.042240Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"> We will convert the predict category back into our generator classes by using train_generator.class_indices. It is the classes that image generator map while converting data into computer vision","metadata":{}},{"cell_type":"code","source":"label_map = dict((v,k) for k,v in train_generator.class_indices.items())\ntest_df['CATEGORIES'] = test_df['CATEGORIES'].replace(label_map)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:26:44.044145Z","iopub.execute_input":"2024-12-04T18:26:44.044704Z","iopub.status.idle":"2024-12-04T18:26:44.057758Z","shell.execute_reply.started":"2024-12-04T18:26:44.044677Z","shell.execute_reply":"2024-12-04T18:26:44.057092Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"> From our prepare data part. We map data with {1: 'dog', 0: 'cat'}. Now we will map the result back to dog is 1 and cat is 0\n\n","metadata":{}},{"cell_type":"code","source":"test_df['CATEGORIES'] = test_df['CATEGORIES'].replace({ 'dog': 1, 'cat': 0 })","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:26:44.058921Z","iopub.execute_input":"2024-12-04T18:26:44.059459Z","iopub.status.idle":"2024-12-04T18:26:44.074021Z","shell.execute_reply.started":"2024-12-04T18:26:44.059419Z","shell.execute_reply":"2024-12-04T18:26:44.073145Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 6- Visualize The Result","metadata":{}},{"cell_type":"code","source":"test_df[\"CATEGORIES\"].value_counts().plot.bar()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:26:44.075017Z","iopub.execute_input":"2024-12-04T18:26:44.075257Z","iopub.status.idle":"2024-12-04T18:26:44.268681Z","shell.execute_reply.started":"2024-12-04T18:26:44.075233Z","shell.execute_reply":"2024-12-04T18:26:44.267790Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"> # Show Predicted Images","metadata":{}},{"cell_type":"code","source":"sample_test = test_df.head(36)\n\nplt.figure(figsize=(15,15))\n\nfor index, row in sample_test.iterrows():\n    file_name = row['file_name']\n    category = row['CATEGORIES']\n    path = os.path.join(\"/kaggle/working/test1\", file_name)\n    img = load_img(path, target_size=IMAGE_SIZE)\n    plt.subplot(6,6,index+1)\n    plt.imshow(img)\n    plt.title(f\"{file_name}\\n is ==> {'cat' if category==0 else 'dog'}\")\n    plt.axis('off')\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:26:44.269637Z","iopub.execute_input":"2024-12-04T18:26:44.269944Z","iopub.status.idle":"2024-12-04T18:26:47.370820Z","shell.execute_reply.started":"2024-12-04T18:26:44.269870Z","shell.execute_reply":"2024-12-04T18:26:47.369511Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 7- Save The Model","metadata":{}},{"cell_type":"code","source":"model.save(\"CNN.h5\")\nmodel.save_weights(\"CNN.weights.h5\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:26:47.372466Z","iopub.execute_input":"2024-12-04T18:26:47.372935Z","iopub.status.idle":"2024-12-04T18:26:47.470427Z","shell.execute_reply.started":"2024-12-04T18:26:47.372866Z","shell.execute_reply":"2024-12-04T18:26:47.469741Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 8- Submission","metadata":{}},{"cell_type":"code","source":"submission_df = test_df.copy()\nsubmission_df['id'] = submission_df['file_name'].str.split('.').str[0]\nsubmission_df['label'] = submission_df['CATEGORIES']\nsubmission_df.drop(['file_name', 'CATEGORIES'], axis=1, inplace=True)\nsubmission_df.to_csv(\"submission.csv\", index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:26:47.471499Z","iopub.execute_input":"2024-12-04T18:26:47.471736Z","iopub.status.idle":"2024-12-04T18:26:47.501575Z","shell.execute_reply.started":"2024-12-04T18:26:47.471712Z","shell.execute_reply":"2024-12-04T18:26:47.500824Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!wget https://wl-genial.cf.tsp.li/resize/728x/jpg/27e/3ac/d457dd54cdbe4443445792ccb8.jpg\nimagen = load_img('d457dd54cdbe4443445792ccb8.jpg', target_size=IMAGE_SIZE)\nimg = np.expand_dims(imagen, 0) # make 'batch' of 1\npred = model.predict(img)\n#pred = labels[\"label_names\"][np.argmax(pred)]\ncategory = np.argmax(pred)\nplt.imshow(imagen)\nplt.title(f\"esa imagen es \\n ==> {'cat' if category==0 else 'dog'}\")\nplt.axis('off')\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:26:47.502556Z","iopub.execute_input":"2024-12-04T18:26:47.502811Z","iopub.status.idle":"2024-12-04T18:26:49.340734Z","shell.execute_reply.started":"2024-12-04T18:26:47.502785Z","shell.execute_reply":"2024-12-04T18:26:49.339459Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!wget https://oglebay.com/wp-content/uploads/2022/06/IMG_5670_M-e1654806092422.jpg\nimagen = load_img('IMG_5670_M-e1654806092422.jpg', target_size=IMAGE_SIZE)\nimg = np.expand_dims(imagen, 0) # make 'batch' of 1\npred = model.predict(img)\n#pred = labels[\"label_names\"][np.argmax(pred)]\ncategory = np.argmax(pred)\nplt.imshow(imagen)\nplt.title(f\"esa imagen es \\n ==> {'cat' if category==0 else 'dog'}\")\nplt.axis('off')\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-04T18:26:49.342476Z","iopub.execute_input":"2024-12-04T18:26:49.342960Z","iopub.status.idle":"2024-12-04T18:26:50.904362Z","shell.execute_reply.started":"2024-12-04T18:26:49.342900Z","shell.execute_reply":"2024-12-04T18:26:50.903100Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}