{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.11.13","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":31193,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"This Kernel for someone want to deep dive into image classification. I use CNN for classification model. If you found this Kernel helpful please up vote it. If you have some feedback and question don't forget to comment below. \n\nI have simplier model with \n* https://www.kaggle.com/uysimty/get-start-image-classification","metadata":{}},{"cell_type":"code","source":"import os, zipfile\n\nBASE_DIR = \"../input/dogs-vs-cats\"\n\n# Распаковать train.zip\nwith zipfile.ZipFile(os.path.join(BASE_DIR, \"train.zip\"), \"r\") as z:\n    z.extractall(\"/kaggle/working/train\")\n\n# Распаковать test1.zip\nwith zipfile.ZipFile(os.path.join(BASE_DIR, \"test1.zip\"), \"r\") as z:\n    z.extractall(\"/kaggle/working/test1\")\n\ntrain_dir = \"/kaggle/working/train/train\"\ntest_dir  = \"/kaggle/working/test1/test1\"\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-05T18:24:43.017919Z","iopub.execute_input":"2025-12-05T18:24:43.018221Z","iopub.status.idle":"2025-12-05T18:24:51.560574Z","shell.execute_reply.started":"2025-12-05T18:24:43.018176Z","shell.execute_reply":"2025-12-05T18:24:51.559936Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nprint(os.listdir(\"../input\"))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-05T18:24:51.561834Z","iopub.execute_input":"2025-12-05T18:24:51.562098Z","iopub.status.idle":"2025-12-05T18:24:51.566115Z","shell.execute_reply.started":"2025-12-05T18:24:51.562075Z","shell.execute_reply":"2025-12-05T18:24:51.565383Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Import Library","metadata":{"_uuid":"fe76d1d1ded592430e7548feacfa38dc42f085d9"}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport random\nimport os\n\nprint(os.listdir(\"../input\"))\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-12-05T18:24:51.566768Z","iopub.execute_input":"2025-12-05T18:24:51.566923Z","iopub.status.idle":"2025-12-05T18:24:51.581834Z","shell.execute_reply.started":"2025-12-05T18:24:51.566911Z","shell.execute_reply":"2025-12-05T18:24:51.581291Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"BASE_DIR = \"../input/dogs-vs-cats\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-05T18:24:51.583392Z","iopub.execute_input":"2025-12-05T18:24:51.583619Z","iopub.status.idle":"2025-12-05T18:24:51.594975Z","shell.execute_reply.started":"2025-12-05T18:24:51.583601Z","shell.execute_reply":"2025-12-05T18:24:51.594439Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Define Constants","metadata":{}},{"cell_type":"code","source":"FAST_RUN = False\nIMAGE_WIDTH = 96\nIMAGE_HEIGHT = 96\nIMAGE_SIZE = (IMAGE_WIDTH, IMAGE_HEIGHT)\nIMAGE_CHANNELS=3","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-05T18:24:51.595665Z","iopub.execute_input":"2025-12-05T18:24:51.595958Z","iopub.status.idle":"2025-12-05T18:24:51.609157Z","shell.execute_reply.started":"2025-12-05T18:24:51.595942Z","shell.execute_reply":"2025-12-05T18:24:51.608562Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Prepare Traning Data","metadata":{"_uuid":"7335a579cc0268fba5d34d6f7558f33c187eedb3"}},{"cell_type":"code","source":"filenames = os.listdir(train_dir)\ncategories = []\nfor filename in filenames:\n    category = filename.split('.')[0]\n    if category == 'dog':\n        categories.append(1)\n    else:\n        categories.append(0)\n\ndf = pd.DataFrame({\n    'filename': filenames,\n    'category': categories\n})","metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true,"execution":{"iopub.status.busy":"2025-12-05T18:24:51.609781Z","iopub.execute_input":"2025-12-05T18:24:51.610011Z","iopub.status.idle":"2025-12-05T18:24:51.646377Z","shell.execute_reply.started":"2025-12-05T18:24:51.609991Z","shell.execute_reply":"2025-12-05T18:24:51.645845Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.head()","metadata":{"trusted":true,"_uuid":"915bb9ba7063ab4d5c07c542419ae119003a5f98","execution":{"iopub.status.busy":"2025-12-05T18:24:51.646991Z","iopub.execute_input":"2025-12-05T18:24:51.647185Z","iopub.status.idle":"2025-12-05T18:24:51.653971Z","shell.execute_reply.started":"2025-12-05T18:24:51.647171Z","shell.execute_reply":"2025-12-05T18:24:51.653495Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.tail()","metadata":{"trusted":true,"_uuid":"72bf69e817f67f5a2eaff8561217e22077248553","execution":{"iopub.status.busy":"2025-12-05T18:24:51.654548Z","iopub.execute_input":"2025-12-05T18:24:51.654751Z","iopub.status.idle":"2025-12-05T18:24:51.668641Z","shell.execute_reply.started":"2025-12-05T18:24:51.654721Z","shell.execute_reply":"2025-12-05T18:24:51.667896Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### See Total In count","metadata":{"_uuid":"a999484fc35b73373fafe2253ae9db7ff46fdb90"}},{"cell_type":"code","source":"df['category'].value_counts().plot.bar()","metadata":{"trusted":true,"_uuid":"fa26f0bc7a6d835a24989790b20f3c6f32946f45","execution":{"iopub.status.busy":"2025-12-05T18:24:51.669444Z","iopub.execute_input":"2025-12-05T18:24:51.669717Z","iopub.status.idle":"2025-12-05T18:24:51.785529Z","shell.execute_reply.started":"2025-12-05T18:24:51.669702Z","shell.execute_reply":"2025-12-05T18:24:51.784779Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"From our data we have 12000 cats and 12000 dogs","metadata":{"_uuid":"3a08da58107777a1dd05c4a4bf5c484484923cac"}},{"cell_type":"markdown","source":"# See sample image","metadata":{"_uuid":"400a293df3c8499059d9175f3915187074efd971"}},{"cell_type":"code","source":"sample = random.choice(filenames)\nimage = load_img(os.path.join(train_dir, sample))\nplt.imshow(image)\nplt.axis(\"off\")","metadata":{"trusted":true,"_uuid":"602b40f7353871cb161c60b5237f0da0096b2f47","execution":{"iopub.status.busy":"2025-12-05T18:24:51.787781Z","iopub.execute_input":"2025-12-05T18:24:51.788018Z","iopub.status.idle":"2025-12-05T18:24:51.972976Z","shell.execute_reply.started":"2025-12-05T18:24:51.788002Z","shell.execute_reply":"2025-12-05T18:24:51.972267Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Build Model\n\n<img src=\"https://i.imgur.com/ebkMGGu.jpg\" width=\"100%\"/>","metadata":{"_uuid":"b244e6b7715a04fc6df92dd6dfa3d35c473ca600"}},{"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":"code","source":"from keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense, Activation, BatchNormalization\n\nmodel = Sequential()\n\nmodel.add(Conv2D(16, (3, 3), activation='relu',\n                 input_shape=(IMAGE_WIDTH, IMAGE_HEIGHT, IMAGE_CHANNELS)))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(32, (3, 3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\nmodel.add(Dense(256, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\nmodel.add(Dense(2, activation='softmax'))\n\nmodel.compile(loss='categorical_crossentropy',\n              optimizer='rmsprop',\n              metrics=['accuracy'])\n\nmodel.summary()","metadata":{"trusted":true,"_uuid":"8c9f833c1441b657c779844912d0b8028218d454","execution":{"iopub.status.busy":"2025-12-05T18:24:51.973777Z","iopub.execute_input":"2025-12-05T18:24:51.974148Z","iopub.status.idle":"2025-12-05T18:24:52.140661Z","shell.execute_reply.started":"2025-12-05T18:24:51.974129Z","shell.execute_reply":"2025-12-05T18:24:52.140115Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Callbacks","metadata":{"_uuid":"bd496f6c65888a969be3703135b0b03a8a1190c8"}},{"cell_type":"code","source":"from keras.callbacks import EarlyStopping, ReduceLROnPlateau","metadata":{"trusted":true,"_uuid":"9aa032f0f6da539d23918890d2d131cc3aac8c7a","execution":{"iopub.status.busy":"2025-12-05T18:24:52.141546Z","iopub.execute_input":"2025-12-05T18:24:52.141975Z","iopub.status.idle":"2025-12-05T18:24:52.145128Z","shell.execute_reply.started":"2025-12-05T18:24:52.141956Z","shell.execute_reply":"2025-12-05T18:24:52.14444Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Early Stop**\n\nTo prevent over fitting we will stop the learning after 10 epochs and val_loss value not decreased","metadata":{"_uuid":"76c9ba4fb7f930c96b2c3e0d6b68ed9fa6a4227b"}},{"cell_type":"code","source":"earlystop = EarlyStopping(patience=10)","metadata":{"trusted":true,"_uuid":"3421c5ec428da6c0d8cc1184179a9caff1e01d1c","execution":{"iopub.status.busy":"2025-12-05T18:24:52.145922Z","iopub.execute_input":"2025-12-05T18:24:52.146134Z","iopub.status.idle":"2025-12-05T18:24:52.157955Z","shell.execute_reply.started":"2025-12-05T18:24:52.146119Z","shell.execute_reply":"2025-12-05T18:24:52.157432Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Learning Rate Reduction**\n\nWe will reduce the learning rate when then accuracy not increase for 2 steps","metadata":{"_uuid":"51d3fe52e911286433cedf6e47332948a253361e"}},{"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)","metadata":{"trusted":true,"_uuid":"8010a5661ad8924d2db24af0f3c00b1593b38901","execution":{"iopub.status.busy":"2025-12-05T18:24:52.15872Z","iopub.execute_input":"2025-12-05T18:24:52.158995Z","iopub.status.idle":"2025-12-05T18:24:52.169822Z","shell.execute_reply.started":"2025-12-05T18:24:52.158979Z","shell.execute_reply":"2025-12-05T18:24:52.169132Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"callbacks = [earlystop, learning_rate_reduction]","metadata":{"trusted":true,"_uuid":"a79cc604199469789f183096d863f7248e5f6aab","execution":{"iopub.status.busy":"2025-12-05T18:24:52.170463Z","iopub.execute_input":"2025-12-05T18:24:52.170689Z","iopub.status.idle":"2025-12-05T18:24:52.183326Z","shell.execute_reply.started":"2025-12-05T18:24:52.170667Z","shell.execute_reply":"2025-12-05T18:24:52.182724Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Prepare data","metadata":{}},{"cell_type":"markdown","source":"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\nSo we will convert 1 to dog and 0 to cat","metadata":{}},{"cell_type":"code","source":"df[\"category\"] = df[\"category\"].replace({0: 'cat', 1: 'dog'}) ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-05T18:24:52.183957Z","iopub.execute_input":"2025-12-05T18:24:52.184136Z","iopub.status.idle":"2025-12-05T18:24:52.198367Z","shell.execute_reply.started":"2025-12-05T18:24:52.184122Z","shell.execute_reply":"2025-12-05T18:24:52.197697Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_df, validate_df = train_test_split(df, test_size=0.20, random_state=42)\ntrain_df = train_df.reset_index(drop=True)\nvalidate_df = validate_df.reset_index(drop=True)","metadata":{"trusted":true,"_uuid":"4eeb7af8dcf02c4ef5ca744c8305c51a2f5cedef","execution":{"iopub.status.busy":"2025-12-05T18:24:52.198994Z","iopub.execute_input":"2025-12-05T18:24:52.199247Z","iopub.status.idle":"2025-12-05T18:24:52.214314Z","shell.execute_reply.started":"2025-12-05T18:24:52.199226Z","shell.execute_reply":"2025-12-05T18:24:52.213759Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_df['category'].value_counts().plot.bar()","metadata":{"trusted":true,"_uuid":"b84836337441705eda9d2e655665ffa14d9feead","execution":{"iopub.status.busy":"2025-12-05T18:24:52.214975Z","iopub.execute_input":"2025-12-05T18:24:52.21516Z","iopub.status.idle":"2025-12-05T18:24:52.322653Z","shell.execute_reply.started":"2025-12-05T18:24:52.215146Z","shell.execute_reply":"2025-12-05T18:24:52.322058Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"validate_df['category'].value_counts().plot.bar()","metadata":{"trusted":true,"_uuid":"19cf03f9a3c39532d6e2d06bd30be49a5afd9d57","execution":{"iopub.status.busy":"2025-12-05T18:24:52.323361Z","iopub.execute_input":"2025-12-05T18:24:52.323625Z","iopub.status.idle":"2025-12-05T18:24:52.436874Z","shell.execute_reply.started":"2025-12-05T18:24:52.323606Z","shell.execute_reply":"2025-12-05T18:24:52.436074Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"total_train = train_df.shape[0]\ntotal_validate = validate_df.shape[0]\nbatch_size=32","metadata":{"trusted":true,"_uuid":"ae3dec0361f0443132d0309d3b883ee80070cf9f","execution":{"iopub.status.busy":"2025-12-05T18:24:52.437738Z","iopub.execute_input":"2025-12-05T18:24:52.438001Z","iopub.status.idle":"2025-12-05T18:24:52.441893Z","shell.execute_reply.started":"2025-12-05T18:24:52.437975Z","shell.execute_reply":"2025-12-05T18:24:52.441153Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Traning Generator","metadata":{"_uuid":"ff760be9104f7d9492467b8d9d3405011aa77d11"}},{"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)\ntrain_generator = train_datagen.flow_from_dataframe(\n    train_df,\n    train_dir,\n    x_col='filename',\n    y_col='category',\n    target_size=IMAGE_SIZE,\n    class_mode='categorical',\n    batch_size=batch_size\n)","metadata":{"trusted":true,"_uuid":"4d1c7818703a8a4bac5c036fdea45972aa9e5e9e","execution":{"iopub.status.busy":"2025-12-05T18:24:52.442687Z","iopub.execute_input":"2025-12-05T18:24:52.442989Z","iopub.status.idle":"2025-12-05T18:24:52.60074Z","shell.execute_reply.started":"2025-12-05T18:24:52.442972Z","shell.execute_reply":"2025-12-05T18:24:52.600132Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Validation Generator","metadata":{"_uuid":"859c7b2857939c19fd2e3bb32839c9f7deb5aa3f"}},{"cell_type":"code","source":"validation_datagen = ImageDataGenerator(rescale=1./255)\nvalidation_generator = validation_datagen.flow_from_dataframe(\n    validate_df,\n    train_dir,\n    x_col='filename',\n    y_col='category',\n    target_size=IMAGE_SIZE,\n    class_mode='categorical',\n    batch_size=batch_size\n)","metadata":{"trusted":true,"_uuid":"7925e16bcacc89f4484fb6fe47e54d6420af732e","execution":{"iopub.status.busy":"2025-12-05T18:24:52.601386Z","iopub.execute_input":"2025-12-05T18:24:52.601648Z","iopub.status.idle":"2025-12-05T18:24:52.644493Z","shell.execute_reply.started":"2025-12-05T18:24:52.601629Z","shell.execute_reply":"2025-12-05T18:24:52.643966Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# See how our generator work","metadata":{"_uuid":"6e17fc1f002fedd60febb78fee5e81770640b909"}},{"cell_type":"code","source":"example_df = train_df.sample(n=1).reset_index(drop=True)\n\nexample_generator = train_datagen.flow_from_dataframe(\n    example_df,\n    train_dir,         \n    x_col='filename',\n    y_col='category',\n    target_size=IMAGE_SIZE,\n    class_mode='categorical'\n)\n\nplt.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        if len(X_batch) == 0:\n            continue\n        image = X_batch[0]\n        plt.imshow(image)\n        plt.axis(\"off\")\n        break\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"_uuid":"4252cce168ab65f88e44a8ebc2672607bc852af4","execution":{"iopub.status.busy":"2025-12-05T18:24:52.645115Z","iopub.execute_input":"2025-12-05T18:24:52.645324Z","iopub.status.idle":"2025-12-05T18:24:53.530593Z","shell.execute_reply.started":"2025-12-05T18:24:52.645308Z","shell.execute_reply":"2025-12-05T18:24:53.5289Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Seem to be nice ","metadata":{"_uuid":"810ddf1373d9db470ed48da4f30ca5a6c1274435"}},{"cell_type":"markdown","source":"# Fit Model","metadata":{"_uuid":"5cd8df64e794ed17de326b613a9819e7da977a0e"}},{"cell_type":"code","source":"epochs = 3 if FAST_RUN else 50\n\nhistory = model.fit(\n    train_generator,\n    epochs=epochs,\n    validation_data=validation_generator,\n    validation_steps=total_validate // batch_size,\n    steps_per_epoch=total_train // batch_size,\n    callbacks=callbacks\n)","metadata":{"trusted":true,"_uuid":"0836a4cc8aa0abf603e0f96573c0c4ff383ad56b","execution":{"iopub.status.busy":"2025-12-05T18:24:53.531721Z","iopub.execute_input":"2025-12-05T18:24:53.532032Z","iopub.status.idle":"2025-12-05T19:04:38.247671Z","shell.execute_reply.started":"2025-12-05T18:24:53.532004Z","shell.execute_reply":"2025-12-05T19:04:38.247013Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Save Model","metadata":{"_uuid":"aa1fbc4081ae0de2993188b2bf658a0be5bc0687"}},{"cell_type":"code","source":"model.save_weights(\"model.weights.h5\")","metadata":{"trusted":true,"_uuid":"67575a4decdaf79a915d23151626b784ffa82642","execution":{"iopub.status.busy":"2025-12-05T19:07:56.085107Z","iopub.execute_input":"2025-12-05T19:07:56.085785Z","iopub.status.idle":"2025-12-05T19:07:56.170657Z","shell.execute_reply.started":"2025-12-05T19:07:56.085761Z","shell.execute_reply":"2025-12-05T19:07:56.170084Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Virtualize Training","metadata":{"_uuid":"1b76c0a9040bc0babf0a453e567e41e22f8a1e0e"}},{"cell_type":"code","source":"fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 12))\nax1.plot(history.history['loss'], color='b', label=\"Training loss\")\nax1.plot(history.history['val_loss'], color='r', label=\"validation loss\")\nax1.set_xticks(np.arange(1, epochs, 1))\nax1.set_yticks(np.arange(0, 1, 0.1))\n\nax2.plot(history.history['accuracy'], color='b', label=\"Training accuracy\")\nax2.plot(history.history['val_accuracy'], color='r', label=\"Validation accuracy\")\n\nax2.set_xticks(np.arange(1, epochs, 1))\n\nlegend = plt.legend(loc='best', shadow=True)\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"_uuid":"79055f2dc3e2abb47bea758e0464c86ca42ab431","execution":{"iopub.status.busy":"2025-12-05T19:08:38.639163Z","iopub.execute_input":"2025-12-05T19:08:38.63946Z","iopub.status.idle":"2025-12-05T19:08:39.222878Z","shell.execute_reply.started":"2025-12-05T19:08:38.639439Z","shell.execute_reply":"2025-12-05T19:08:39.222254Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Prepare Testing Data","metadata":{"_uuid":"764dc66e4b2bc558f3a0f90b80bb802f5b3d45a8"}},{"cell_type":"code","source":"test_filenames = os.listdir(test_dir)\ntest_df = pd.DataFrame({\n    'filename': test_filenames\n})\nnb_samples = test_df.shape[0]","metadata":{"trusted":true,"_uuid":"c35e70d3e1e4834dbbf840fa0ea08c049bfcd915","execution":{"iopub.status.busy":"2025-12-05T19:08:54.437916Z","iopub.execute_input":"2025-12-05T19:08:54.438216Z","iopub.status.idle":"2025-12-05T19:08:54.449594Z","shell.execute_reply.started":"2025-12-05T19:08:54.438169Z","shell.execute_reply":"2025-12-05T19:08:54.449025Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Create Testing Generator","metadata":{"_uuid":"291bc3996dce8d05e174b27d64f03996d3e8038e"}},{"cell_type":"code","source":"test_gen = ImageDataGenerator(rescale=1./255)\ntest_generator = test_gen.flow_from_dataframe(\n    test_df,\n    test_dir,\n    x_col='filename',\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,"_uuid":"52249ec1c35fb1be3adef386be245de3794e55aa","execution":{"iopub.status.busy":"2025-12-05T19:08:56.746794Z","iopub.execute_input":"2025-12-05T19:08:56.747062Z","iopub.status.idle":"2025-12-05T19:08:56.832066Z","shell.execute_reply.started":"2025-12-05T19:08:56.747044Z","shell.execute_reply":"2025-12-05T19:08:56.83148Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Predict","metadata":{"_uuid":"2fa580afca2931ec5ce374e732d8c1789d03f2ed"}},{"cell_type":"code","source":"steps = int(np.ceil(nb_samples / batch_size))\npredict = model.predict(test_generator, steps=steps)\n","metadata":{"trusted":true,"_uuid":"4782eb23fa7d003f0e2415d995894017edb2d896","execution":{"iopub.status.busy":"2025-12-05T19:09:36.593613Z","iopub.execute_input":"2025-12-05T19:09:36.594326Z","iopub.status.idle":"2025-12-05T19:09:51.833893Z","shell.execute_reply.started":"2025-12-05T19:09:36.594302Z","shell.execute_reply":"2025-12-05T19:09:51.833092Z"}},"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['category'] = np.argmax(predict, axis=-1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-05T19:09:56.920646Z","iopub.execute_input":"2025-12-05T19:09:56.920911Z","iopub.status.idle":"2025-12-05T19:09:56.925985Z","shell.execute_reply.started":"2025-12-05T19:09:56.92089Z","shell.execute_reply":"2025-12-05T19:09:56.925244Z"}},"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['category'] = test_df['category'].replace(label_map)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-05T19:09:59.447079Z","iopub.execute_input":"2025-12-05T19:09:59.447595Z","iopub.status.idle":"2025-12-05T19:09:59.453522Z","shell.execute_reply.started":"2025-12-05T19:09:59.447573Z","shell.execute_reply":"2025-12-05T19:09:59.452878Z"}},"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","metadata":{}},{"cell_type":"code","source":"test_df['category'] = (\n    test_df['category']\n    .replace({'dog': 1, 'cat': 0})\n    .astype(int)\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-05T19:10:26.40736Z","iopub.execute_input":"2025-12-05T19:10:26.407981Z","iopub.status.idle":"2025-12-05T19:10:26.411895Z","shell.execute_reply.started":"2025-12-05T19:10:26.407961Z","shell.execute_reply":"2025-12-05T19:10:26.41134Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Virtaulize Result","metadata":{"_uuid":"b00add65fe765529e637c3a9904d710bb7eff1d8"}},{"cell_type":"code","source":"test_df['category'].value_counts().plot.bar()","metadata":{"trusted":true,"_uuid":"d0bf6dd5ff344092fa0121f70bdd60fa5a40e29c","execution":{"iopub.status.busy":"2025-12-05T19:10:29.188503Z","iopub.execute_input":"2025-12-05T19:10:29.188949Z","iopub.status.idle":"2025-12-05T19:10:29.309818Z","shell.execute_reply.started":"2025-12-05T19:10:29.188927Z","shell.execute_reply":"2025-12-05T19:10:29.309246Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### See predicted result with images","metadata":{"_uuid":"ce72a83f80d6e012b12b82c8ee3365d671a3b307"}},{"cell_type":"code","source":"sample_test = test_df.head(18)\n\nplt.figure(figsize=(12, 24))\nfor index, row in sample_test.iterrows():\n    filename = row['filename']\n    category = row['category']\n    img = load_img(\n        os.path.join(test_dir, filename),  \n        target_size=IMAGE_SIZE\n    )\n    plt.subplot(6, 3, index+1)\n    plt.imshow(img)\n    plt.xlabel(f\"{filename} ({category})\")\n    plt.axis(\"off\")\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"_uuid":"98b41dc83075e6297137fb45bf703c313dd4ae28","execution":{"iopub.status.busy":"2025-12-05T19:11:06.869431Z","iopub.execute_input":"2025-12-05T19:11:06.869721Z","iopub.status.idle":"2025-12-05T19:11:07.484454Z","shell.execute_reply.started":"2025-12-05T19:11:06.8697Z","shell.execute_reply":"2025-12-05T19:11:07.483605Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Submission","metadata":{"_uuid":"d1ca25943e73aa20a37f9fb8670ee430caeaaf1f"}},{"cell_type":"code","source":"submission_df = test_df.copy()\nsubmission_df['id'] = submission_df['filename'].str.split('.').str[0]\nsubmission_df['label'] = submission_df['category']\nsubmission_df.drop(['filename', 'category'], axis=1, inplace=True)\nsubmission_df.to_csv('submission.csv', index=False)","metadata":{"trusted":true,"_uuid":"cce9f3e2ffff0693d79d84590ed71fbbca7c3c7c","execution":{"iopub.status.busy":"2025-12-05T19:11:22.084458Z","iopub.execute_input":"2025-12-05T19:11:22.085255Z","iopub.status.idle":"2025-12-05T19:11:22.114535Z","shell.execute_reply.started":"2025-12-05T19:11:22.085226Z","shell.execute_reply":"2025-12-05T19:11:22.113945Z"}},"outputs":[],"execution_count":null}]}