{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30804,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input,Conv2D,MaxPooling2D,Dense,Flatten,Dropout,BatchNormalization","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T10:10:39.474720Z","iopub.execute_input":"2024-12-13T10:10:39.475678Z","iopub.status.idle":"2024-12-13T10:10:39.480407Z","shell.execute_reply.started":"2024-12-13T10:10:39.475637Z","shell.execute_reply":"2024-12-13T10:10:39.479211Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator,load_img\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport os\nimport random\nimport itertools\nimport shutil\nimport glob","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T10:10:40.074459Z","iopub.execute_input":"2024-12-13T10:10:40.074760Z","iopub.status.idle":"2024-12-13T10:10:40.079760Z","shell.execute_reply.started":"2024-12-13T10:10:40.074733Z","shell.execute_reply":"2024-12-13T10:10:40.078718Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"os.listdir(\"/kaggle/input/dogs-vs-cats\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T10:10:41.320293Z","iopub.execute_input":"2024-12-13T10:10:41.321147Z","iopub.status.idle":"2024-12-13T10:10:41.328144Z","shell.execute_reply.started":"2024-12-13T10:10:41.321100Z","shell.execute_reply":"2024-12-13T10:10:41.327181Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#!unzip /kaggle/input/dogs-vs-cats/test1.zip","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T10:10:43.272875Z","iopub.execute_input":"2024-12-13T10:10:43.273231Z","iopub.status.idle":"2024-12-13T10:10:43.277547Z","shell.execute_reply.started":"2024-12-13T10:10:43.273199Z","shell.execute_reply":"2024-12-13T10:10:43.276562Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#!unzip /kaggle/input/dogs-vs-cats/train.zip","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T10:10:43.799504Z","iopub.execute_input":"2024-12-13T10:10:43.799916Z","iopub.status.idle":"2024-12-13T10:10:43.804074Z","shell.execute_reply.started":"2024-12-13T10:10:43.799873Z","shell.execute_reply":"2024-12-13T10:10:43.803132Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Extracting files and Making directories ","metadata":{}},{"cell_type":"code","source":"import os\nimport zipfile\n\n# Specify the directory where the zip files are located\nzip_dir = '/kaggle/input/dogs-vs-cats'\n\n# List of zip files to extract\nzip_files = ['test1.zip', 'train.zip']\n\n# Create a directory for all extracted files (optional, if not already created)\nextracted_dir = '/kaggle/working/dogs-vs-cats-extracted'\nos.makedirs(extracted_dir, exist_ok=True)\n\n# Function to unzip the file into the specified folder\ndef unzip_file(zip_path, extract_to_folder):\n    with zipfile.ZipFile(zip_path, 'r') as zip_ref:\n        zip_ref.extractall(extract_to_folder)\n\n# Loop through the zip files and extract them\nfor zip_file in zip_files:\n    zip_path = os.path.join(zip_dir, zip_file)\n    \n    # Unzip the file into the target folder\n    unzip_file(zip_path, extracted_dir)\n\n# Verify the extraction by listing the contents of the extracted directory\nextracted_files = os.listdir(extracted_dir)\nprint(extracted_files)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T10:10:44.810041Z","iopub.execute_input":"2024-12-13T10:10:44.810757Z","iopub.status.idle":"2024-12-13T10:10:55.403046Z","shell.execute_reply.started":"2024-12-13T10:10:44.810719Z","shell.execute_reply":"2024-12-13T10:10:55.402038Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"split the labeled training data into two subfolders: one for training and one for validation","metadata":{}},{"cell_type":"code","source":"import os\nimport shutil\nimport random\n\n# Paths to your datasets\ntrain_dir = '/kaggle/working/dogs-vs-cats-extracted/train'  # The directory where the original data is\ntrain_split_dir = '/kaggle/working/split_train_data'  # Directory where you want to store the split data\n\n# Change working directory to where the original train data exists\nos.chdir(train_dir)\n\n# Check and create directories if they don't exist\nif not os.path.isdir(os.path.join(train_split_dir, 'train/dog')):\n    os.makedirs(os.path.join(train_split_dir, 'train/dog'))\n    os.makedirs(os.path.join(train_split_dir, 'train/cat'))\n    os.makedirs(os.path.join(train_split_dir, 'valid/dog'))\n    os.makedirs(os.path.join(train_split_dir, 'valid/cat'))\n\n\nos.chdir('../../')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T10:11:05.272820Z","iopub.execute_input":"2024-12-13T10:11:05.273225Z","iopub.status.idle":"2024-12-13T10:11:05.279247Z","shell.execute_reply.started":"2024-12-13T10:11:05.273185Z","shell.execute_reply":"2024-12-13T10:11:05.278272Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### splitting images into train and validation directories based on file name","metadata":{}},{"cell_type":"code","source":"# Get the list of all images in the original train directory\nimage_files = os.listdir(train_dir)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T10:11:08.972689Z","iopub.execute_input":"2024-12-13T10:11:08.973551Z","iopub.status.idle":"2024-12-13T10:11:08.991928Z","shell.execute_reply.started":"2024-12-13T10:11:08.973498Z","shell.execute_reply":"2024-12-13T10:11:08.991105Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Separate the images into dogs and cats\ndog_images = [f for f in image_files if 'dog' in f]  # Assuming filenames contain 'dog'\ncat_images = [f for f in image_files if 'cat' in f]  # Assuming filenames contain 'cat'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T10:11:09.579971Z","iopub.execute_input":"2024-12-13T10:11:09.580847Z","iopub.status.idle":"2024-12-13T10:11:09.589723Z","shell.execute_reply.started":"2024-12-13T10:11:09.580814Z","shell.execute_reply":"2024-12-13T10:11:09.588751Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Split images into train and validation sets (80% for train, 20% for validation)\ndef split_data(images):\n    random.shuffle(images)\n    split_index = int(0.8 * len(images))  # 80% for train, 20% for valid\n    train_images = images[:split_index]\n    valid_images = images[split_index:]\n    return train_images, valid_images","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T10:11:10.400458Z","iopub.execute_input":"2024-12-13T10:11:10.400833Z","iopub.status.idle":"2024-12-13T10:11:10.406261Z","shell.execute_reply.started":"2024-12-13T10:11:10.400804Z","shell.execute_reply":"2024-12-13T10:11:10.405251Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Split the dog and cat images\ntrain_dogs, valid_dogs = split_data(dog_images)\ntrain_cats, valid_cats = split_data(cat_images)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T10:11:10.973174Z","iopub.execute_input":"2024-12-13T10:11:10.973549Z","iopub.status.idle":"2024-12-13T10:11:10.993261Z","shell.execute_reply.started":"2024-12-13T10:11:10.973514Z","shell.execute_reply":"2024-12-13T10:11:10.992271Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Function to transfer images to the appropriate directory\ndef transfer_images(images, source_dir, target_dir):\n    for image in images:\n        source_path = os.path.join(source_dir, image)\n        target_path = os.path.join(target_dir, image)\n        shutil.copy(source_path, target_path)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T10:11:11.472733Z","iopub.execute_input":"2024-12-13T10:11:11.473120Z","iopub.status.idle":"2024-12-13T10:11:11.479113Z","shell.execute_reply.started":"2024-12-13T10:11:11.473089Z","shell.execute_reply":"2024-12-13T10:11:11.478038Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Transfer dog images to respective train and valid directories\ntransfer_images(train_dogs, train_dir, os.path.join(train_split_dir, 'train/dog'))\ntransfer_images(valid_dogs, train_dir, os.path.join(train_split_dir, 'valid/dog'))\n\n# Transfer cat images to respective train and valid directories\ntransfer_images(train_cats, train_dir, os.path.join(train_split_dir, 'train/cat'))\ntransfer_images(valid_cats, train_dir, os.path.join(train_split_dir, 'valid/cat'))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T10:11:12.174369Z","iopub.execute_input":"2024-12-13T10:11:12.174768Z","iopub.status.idle":"2024-12-13T10:11:15.982476Z","shell.execute_reply.started":"2024-12-13T10:11:12.174734Z","shell.execute_reply":"2024-12-13T10:11:15.981584Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(f\"Transferred {len(train_dogs)} dog images to train, {len(valid_dogs)} dog images to valid.\")\nprint(f\"Transferred {len(train_cats)} cat images to train, {len(valid_cats)} cat images to valid.\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T10:11:15.984220Z","iopub.execute_input":"2024-12-13T10:11:15.984742Z","iopub.status.idle":"2024-12-13T10:11:15.990853Z","shell.execute_reply.started":"2024-12-13T10:11:15.984700Z","shell.execute_reply":"2024-12-13T10:11:15.989824Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Building an architecture / Model","metadata":{}},{"cell_type":"code","source":"input = Input(shape=(128,128,3))\n\nconv1 = Conv2D(32,(5,5),activation='relu', padding='same',name='conv1')(input)\npool1 = MaxPooling2D((2,2), name='pool1')(conv1)\n\nconv2 = Conv2D(64,(5,5),activation='relu', padding='same', name='conv2')(pool1)\npool2 = MaxPooling2D((2,2), name='pool2')(conv2)\n\nconv3 =Conv2D(128,(5,5), activation='relu', padding='same', name='conv3')(pool2)\npool3 =MaxPooling2D((2,2), name='pool3')(conv3)\n\nflatten = Flatten(name='flatten')(pool3)\n\ndense1 = Dense(512, activation='relu', name='dense1')(flatten)\nbn1 =BatchNormalization(name='bn1')(dense1)\ndrop1 =Dropout(0.25, name='drop1')(bn1)\n\ndense2 = Dense(64, activation='relu', name='dense2')(drop1)\nbn2 =BatchNormalization(name='bn2')(dense2)\ndrop2 = Dropout(0.25, name='drop2')(bn2)\n\noutput = Dense(2,activation='softmax', name='output')(drop2)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T10:11:18.373347Z","iopub.execute_input":"2024-12-13T10:11:18.373995Z","iopub.status.idle":"2024-12-13T10:11:18.433048Z","shell.execute_reply.started":"2024-12-13T10:11:18.373959Z","shell.execute_reply":"2024-12-13T10:11:18.432122Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = Model(inputs=input, outputs=output)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T10:11:20.173092Z","iopub.execute_input":"2024-12-13T10:11:20.173730Z","iopub.status.idle":"2024-12-13T10:11:20.182285Z","shell.execute_reply.started":"2024-12-13T10:11:20.173692Z","shell.execute_reply":"2024-12-13T10:11:20.181309Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.utils import plot_model\n\nplot_model(model, show_shapes=True, show_layer_names=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T10:11:20.710760Z","iopub.execute_input":"2024-12-13T10:11:20.711125Z","iopub.status.idle":"2024-12-13T10:11:21.394797Z","shell.execute_reply.started":"2024-12-13T10:11:20.711091Z","shell.execute_reply":"2024-12-13T10:11:21.393842Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T10:11:21.679564Z","iopub.execute_input":"2024-12-13T10:11:21.680531Z","iopub.status.idle":"2024-12-13T10:11:21.706116Z","shell.execute_reply.started":"2024-12-13T10:11:21.680471Z","shell.execute_reply":"2024-12-13T10:11:21.705114Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['acc'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T10:11:22.572744Z","iopub.execute_input":"2024-12-13T10:11:22.573095Z","iopub.status.idle":"2024-12-13T10:11:22.582344Z","shell.execute_reply.started":"2024-12-13T10:11:22.573066Z","shell.execute_reply":"2024-12-13T10:11:22.581208Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# keras callback utilities","metadata":{}},{"cell_type":"code","source":"from keras.callbacks import EarlyStopping, ReduceLROnPlateau","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T10:11:24.473926Z","iopub.execute_input":"2024-12-13T10:11:24.474843Z","iopub.status.idle":"2024-12-13T10:11:24.478988Z","shell.execute_reply.started":"2024-12-13T10:11:24.474804Z","shell.execute_reply":"2024-12-13T10:11:24.478027Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nearly_stopping = EarlyStopping(monitor='val_loss',  # Metric to monitor\n                                patience=5,  # Number of epochs with no improvement after which training will stop\n                                restore_best_weights=True,  # Restores the model weights from the epoch with the best performance\n                                verbose=1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T10:11:25.772835Z","iopub.execute_input":"2024-12-13T10:11:25.773213Z","iopub.status.idle":"2024-12-13T10:11:25.778532Z","shell.execute_reply.started":"2024-12-13T10:11:25.773182Z","shell.execute_reply":"2024-12-13T10:11:25.777632Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', \n                                            patience=3, \n                                            verbose=1, \n                                            factor=0.5, \n                                            min_lr=0.00001)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T10:11:26.299666Z","iopub.execute_input":"2024-12-13T10:11:26.300017Z","iopub.status.idle":"2024-12-13T10:11:26.304382Z","shell.execute_reply.started":"2024-12-13T10:11:26.299986Z","shell.execute_reply":"2024-12-13T10:11:26.303496Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Traning Generator","metadata":{}},{"cell_type":"code","source":"train_dir = '/kaggle/working/split_train_data/train'\nval_dir ='/kaggle/working/split_train_data/valid'\ntest_dir ='/kaggle/working/dogs-vs-cats-extracted/test1'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T10:12:05.100873Z","iopub.execute_input":"2024-12-13T10:12:05.101748Z","iopub.status.idle":"2024-12-13T10:12:05.106058Z","shell.execute_reply.started":"2024-12-13T10:12:05.101713Z","shell.execute_reply":"2024-12-13T10:12:05.104945Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_data_gen = ImageDataGenerator(rescale=1./255,\n                      width_shift_range=0.2,  \n    height_shift_range=0.2, shear_range=0.2 )\n\nval_data_gen =ImageDataGenerator(rescale=1./255,\n    width_shift_range=0.2,  \n    height_shift_range=0.2, shear_range=0.2)\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T10:12:06.529968Z","iopub.execute_input":"2024-12-13T10:12:06.531061Z","iopub.status.idle":"2024-12-13T10:12:06.535797Z","shell.execute_reply.started":"2024-12-13T10:12:06.531020Z","shell.execute_reply":"2024-12-13T10:12:06.534674Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_generator =train_data_gen.flow_from_directory(\n    train_dir, target_size=(128,128),\n    batch_size=500, class_mode='categorical'\n)\n\nval_generator = val_data_gen.flow_from_directory(\n    val_dir, target_size=(128,128),\n    batch_size=500, class_mode='categorical'\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T10:12:07.330394Z","iopub.execute_input":"2024-12-13T10:12:07.331404Z","iopub.status.idle":"2024-12-13T10:12:07.872554Z","shell.execute_reply.started":"2024-12-13T10:12:07.331365Z","shell.execute_reply":"2024-12-13T10:12:07.871868Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history = model.fit(\n    train_generator, \n    epochs=20,\n    validation_data=val_generator,\n    validation_steps=200,\n    steps_per_epoch=50, verbose=2,\n    callbacks=[early_stopping,learning_rate_reduction]\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T10:12:08.100753Z","iopub.execute_input":"2024-12-13T10:12:08.101585Z","iopub.status.idle":"2024-12-13T11:10:47.985131Z","shell.execute_reply.started":"2024-12-13T10:12:08.101549Z","shell.execute_reply":"2024-12-13T11:10:47.984375Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Assuming 'history' contains the training logs\n# Plot training & validation accuracy values\nplt.figure(figsize=(12, 6))\n\n# Accuracy plot\nplt.subplot(1, 2, 1)\nplt.plot(history.history['acc'], label='Training Accuracy')\nplt.plot(history.history['val_acc'], label='Validation Accuracy')\nplt.title('Training and Validation Accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend()\n\n# Loss plot\nplt.subplot(1, 2, 2)\nplt.plot(history.history['loss'], label='Training Loss')\nplt.plot(history.history['val_loss'], label='Validation Loss')\nplt.title('Training and Validation Loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\n\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T11:10:47.986888Z","iopub.execute_input":"2024-12-13T11:10:47.987177Z","iopub.status.idle":"2024-12-13T11:10:48.640608Z","shell.execute_reply.started":"2024-12-13T11:10:47.987149Z","shell.execute_reply":"2024-12-13T11:10:48.639625Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Save the trained model as an .h5 file","metadata":{}},{"cell_type":"code","source":"model.save(\"model.h5\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T11:10:48.641948Z","iopub.execute_input":"2024-12-13T11:10:48.642671Z","iopub.status.idle":"2024-12-13T11:10:49.186374Z","shell.execute_reply.started":"2024-12-13T11:10:48.642626Z","shell.execute_reply":"2024-12-13T11:10:49.185293Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Visualizing images from test data","metadata":{}},{"cell_type":"code","source":"import os\nimport random\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.preprocessing import image\n\n# Directory containing test images\ntest_dir = '/kaggle/working/dogs-vs-cats-extracted_files/test1'\n\n# List all image files in the directory (filter by common image extensions)\nimage_files = [os.path.join(test_dir, fname) for fname in os.listdir(test_dir) if fname.endswith(('.jpg', '.png', '.jpeg'))]\n\n# Randomly select 6 images from the list\nrandom_images = random.sample(image_files, 6)\n\n# Create a figure to plot images\nplt.figure(figsize=(12, 8))\n\n# Loop through the selected random images and plot them\nfor i, img_path in enumerate(random_images):\n    # Load the image\n    img = image.load_img(img_path, target_size=(224, 224))  # Resize to desired size (224x224 is an example)\n    \n    # Plot the image\n    plt.subplot(2, 3, i + 1)  # Create a 2x3 grid of subplots\n    plt.imshow(img)\n    plt.axis('off')  # Hide axes for better visualization\n    plt.title(f\"Image {i + 1}\")  # Optional: Title for each image\n\n# Show the plot\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T11:10:49.188913Z","iopub.execute_input":"2024-12-13T11:10:49.189348Z","iopub.status.idle":"2024-12-13T11:10:50.304986Z","shell.execute_reply.started":"2024-12-13T11:10:49.189303Z","shell.execute_reply":"2024-12-13T11:10:50.304035Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Preparing data for test","metadata":{}},{"cell_type":"code","source":"\n# Create an ImageDataGenerator without class_mode as we don't need labels\ntest_data_gen = ImageDataGenerator(rescale=1./255)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T11:10:50.306298Z","iopub.execute_input":"2024-12-13T11:10:50.306651Z","iopub.status.idle":"2024-12-13T11:10:50.311338Z","shell.execute_reply.started":"2024-12-13T11:10:50.306616Z","shell.execute_reply":"2024-12-13T11:10:50.310353Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nimport pandas as pd\nfrom tensorflow.keras.preprocessing.image import  load_img, img_to_array\nfrom tensorflow.keras.models import load_model\n\n# load the model\nmodel = load_model('model.h5')\n\n# Directory containing test images\ntest_dir = '/kaggle/working/dogs-vs-cats-extracted_files/test1'\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T11:10:50.312629Z","iopub.execute_input":"2024-12-13T11:10:50.312912Z","iopub.status.idle":"2024-12-13T11:10:50.480410Z","shell.execute_reply.started":"2024-12-13T11:10:50.312885Z","shell.execute_reply":"2024-12-13T11:10:50.479523Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Function to load and preprocess images\ndef load_images(test_dir, target_size=(128, 128)):\n    images = []\n    filenames = []\n    for filename in os.listdir(test_dir):\n        # Only process image files (filtering out non-images if needed)\n        if filename.endswith(('.jpg', '.png', '.jpeg')):\n            img_path = os.path.join(test_dir, filename)\n            img = load_img(img_path, target_size=target_size)  # Load image\n            img_array = img_to_array(img) / 255.0  # Convert to array and normalize\n            images.append(img_array)\n            filenames.append(filename.split('.')[0])  # Use the filename (without extension) as the ID\n    return np.array(images), filenames","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T11:10:50.481686Z","iopub.execute_input":"2024-12-13T11:10:50.482050Z","iopub.status.idle":"2024-12-13T11:10:50.488397Z","shell.execute_reply.started":"2024-12-13T11:10:50.482007Z","shell.execute_reply":"2024-12-13T11:10:50.487330Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load and preprocess test images\ntest_images, test_filenames = load_images(test_dir)\n\n# Predict the class labels\npredictions = model.predict(test_images)\n\n# Convert predictions to class labels by selecting the class with the highest probability\npredicted_labels = np.argmax(predictions, axis=-1)  # Use argmax to get the class index with highest probability","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T11:10:50.489654Z","iopub.execute_input":"2024-12-13T11:10:50.489997Z","iopub.status.idle":"2024-12-13T11:11:16.566344Z","shell.execute_reply.started":"2024-12-13T11:10:50.489968Z","shell.execute_reply":"2024-12-13T11:11:16.565421Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Prepare the submission format\nsubmission_df = pd.DataFrame({\n    'id': test_filenames,\n    'label': predicted_labels.flatten()  # Flatten the array to match shape\n})\n\nsubmission_df.head(10)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T11:11:16.567556Z","iopub.execute_input":"2024-12-13T11:11:16.567853Z","iopub.status.idle":"2024-12-13T11:11:16.580152Z","shell.execute_reply.started":"2024-12-13T11:11:16.567824Z","shell.execute_reply":"2024-12-13T11:11:16.579046Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission_df.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T11:11:16.583300Z","iopub.execute_input":"2024-12-13T11:11:16.583676Z","iopub.status.idle":"2024-12-13T11:11:16.595905Z","shell.execute_reply.started":"2024-12-13T11:11:16.583646Z","shell.execute_reply":"2024-12-13T11:11:16.594871Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Save to CSV\nsubmission_df.to_csv('submission.csv', index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-13T11:11:16.597302Z","iopub.execute_input":"2024-12-13T11:11:16.597693Z","iopub.status.idle":"2024-12-13T11:11:16.615024Z","shell.execute_reply.started":"2024-12-13T11:11:16.597663Z","shell.execute_reply":"2024-12-13T11:11:16.614012Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}