{"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":{"execution":{"iopub.status.busy":"2024-10-31T13:10:26.069139Z","iopub.execute_input":"2024-10-31T13:10:26.069787Z","iopub.status.idle":"2024-10-31T13:10:40.073716Z","shell.execute_reply.started":"2024-10-31T13:10:26.069752Z","shell.execute_reply":"2024-10-31T13:10:40.072757Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-31T13:14:44.609516Z","iopub.execute_input":"2024-10-31T13:14:44.610354Z","iopub.status.idle":"2024-10-31T13:14:44.614680Z","shell.execute_reply.started":"2024-10-31T13:14:44.610314Z","shell.execute_reply":"2024-10-31T13:14:44.613747Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-31T13:14:52.063164Z","iopub.execute_input":"2024-10-31T13:14:52.063570Z","iopub.status.idle":"2024-10-31T13:14:52.067654Z","shell.execute_reply.started":"2024-10-31T13:14:52.063532Z","shell.execute_reply":"2024-10-31T13:14:52.066679Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-31T13:15:08.867462Z","iopub.execute_input":"2024-10-31T13:15:08.867831Z","iopub.status.idle":"2024-10-31T13:15:21.862465Z","shell.execute_reply.started":"2024-10-31T13:15:08.867798Z","shell.execute_reply":"2024-10-31T13:15:21.861555Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-31T13:16:19.701315Z","iopub.execute_input":"2024-10-31T13:16:19.702062Z","iopub.status.idle":"2024-10-31T13:16:19.749270Z","shell.execute_reply.started":"2024-10-31T13:16:19.702023Z","shell.execute_reply":"2024-10-31T13:16:19.748549Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"> ## Show DataFrame","metadata":{}},{"cell_type":"code","source":"df.head()","metadata":{"execution":{"iopub.status.busy":"2024-10-31T13:16:23.831301Z","iopub.execute_input":"2024-10-31T13:16:23.832137Z","iopub.status.idle":"2024-10-31T13:16:23.849178Z","shell.execute_reply.started":"2024-10-31T13:16:23.832096Z","shell.execute_reply":"2024-10-31T13:16:23.848320Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.tail()","metadata":{"execution":{"iopub.status.busy":"2024-10-31T13:16:35.142475Z","iopub.execute_input":"2024-10-31T13:16:35.142889Z","iopub.status.idle":"2024-10-31T13:16:35.153382Z","shell.execute_reply.started":"2024-10-31T13:16:35.142852Z","shell.execute_reply":"2024-10-31T13:16:35.152274Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.describe()","metadata":{"execution":{"iopub.status.busy":"2024-10-31T13:16:46.832716Z","iopub.execute_input":"2024-10-31T13:16:46.833671Z","iopub.status.idle":"2024-10-31T13:16:46.854583Z","shell.execute_reply.started":"2024-10-31T13:16:46.833618Z","shell.execute_reply":"2024-10-31T13:16:46.853630Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df[\"CATEGORIES\"].value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-10-31T13:16:54.415956Z","iopub.execute_input":"2024-10-31T13:16:54.416349Z","iopub.status.idle":"2024-10-31T13:16:54.429024Z","shell.execute_reply.started":"2024-10-31T13:16:54.416312Z","shell.execute_reply":"2024-10-31T13:16:54.428150Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"> ## Visualize The Data","metadata":{}},{"cell_type":"code","source":"df[\"CATEGORIES\"].value_counts().plot.bar()","metadata":{"execution":{"iopub.status.busy":"2024-10-31T13:16:59.757572Z","iopub.execute_input":"2024-10-31T13:16:59.757918Z","iopub.status.idle":"2024-10-31T13:17:00.003988Z","shell.execute_reply.started":"2024-10-31T13:16:59.757886Z","shell.execute_reply":"2024-10-31T13:17:00.003096Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-31T13:17:20.291324Z","iopub.execute_input":"2024-10-31T13:17:20.291996Z","iopub.status.idle":"2024-10-31T13:17:50.469792Z","shell.execute_reply.started":"2024-10-31T13:17:20.291956Z","shell.execute_reply":"2024-10-31T13:17:50.468791Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-31T13:21:40.369949Z","iopub.execute_input":"2024-10-31T13:21:40.370342Z","iopub.status.idle":"2024-10-31T13:21:40.651191Z","shell.execute_reply.started":"2024-10-31T13:21:40.370304Z","shell.execute_reply":"2024-10-31T13:21:40.650320Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-31T13:21:52.031402Z","iopub.execute_input":"2024-10-31T13:21:52.031797Z","iopub.status.idle":"2024-10-31T13:21:52.039916Z","shell.execute_reply.started":"2024-10-31T13:21:52.031759Z","shell.execute_reply":"2024-10-31T13:21:52.038922Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-31T13:21:58.144159Z","iopub.execute_input":"2024-10-31T13:21:58.145090Z","iopub.status.idle":"2024-10-31T13:21:58.160377Z","shell.execute_reply.started":"2024-10-31T13:21:58.145046Z","shell.execute_reply":"2024-10-31T13:21:58.159383Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"> # Show tarin DataFrame","metadata":{}},{"cell_type":"code","source":"train_df['CATEGORIES'].value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-10-31T13:22:11.044127Z","iopub.execute_input":"2024-10-31T13:22:11.044523Z","iopub.status.idle":"2024-10-31T13:22:11.054429Z","shell.execute_reply.started":"2024-10-31T13:22:11.044464Z","shell.execute_reply":"2024-10-31T13:22:11.053538Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df['CATEGORIES'].value_counts().plot.bar()","metadata":{"execution":{"iopub.status.busy":"2024-10-31T13:22:15.586140Z","iopub.execute_input":"2024-10-31T13:22:15.586976Z","iopub.status.idle":"2024-10-31T13:22:15.807951Z","shell.execute_reply.started":"2024-10-31T13:22:15.586935Z","shell.execute_reply":"2024-10-31T13:22:15.807030Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"> # Show valid DataFrame","metadata":{}},{"cell_type":"code","source":"valid_df['CATEGORIES'].value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-10-31T13:22:22.403919Z","iopub.execute_input":"2024-10-31T13:22:22.404308Z","iopub.status.idle":"2024-10-31T13:22:22.414733Z","shell.execute_reply.started":"2024-10-31T13:22:22.404271Z","shell.execute_reply":"2024-10-31T13:22:22.413093Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"valid_df['CATEGORIES'].value_counts().plot.bar()","metadata":{"execution":{"iopub.status.busy":"2024-10-31T13:22:25.869382Z","iopub.execute_input":"2024-10-31T13:22:25.869771Z","iopub.status.idle":"2024-10-31T13:22:26.021152Z","shell.execute_reply.started":"2024-10-31T13:22:25.869733Z","shell.execute_reply":"2024-10-31T13:22:26.020211Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-31T13:22:38.764770Z","iopub.execute_input":"2024-10-31T13:22:38.765659Z","iopub.status.idle":"2024-10-31T13:22:38.770640Z","shell.execute_reply.started":"2024-10-31T13:22:38.765606Z","shell.execute_reply":"2024-10-31T13:22:38.769568Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"> ## Train Generator","metadata":{}},{"cell_type":"code","source":"df.head()","metadata":{"execution":{"iopub.status.busy":"2024-10-31T13:22:41.389956Z","iopub.execute_input":"2024-10-31T13:22:41.390590Z","iopub.status.idle":"2024-10-31T13:22:41.399679Z","shell.execute_reply.started":"2024-10-31T13:22:41.390542Z","shell.execute_reply":"2024-10-31T13:22:41.398757Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-31T13:22:47.478877Z","iopub.execute_input":"2024-10-31T13:22:47.479634Z","iopub.status.idle":"2024-10-31T13:22:47.722241Z","shell.execute_reply.started":"2024-10-31T13:22:47.479591Z","shell.execute_reply":"2024-10-31T13:22:47.721326Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-31T13:23:05.993515Z","iopub.execute_input":"2024-10-31T13:23:05.993905Z","iopub.status.idle":"2024-10-31T13:23:06.062377Z","shell.execute_reply.started":"2024-10-31T13:23:05.993868Z","shell.execute_reply":"2024-10-31T13:23:06.061477Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-31T13:23:11.202474Z","iopub.execute_input":"2024-10-31T13:23:11.203166Z","iopub.status.idle":"2024-10-31T13:23:11.216536Z","shell.execute_reply.started":"2024-10-31T13:23:11.203128Z","shell.execute_reply":"2024-10-31T13:23:11.215621Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-31T13:23:33.386127Z","iopub.execute_input":"2024-10-31T13:23:33.386547Z","iopub.status.idle":"2024-10-31T13:23:34.482104Z","shell.execute_reply.started":"2024-10-31T13:23:33.386507Z","shell.execute_reply":"2024-10-31T13:23:34.481038Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-31T13:24:28.794188Z","iopub.execute_input":"2024-10-31T13:24:28.794958Z","iopub.status.idle":"2024-10-31T13:24:29.570565Z","shell.execute_reply.started":"2024-10-31T13:24:28.794911Z","shell.execute_reply":"2024-10-31T13:24:29.569690Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"> ## Callbacks","metadata":{}},{"cell_type":"code","source":"from keras.callbacks import EarlyStopping, ReduceLROnPlateau","metadata":{"execution":{"iopub.status.busy":"2024-10-31T13:24:42.891885Z","iopub.execute_input":"2024-10-31T13:24:42.892577Z","iopub.status.idle":"2024-10-31T13:24:42.897592Z","shell.execute_reply.started":"2024-10-31T13:24:42.892533Z","shell.execute_reply":"2024-10-31T13:24:42.896642Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-31T13:24:47.407263Z","iopub.execute_input":"2024-10-31T13:24:47.407973Z","iopub.status.idle":"2024-10-31T13:24:47.412210Z","shell.execute_reply.started":"2024-10-31T13:24:47.407932Z","shell.execute_reply":"2024-10-31T13:24:47.411262Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-31T13:25:02.016528Z","iopub.execute_input":"2024-10-31T13:25:02.017236Z","iopub.status.idle":"2024-10-31T13:25:02.021772Z","shell.execute_reply.started":"2024-10-31T13:25:02.017194Z","shell.execute_reply":"2024-10-31T13:25:02.020730Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-31T13:25:13.057966Z","iopub.execute_input":"2024-10-31T13:25:13.058347Z","iopub.status.idle":"2024-10-31T13:43:20.674171Z","shell.execute_reply.started":"2024-10-31T13:25:13.058311Z","shell.execute_reply":"2024-10-31T13:43:20.673333Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-31T13:54:44.713058Z","iopub.execute_input":"2024-10-31T13:54:44.713439Z","iopub.status.idle":"2024-10-31T13:54:45.133893Z","shell.execute_reply.started":"2024-10-31T13:54:44.713405Z","shell.execute_reply":"2024-10-31T13:54:45.132932Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-31T13:56:46.373630Z","iopub.execute_input":"2024-10-31T13:56:46.374382Z","iopub.status.idle":"2024-10-31T13:56:46.387935Z","shell.execute_reply.started":"2024-10-31T13:56:46.374339Z","shell.execute_reply":"2024-10-31T13:56:46.386913Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-31T13:56:51.314454Z","iopub.execute_input":"2024-10-31T13:56:51.315313Z","iopub.status.idle":"2024-10-31T13:56:51.448689Z","shell.execute_reply.started":"2024-10-31T13:56:51.315263Z","shell.execute_reply":"2024-10-31T13:56:51.447698Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"> # Predict","metadata":{}},{"cell_type":"code","source":"predictions = model.predict(test_generator)","metadata":{"execution":{"iopub.status.busy":"2024-10-31T13:56:57.875084Z","iopub.execute_input":"2024-10-31T13:56:57.875505Z","iopub.status.idle":"2024-10-31T13:57:16.500931Z","shell.execute_reply.started":"2024-10-31T13:56:57.875445Z","shell.execute_reply":"2024-10-31T13:57:16.499916Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-31T14:01:55.292467Z","iopub.execute_input":"2024-10-31T14:01:55.293629Z","iopub.status.idle":"2024-10-31T14:01:55.299075Z","shell.execute_reply.started":"2024-10-31T14:01:55.293583Z","shell.execute_reply":"2024-10-31T14:01:55.298168Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-31T14:02:02.191551Z","iopub.execute_input":"2024-10-31T14:02:02.192189Z","iopub.status.idle":"2024-10-31T14:02:02.199151Z","shell.execute_reply.started":"2024-10-31T14:02:02.192148Z","shell.execute_reply":"2024-10-31T14:02:02.198369Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-31T14:02:14.949552Z","iopub.execute_input":"2024-10-31T14:02:14.950401Z","iopub.status.idle":"2024-10-31T14:02:14.956112Z","shell.execute_reply.started":"2024-10-31T14:02:14.950351Z","shell.execute_reply":"2024-10-31T14:02:14.955025Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 6- Visualize The Result","metadata":{}},{"cell_type":"code","source":"test_df[\"CATEGORIES\"].value_counts().plot.bar()","metadata":{"execution":{"iopub.status.busy":"2024-10-31T14:02:18.605058Z","iopub.execute_input":"2024-10-31T14:02:18.605428Z","iopub.status.idle":"2024-10-31T14:02:18.842717Z","shell.execute_reply.started":"2024-10-31T14:02:18.605394Z","shell.execute_reply":"2024-10-31T14:02:18.841751Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-31T14:02:23.630679Z","iopub.execute_input":"2024-10-31T14:02:23.631061Z","iopub.status.idle":"2024-10-31T14:02:27.507953Z","shell.execute_reply.started":"2024-10-31T14:02:23.631023Z","shell.execute_reply":"2024-10-31T14:02:27.506547Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 7- Save The Model","metadata":{}},{"cell_type":"code","source":"model.save(\"CNN.h5\")\nmodel.save_weights(\"CNN.weights.h5\")","metadata":{"execution":{"iopub.status.busy":"2024-10-31T14:04:43.121663Z","iopub.execute_input":"2024-10-31T14:04:43.122410Z","iopub.status.idle":"2024-10-31T14:04:43.231070Z","shell.execute_reply.started":"2024-10-31T14:04:43.122371Z","shell.execute_reply":"2024-10-31T14:04:43.230180Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-31T14:04:48.130901Z","iopub.execute_input":"2024-10-31T14:04:48.131328Z","iopub.status.idle":"2024-10-31T14:04:48.175156Z","shell.execute_reply.started":"2024-10-31T14:04:48.131287Z","shell.execute_reply":"2024-10-31T14:04:48.174277Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-31T14:04:51.140564Z","iopub.execute_input":"2024-10-31T14:04:51.141049Z","iopub.status.idle":"2024-10-31T14:04:53.116309Z","shell.execute_reply.started":"2024-10-31T14:04:51.141004Z","shell.execute_reply":"2024-10-31T14:04:53.115257Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-10-31T14:04:59.563822Z","iopub.execute_input":"2024-10-31T14:04:59.564580Z","iopub.status.idle":"2024-10-31T14:05:01.258370Z","shell.execute_reply.started":"2024-10-31T14:04:59.564535Z","shell.execute_reply":"2024-10-31T14:05:01.257310Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}