{"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":"nvidiaTeslaT4","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-05T19:33:08.861362Z","iopub.execute_input":"2025-12-05T19:33:08.861533Z","iopub.status.idle":"2025-12-05T19:33:16.96314Z","shell.execute_reply.started":"2025-12-05T19:33:08.861517Z","shell.execute_reply":"2025-12-05T19:33:16.962361Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nprint(os.listdir(\"../input\"))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-05T19:33:16.964865Z","iopub.execute_input":"2025-12-05T19:33:16.965221Z","iopub.status.idle":"2025-12-05T19:33:16.97025Z","shell.execute_reply.started":"2025-12-05T19:33:16.965194Z","shell.execute_reply":"2025-12-05T19:33:16.968892Z"}},"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-05T19:33:16.973995Z","iopub.execute_input":"2025-12-05T19:33:16.974397Z","iopub.status.idle":"2025-12-05T19:33:32.467033Z","shell.execute_reply.started":"2025-12-05T19:33:16.974373Z","shell.execute_reply":"2025-12-05T19:33:32.466369Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"BASE_DIR = \"../input/dogs-vs-cats\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-05T19:33:32.467725Z","iopub.execute_input":"2025-12-05T19:33:32.468229Z","iopub.status.idle":"2025-12-05T19:33:32.471581Z","shell.execute_reply.started":"2025-12-05T19:33:32.468206Z","shell.execute_reply":"2025-12-05T19:33:32.471043Z"}},"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-05T19:33:32.472179Z","iopub.execute_input":"2025-12-05T19:33:32.472376Z","iopub.status.idle":"2025-12-05T19:33:33.499438Z","shell.execute_reply.started":"2025-12-05T19:33:32.472357Z","shell.execute_reply":"2025-12-05T19:33:33.498497Z"}},"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-05T19:33:33.501959Z","iopub.execute_input":"2025-12-05T19:33:33.502445Z","iopub.status.idle":"2025-12-05T19:33:33.536575Z","shell.execute_reply.started":"2025-12-05T19:33:33.502424Z","shell.execute_reply":"2025-12-05T19:33:33.536046Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.head()","metadata":{"trusted":true,"_uuid":"915bb9ba7063ab4d5c07c542419ae119003a5f98","execution":{"iopub.status.busy":"2025-12-05T19:33:33.537246Z","iopub.execute_input":"2025-12-05T19:33:33.537485Z","iopub.status.idle":"2025-12-05T19:33:33.556493Z","shell.execute_reply.started":"2025-12-05T19:33:33.537468Z","shell.execute_reply":"2025-12-05T19:33:33.555805Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.tail()","metadata":{"trusted":true,"_uuid":"72bf69e817f67f5a2eaff8561217e22077248553","execution":{"iopub.status.busy":"2025-12-05T19:33:33.557248Z","iopub.execute_input":"2025-12-05T19:33:33.557757Z","iopub.status.idle":"2025-12-05T19:33:33.565086Z","shell.execute_reply.started":"2025-12-05T19:33:33.557731Z","shell.execute_reply":"2025-12-05T19:33:33.56437Z"}},"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-05T19:33:33.565917Z","iopub.execute_input":"2025-12-05T19:33:33.566145Z","iopub.status.idle":"2025-12-05T19:33:33.796425Z","shell.execute_reply.started":"2025-12-05T19:33:33.566128Z","shell.execute_reply":"2025-12-05T19:33:33.795642Z"}},"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-05T19:33:33.797176Z","iopub.execute_input":"2025-12-05T19:33:33.797361Z","iopub.status.idle":"2025-12-05T19:33:33.896971Z","shell.execute_reply.started":"2025-12-05T19:33:33.797346Z","shell.execute_reply":"2025-12-05T19:33:33.896369Z"}},"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-05T19:33:33.897636Z","iopub.execute_input":"2025-12-05T19:33:33.897945Z","iopub.status.idle":"2025-12-05T19:33:36.028613Z","shell.execute_reply.started":"2025-12-05T19:33:33.897928Z","shell.execute_reply":"2025-12-05T19:33:36.027746Z"}},"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-05T19:33:36.029477Z","iopub.execute_input":"2025-12-05T19:33:36.029743Z","iopub.status.idle":"2025-12-05T19:33:36.03443Z","shell.execute_reply.started":"2025-12-05T19:33:36.029719Z","shell.execute_reply":"2025-12-05T19:33:36.033474Z"}},"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-05T19:33:36.035353Z","iopub.execute_input":"2025-12-05T19:33:36.035615Z","iopub.status.idle":"2025-12-05T19:33:36.052179Z","shell.execute_reply.started":"2025-12-05T19:33:36.035595Z","shell.execute_reply":"2025-12-05T19:33:36.051389Z"}},"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-05T19:33:36.052935Z","iopub.execute_input":"2025-12-05T19:33:36.053113Z","iopub.status.idle":"2025-12-05T19:33:36.064968Z","shell.execute_reply.started":"2025-12-05T19:33:36.053099Z","shell.execute_reply":"2025-12-05T19:33:36.064382Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"callbacks = [earlystop, learning_rate_reduction]","metadata":{"trusted":true,"_uuid":"a79cc604199469789f183096d863f7248e5f6aab","execution":{"iopub.status.busy":"2025-12-05T19:33:36.065651Z","iopub.execute_input":"2025-12-05T19:33:36.065969Z","iopub.status.idle":"2025-12-05T19:33:36.076541Z","shell.execute_reply.started":"2025-12-05T19:33:36.065942Z","shell.execute_reply":"2025-12-05T19:33:36.076028Z"}},"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-05T19:33:36.077237Z","iopub.execute_input":"2025-12-05T19:33:36.077504Z","iopub.status.idle":"2025-12-05T19:33:36.089353Z","shell.execute_reply.started":"2025-12-05T19:33:36.077478Z","shell.execute_reply":"2025-12-05T19:33:36.088654Z"}},"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-05T19:33:36.090236Z","iopub.execute_input":"2025-12-05T19:33:36.090622Z","iopub.status.idle":"2025-12-05T19:33:36.101422Z","shell.execute_reply.started":"2025-12-05T19:33:36.090604Z","shell.execute_reply":"2025-12-05T19:33:36.100775Z"}},"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-05T19:33:36.102166Z","iopub.execute_input":"2025-12-05T19:33:36.102414Z","iopub.status.idle":"2025-12-05T19:33:36.218823Z","shell.execute_reply.started":"2025-12-05T19:33:36.102397Z","shell.execute_reply":"2025-12-05T19:33:36.218261Z"}},"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-05T19:33:36.219516Z","iopub.execute_input":"2025-12-05T19:33:36.219742Z","iopub.status.idle":"2025-12-05T19:33:36.352522Z","shell.execute_reply.started":"2025-12-05T19:33:36.219722Z","shell.execute_reply":"2025-12-05T19:33:36.351917Z"}},"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-05T19:33:36.35324Z","iopub.execute_input":"2025-12-05T19:33:36.353495Z","iopub.status.idle":"2025-12-05T19:33:36.35729Z","shell.execute_reply.started":"2025-12-05T19:33:36.353477Z","shell.execute_reply":"2025-12-05T19:33:36.356504Z"}},"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-05T19:33:36.360479Z","iopub.execute_input":"2025-12-05T19:33:36.360689Z","iopub.status.idle":"2025-12-05T19:33:36.509508Z","shell.execute_reply.started":"2025-12-05T19:33:36.360674Z","shell.execute_reply":"2025-12-05T19:33:36.508954Z"}},"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-05T19:33:36.510034Z","iopub.execute_input":"2025-12-05T19:33:36.510226Z","iopub.status.idle":"2025-12-05T19:33:36.551846Z","shell.execute_reply.started":"2025-12-05T19:33:36.510211Z","shell.execute_reply":"2025-12-05T19:33:36.551312Z"}},"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-05T19:33:36.552471Z","iopub.execute_input":"2025-12-05T19:33:36.552707Z","iopub.status.idle":"2025-12-05T19:33:37.421287Z","shell.execute_reply.started":"2025-12-05T19:33:36.552681Z","shell.execute_reply":"2025-12-05T19:33:37.420263Z"}},"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-05T19:33:37.422166Z","iopub.execute_input":"2025-12-05T19:33:37.422437Z","iopub.status.idle":"2025-12-05T20:09:09.928372Z","shell.execute_reply.started":"2025-12-05T19:33:37.422419Z","shell.execute_reply":"2025-12-05T20:09:09.927546Z"}},"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-05T20:09:09.929473Z","iopub.execute_input":"2025-12-05T20:09:09.929729Z","iopub.status.idle":"2025-12-05T20:09:10.020412Z","shell.execute_reply.started":"2025-12-05T20:09:09.929705Z","shell.execute_reply":"2025-12-05T20:09:10.019844Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Virtualize Training","metadata":{"_uuid":"1b76c0a9040bc0babf0a453e567e41e22f8a1e0e"}},{"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-05T20:09:10.61018Z","iopub.execute_input":"2025-12-05T20:09:10.610441Z","iopub.status.idle":"2025-12-05T20:09:10.622417Z","shell.execute_reply.started":"2025-12-05T20:09:10.610416Z","shell.execute_reply":"2025-12-05T20:09:10.621861Z"}},"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-05T20:09:10.623184Z","iopub.execute_input":"2025-12-05T20:09:10.623418Z","iopub.status.idle":"2025-12-05T20:09:10.711123Z","shell.execute_reply.started":"2025-12-05T20:09:10.623394Z","shell.execute_reply":"2025-12-05T20:09:10.710569Z"}},"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-05T20:09:10.711669Z","iopub.execute_input":"2025-12-05T20:09:10.711842Z","iopub.status.idle":"2025-12-05T20:09:26.642178Z","shell.execute_reply.started":"2025-12-05T20:09:10.711828Z","shell.execute_reply":"2025-12-05T20:09:26.641579Z"}},"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-05T20:09:26.64308Z","iopub.execute_input":"2025-12-05T20:09:26.643344Z","iopub.status.idle":"2025-12-05T20:09:26.648552Z","shell.execute_reply.started":"2025-12-05T20:09:26.643317Z","shell.execute_reply":"2025-12-05T20:09:26.647856Z"}},"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-05T20:09:26.649372Z","iopub.execute_input":"2025-12-05T20:09:26.649711Z","iopub.status.idle":"2025-12-05T20:09:26.659646Z","shell.execute_reply.started":"2025-12-05T20:09:26.649687Z","shell.execute_reply":"2025-12-05T20:09:26.658863Z"}},"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-05T20:09:26.660277Z","iopub.execute_input":"2025-12-05T20:09:26.661162Z","iopub.status.idle":"2025-12-05T20:09:26.675022Z","shell.execute_reply.started":"2025-12-05T20:09:26.661137Z","shell.execute_reply":"2025-12-05T20:09:26.674374Z"}},"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-05T20:09:26.675668Z","iopub.execute_input":"2025-12-05T20:09:26.675998Z","iopub.status.idle":"2025-12-05T20:09:26.792967Z","shell.execute_reply.started":"2025-12-05T20:09:26.675974Z","shell.execute_reply":"2025-12-05T20:09:26.792143Z"}},"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-05T20:09:26.793734Z","iopub.execute_input":"2025-12-05T20:09:26.793999Z","iopub.status.idle":"2025-12-05T20:09:27.43626Z","shell.execute_reply.started":"2025-12-05T20:09:26.793977Z","shell.execute_reply":"2025-12-05T20:09:27.435305Z"}},"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-05T20:09:27.437431Z","iopub.execute_input":"2025-12-05T20:09:27.437806Z","iopub.status.idle":"2025-12-05T20:09:27.47545Z","shell.execute_reply.started":"2025-12-05T20:09:27.437781Z","shell.execute_reply":"2025-12-05T20:09:27.474756Z"}},"outputs":[],"execution_count":null}]}