{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.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":30646,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# **Pawsome Pet Classifier: VGG16 Edition**\n> *This notebook utilizes transfer learning with the VGG16 model to classify images of cats and dogs. It demonstrates how to preprocess the data, fine-tune the model, and evaluate its performance. By leveraging a pre-trained model, it achieves accurate classification results while providing insights into deep learning techniques for image classification tasks.*","metadata":{}},{"cell_type":"markdown","source":"# Image Classification Preparation and Model Setup\n\nThis code block is designed for preparing an image classification task using deep learning. It includes importing necessary libraries and setting up a convolutional neural network (CNN) model for image classification. Here's a breakdown of what each part does:\n\n- **Library Imports**: Essential libraries such as `numpy`, `pandas`, `matplotlib`, `tensorflow`, and `keras` are imported for data manipulation, visualization, and deep learning model construction.\n- **Model Architecture Setup**: Using `VGG16` as a base model, this section demonstrates how to customize a CNN by adding additional layers like `Dense`, `Flatten`, and `Dropout` to tailor the network for a specific image classification task.\n- **Data Preparation**: Utilities to load datasets, split data into training and testing sets, and augment images for better model generalization are prepared.\n- **Miscellaneous**: Setting up to ignore warnings to keep the output clean.\n\nThis setup is crucial for anyone looking to dive into image classification with deep learning, providing a solid foundation for model training and evaluation.","metadata":{}},{"cell_type":"code","source":"# Core libraries for data processing and mathematical operations\nimport zipfile\nimport numpy as np\nimport pandas as pd\n\n# Visualization library\nimport matplotlib.pyplot as plt\n\n# Deep learning libraries\nimport tensorflow as tf\nfrom keras.applications import VGG16  # Pre-trained model for image classification\nfrom keras.models import Model\nfrom keras.layers import Dense, Flatten, Dropout  # Layers for model customization\nfrom tensorflow.keras.optimizers import Adam\n\n# Dataset handling\nfrom datasets import load_dataset\nfrom sklearn.model_selection import train_test_split\n\n# Image processing\nimport matplotlib.image as mpimg\n\n# Standard libraries for file and random operations\nimport os\nimport random\n\n# Data augmentation library for image data\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# Suppress warnings for a cleaner output\nimport warnings\nwarnings.filterwarnings('ignore')","metadata":{"execution":{"iopub.status.busy":"2024-02-17T10:18:27.836769Z","iopub.execute_input":"2024-02-17T10:18:27.837153Z","iopub.status.idle":"2024-02-17T10:18:43.207395Z","shell.execute_reply.started":"2024-02-17T10:18:27.837121Z","shell.execute_reply":"2024-02-17T10:18:43.206333Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Extracting Zip Files for Dogs vs. Cats Dataset\n\nThe following code extracts the contents of two zip files, `train.zip` and `test1.zip`, which are assumed to contain the training and testing datasets for a Dogs vs. Cats classification problem. The datasets are extracted into the current working directory (`\".\"`) for further processing.","metadata":{}},{"cell_type":"code","source":"# Import the zipfile module to work with zip files\nimport zipfile\n\n# Define a function to extract a zip file to a specified directory\ndef extract_zip(input_zip, output_dir=\".\"):\n    \"\"\"\n    Extracts a zip file to the specified output directory.\n    \n    Parameters:\n    - input_zip (str): The path to the zip file.\n    - output_dir (str): The directory to extract the files into.\n    \"\"\"\n    with zipfile.ZipFile(input_zip, \"r\") as z:\n        z.extractall(output_dir)\n\n# Paths to the zip files for training and testing datasets\ntrain_zip_path = \"/kaggle/input/dogs-vs-cats/train.zip\"\ntest_zip_path = \"/kaggle/input/dogs-vs-cats/test1.zip\"\n\n# Extract the training and testing datasets\nextract_zip(train_zip_path)\nextract_zip(test_zip_path)\n","metadata":{"execution":{"iopub.status.busy":"2024-02-17T10:18:43.209490Z","iopub.execute_input":"2024-02-17T10:18:43.210565Z","iopub.status.idle":"2024-02-17T10:19:00.028230Z","shell.execute_reply.started":"2024-02-17T10:18:43.210528Z","shell.execute_reply":"2024-02-17T10:19:00.027385Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Creating a DataFrame with Image Labels\n\nThis snippet of code is designed to organize and label images from a training dataset, presumably consisting of images of cats and dogs. It reads the filenames from the \"train\" directory, then iterates through each filename to determine if the image is of a cat or a dog based on the presence of the substring in the filename. It then creates a pandas DataFrame with two columns: one for the filename and another for the corresponding label ('cat' or 'dog'). Finally, it displays the first few rows of the DataFrame to verify its structure.","metadata":{}},{"cell_type":"code","source":"# Import necessary libraries\nimport os\nimport pandas as pd\n\n# Get a list of filenames in the \"train\" directory\nfilenames = os.listdir(\"train\")\n\n# Initialize an empty list to store labels\nlabels = []\n\n# Loop through each filename to determine its label based on its name\nfor filename in filenames:\n    if \"cat\" in filename:\n        labels.append('cat')  # Append 'cat' if the filename contains \"cat\"\n    elif \"dog\" in filename:\n        labels.append('dog')  # Append 'dog' if the filename contains \"dog\"\n    \n# Create a DataFrame with filenames and their corresponding labels\ndf = pd.DataFrame({\n    'Filename': filenames,\n    'Label': labels\n})\n\n# Display the first five rows of the DataFrame\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2024-02-17T10:19:00.033513Z","iopub.execute_input":"2024-02-17T10:19:00.033772Z","iopub.status.idle":"2024-02-17T10:19:00.075809Z","shell.execute_reply.started":"2024-02-17T10:19:00.033747Z","shell.execute_reply":"2024-02-17T10:19:00.074958Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.info()","metadata":{"execution":{"iopub.status.busy":"2024-02-17T10:19:00.077081Z","iopub.execute_input":"2024-02-17T10:19:00.077420Z","iopub.status.idle":"2024-02-17T10:19:00.106461Z","shell.execute_reply.started":"2024-02-17T10:19:00.077387Z","shell.execute_reply":"2024-02-17T10:19:00.105419Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Displaying Images of Cats and Dogs\n\nThe `display_images` function is designed to display a specified number of images for a given category (either cats or dogs) from the \"train\" directory. It uses matplotlib to plot the images in a row, with each image's title indicating its category.\n\nAfter defining this function, the code selects three random images of cats and three random images of dogs from the filenames list. It then calls `display_images` for each category, displaying the selected images. This visualization is helpful for verifying the data and the labels visually, ensuring that the dataset is correctly labeled and ready for further processing in machine learning models.","metadata":{}},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport os\nimport random\nimport matplotlib.image as mpimg\n\n# Function to display a specified number of images for a given category (cats or dogs)\ndef display_images(image_paths, category):\n    plt.figure(figsize=(24, 4))  # Set figure size for the display\n    for i, img_path in enumerate(image_paths):\n        plt.subplot(1, 3, i + 1)  # Arrange images in a single row\n        img = mpimg.imread(os.path.join('train', img_path))  # Read the image file\n        plt.imshow(img)  # Display the image\n        plt.title(category)  # Set the title to the category (cat or dog)\n        plt.axis('off')  # Hide the axis for a cleaner look\n    plt.show()  # Display the plot\n\n# List all cat and dog filenames in the \"train\" directory\ncat_images = [filename for filename in filenames if 'cat' in filename]\ndog_images = [filename for filename in filenames if 'dog' in filename]\n\n# Randomly select three images from each category\nselected_cat_images = random.sample(cat_images, 3)\nselected_dog_images = random.sample(dog_images, 3)\n\n# Display the selected images for each category\ndisplay_images(selected_cat_images, 'Cat')\ndisplay_images(selected_dog_images, 'Dog')","metadata":{"execution":{"iopub.status.busy":"2024-02-17T10:19:00.107613Z","iopub.execute_input":"2024-02-17T10:19:00.108227Z","iopub.status.idle":"2024-02-17T10:19:01.081402Z","shell.execute_reply.started":"2024-02-17T10:19:00.108189Z","shell.execute_reply":"2024-02-17T10:19:01.080541Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Image Data Generation for Training and Validation\n\nThis code segment prepares image data generators for training and validation using the `ImageDataGenerator` class from Keras. It rescales the pixel values of the images and splits the dataset into training and validation subsets.","metadata":{}},{"cell_type":"code","source":"# Define image dimensions and batch size\nIMAGE_WIDTH, IMAGE_HEIGHT = 224, 224\nBATCH_SIZE = 32\n\n# Create an image data generator with rescaling and validation split\ndatagen = ImageDataGenerator(rescale=1./255, validation_split=0.2)\n\n# Generate training data from DataFrame with specified parameters\ntrain_generator = datagen.flow_from_dataframe(\n    dataframe=df,\n    directory='train/',\n    x_col='Filename',\n    y_col='Label',\n    target_size=(IMAGE_WIDTH, IMAGE_HEIGHT),\n    batch_size=BATCH_SIZE,\n    class_mode='binary',\n    subset='training'\n)\n\n# Generate validation data from DataFrame with specified parameters\nvalidation_generator = datagen.flow_from_dataframe(\n    dataframe=df,\n    directory='train/',\n    x_col='Filename',\n    y_col='Label',\n    target_size=(IMAGE_WIDTH, IMAGE_HEIGHT),\n    batch_size=BATCH_SIZE,\n    class_mode='binary',\n    subset='validation'\n)","metadata":{"execution":{"iopub.status.busy":"2024-02-17T10:19:01.082494Z","iopub.execute_input":"2024-02-17T10:19:01.082768Z","iopub.status.idle":"2024-02-17T10:19:01.600944Z","shell.execute_reply.started":"2024-02-17T10:19:01.082744Z","shell.execute_reply":"2024-02-17T10:19:01.600012Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Loading and Freezing Pretrained VGG16 Model\n\nThis code segment loads the VGG16 model pretrained on ImageNet and freezes its layers to prevent them from being updated during training.\n\n- The `VGG16` model is loaded with pretrained weights from ImageNet using the `weights='imagenet'` parameter.\n- The `include_top=False` parameter excludes the fully connected layers from the model.\n- The `input_shape` parameter specifies the input image dimensions.\n- All layers of the base model are iterated through, and their `trainable` attribute is set to `False` to freeze them.\n","metadata":{}},{"cell_type":"code","source":"# Load the VGG16 model, pretrained on ImageNet\nbase_model = VGG16(weights='imagenet', include_top=False, input_shape=(IMAGE_WIDTH, IMAGE_HEIGHT, 3))\n\n# Freeze the layers of the base model\nfor layer in base_model.layers:\n    layer.trainable = False","metadata":{"execution":{"iopub.status.busy":"2024-02-17T10:19:01.601996Z","iopub.execute_input":"2024-02-17T10:19:01.602271Z","iopub.status.idle":"2024-02-17T10:19:03.040903Z","shell.execute_reply.started":"2024-02-17T10:19:01.602247Z","shell.execute_reply":"2024-02-17T10:19:03.039799Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Creating Custom Model on Top of Pretrained VGG16\n\nThis code segment creates a custom model by adding layers on top of the pretrained VGG16 model.\n\n- The output of the VGG16 base model is flattened using `Flatten()` layer.\n- A fully connected layer with 512 units and ReLU activation is added using `Dense` layer.\n- Dropout regularization with a rate of 0.5 is applied to prevent overfitting.\n- The final output layer with a single unit and sigmoid activation is added to perform binary classification.","metadata":{}},{"cell_type":"code","source":"# Create a custom model on top of the pretrained VGG16 model\nx = Flatten()(base_model.output)  # Flatten the output of the base model\nx = Dense(512, activation='relu')(x)  # Add a fully connected layer with 512 units and ReLU activation\nx = Dropout(0.5)(x)  # Apply dropout regularization to prevent overfitting\npredictions = Dense(1, activation='sigmoid')(x)  # Add a final output layer with sigmoid activation for binary classification\nmodel = Model(inputs=base_model.input, outputs=predictions)  # Define the input and output of the custom model","metadata":{"execution":{"iopub.status.busy":"2024-02-17T10:19:03.042170Z","iopub.execute_input":"2024-02-17T10:19:03.042442Z","iopub.status.idle":"2024-02-17T10:19:03.089757Z","shell.execute_reply.started":"2024-02-17T10:19:03.042418Z","shell.execute_reply":"2024-02-17T10:19:03.088923Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model Compilation\n\nThe provided code segment compiles the Keras model with the following configurations:\n\n- **Optimizer:** Adam optimizer with a learning rate of 0.0001 is used for optimization.\n- **Loss Function:** Binary crossentropy is employed as the loss function, suitable for binary classification tasks.\n- **Metrics:** The model's performance is evaluated based on the accuracy metric.\n\nThis compilation step finalizes the model setup, specifying how it should be trained and evaluated during the training process.","metadata":{}},{"cell_type":"code","source":"# Compile the model with Adam optimizer, binary crossentropy loss, and accuracy metric\nmodel.compile(optimizer=Adam(learning_rate=0.0001), loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-02-17T10:19:03.093072Z","iopub.execute_input":"2024-02-17T10:19:03.093348Z","iopub.status.idle":"2024-02-17T10:19:03.110572Z","shell.execute_reply.started":"2024-02-17T10:19:03.093324Z","shell.execute_reply":"2024-02-17T10:19:03.109657Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-17T10:19:03.111512Z","iopub.execute_input":"2024-02-17T10:19:03.111767Z","iopub.status.idle":"2024-02-17T10:19:03.166790Z","shell.execute_reply.started":"2024-02-17T10:19:03.111744Z","shell.execute_reply":"2024-02-17T10:19:03.161982Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model Training\n\nThe provided code segment initiates the training of the Keras model with the following configurations:\n\n- **Training Data:** The `train_generator` is used to provide training data batches.\n- **Validation Data:** The `validation_generator` is used to provide validation data batches.\n- **Steps per Epoch:** The number of steps per epoch is determined by `train_generator.samples // BATCH_SIZE`, ensuring that each sample in the training dataset is seen once per epoch.\n- **Validation Steps:** Similarly, the number of validation steps per epoch is determined by `validation_generator.samples // BATCH_SIZE`.\n- **Epochs:** The model is trained for 10 epochs.\n\nThis training procedure updates the model's weights using the training data, while also monitoring its performance on the validation data to prevent overfitting.","metadata":{}},{"cell_type":"code","source":"# Train the model with optimized configurations\nhistory = model.fit(\n    train_generator,\n    steps_per_epoch=len(train_generator),\n    validation_data=validation_generator,\n    validation_steps=len(validation_generator),\n    epochs=10\n)","metadata":{"execution":{"iopub.status.busy":"2024-02-17T10:19:03.167816Z","iopub.execute_input":"2024-02-17T10:19:03.168097Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model Evaluation\n\nThe provided code segment plots the training and validation accuracy of the model over epochs. The following details are illustrated:\n\n- **X-axis:** Represents the number of epochs during model training.\n- **Y-axis:** Indicates the corresponding accuracy values achieved by the model.\n- **Training Accuracy:** The accuracy of the model on the training dataset.\n- **Validation Accuracy:** The accuracy of the model on the validation dataset.\n- **Title:** Title of the plot indicating \"Model Accuracy over Epochs\".\n- **Legend:** Indicates the training and validation accuracy lines in the plot.","metadata":{}},{"cell_type":"code","source":"# Visualize model training and validation accuracy\nplt.plot(history.history['accuracy'], label='Training Accuracy')\nplt.plot(history.history['val_accuracy'], label='Validation Accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.ylim([0.8, 1])  # Set y-axis limits for clarity\nplt.legend(loc='lower right')\nplt.title('Model Accuracy over Epochs')\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model Fine-Tuning\n\nThe provided code segment unfreezes the last 10 layers of the base model for fine-tuning. It then compiles the model with the following configurations:\n- **Optimizer:** Adam optimizer with a learning rate of 0.0001.\n- **Loss Function:** Binary crossentropy, suitable for binary classification tasks.\n- **Metrics:** Accuracy metric is used to evaluate the model's performance during training.\n","metadata":{}},{"cell_type":"code","source":"# Unfreeze the last 10 layers of the base model for fine-tuning\nfor layer in base_model.layers[-10:]:\n    layer.trainable = True\n\n# Compile the model with Adam optimizer, binary crossentropy loss, and accuracy metric\nmodel.compile(optimizer=Adam(learning_rate=0.0001), loss='binary_crossentropy', metrics=['accuracy'])\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Continuing Training with Fine-Tuning\n\nThe provided code segment continues training the model with fine-tuning for additional epochs. It utilizes the same data generators used for initial training and evaluates the model's performance on the validation data. Adjust the number of epochs as needed for further training.","metadata":{}},{"cell_type":"code","source":"# Continue training the model with fine-tuning\nhistory_fine = model.fit(\n    train_generator,\n    steps_per_epoch=train_generator.samples // BATCH_SIZE,\n    validation_data=validation_generator,\n    validation_steps=validation_generator.samples // BATCH_SIZE,\n    epochs=10 \n)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Evaluating the Fine-Tuned Model\n\nThis code segment visualizes the accuracy of the fine-tuned model over epochs. It plots both training and validation accuracy to assess the model's performance after fine-tuning. Adjust the y-axis limits as needed for better visualization.","metadata":{}},{"cell_type":"code","source":"# Visualize the accuracy of the fine-tuned model\nplt.plot(history_fine.history['accuracy'], label='accuracy')\nplt.plot(history_fine.history['val_accuracy'], label='val_accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.ylim([0.92, 1])\nplt.legend(loc='lower right')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Loading and Preparing Test Data\n\nThis code segment extracts the test data from the provided ZIP file and creates a DataFrame to store the filenames of the test images. The DataFrame allows easy access to the test data for further processing or evaluation.\n","metadata":{}},{"cell_type":"code","source":"# Extracting the test data from the ZIP file\nwith zipfile.ZipFile('/kaggle/input/dogs-vs-cats/test1.zip', 'r') as test1_zip:\n    test1_zip.extractall('.') \n\n# Define the directory path for the test data\ntest_dir = \"../working/test1/\"\n\n# List the filenames of the test images\nfilenames = os.listdir(test_dir)\n\n# Create a DataFrame to store the filenames of the test images\ntest_data = pd.DataFrame({\"Filename\": filenames})\n\n# Display the first few rows of the test data DataFrame\ntest_data.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Preparing Test Data Generator\n\nThis code segment sets up an ImageDataGenerator to preprocess the test data and creates a generator to yield batches of test images. The generator allows efficient processing of large test datasets in batches, which is essential for evaluation or prediction tasks.","metadata":{}},{"cell_type":"code","source":"# Create an ImageDataGenerator for test data preprocessing\ntest_gen = ImageDataGenerator(rescale=1./255)\n\n# Generate batches of test data from the DataFrame\ntest_generator = test_gen.flow_from_dataframe(\n    dataframe=test_data,\n    directory='test1/',\n    x_col='Filename',\n    y_col=None,\n    target_size=(IMAGE_WIDTH, IMAGE_HEIGHT),\n    batch_size=BATCH_SIZE,\n    class_mode=None,\n)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Performing Predictions on Test Data\n\nThis code snippet utilizes the trained model to perform predictions on the test data generated by the test data generator. The `predict` method of the model is called on the test generator to obtain the predictions for each image in the test dataset. The resulting array contains the predicted probabilities for each image being in the positive class (dog).\n","metadata":{}},{"cell_type":"code","source":"# Perform predictions on the test data using the trained model\ntest1_predict = model.predict(test_generator)\ntest1_predict","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Assigning Labels to Test Data\n\nIn this code snippet, a threshold of 0.5 is set for binary classification. The predicted probabilities obtained earlier are compared to this threshold, and based on the comparison, labels ('dog' or 'cat') are assigned to the test data. If the predicted probability is greater than the threshold, the label is set to 'dog'; otherwise, it is set to 'cat'.","metadata":{}},{"cell_type":"code","source":"# Set the threshold for binary classification\nthreshold = 0.5\n\n# Assign labels to the test data based on the predicted probabilities\ntest_data['Label'] = np.where(test1_predict > threshold, 'dog', 'cat')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Numerical Encoding of Labels\n\nIn this code snippet, the labels in the 'Label' column of the test data DataFrame are replaced with numerical equivalents. 'dog' is replaced with 1, and 'cat' is replaced with 0. This encoding allows for easier analysis and comparison of the labels in numerical form.","metadata":{}},{"cell_type":"code","source":"test_data['Label'] = test_data['Label'].replace({ 'dog': 1, 'cat': 0 })","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_data.tail()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Sample Test Images with Predicted Labels\n\nIn this code snippet, a sample of 6 test images along with their predicted labels are displayed using Matplotlib. The 'sample_test' DataFrame contains randomly selected rows from the test data, and for each row, the corresponding image is loaded and displayed along with its predicted label. The titles of the subplots represent the predicted labels ('dog' or 'cat').","metadata":{}},{"cell_type":"code","source":"# Display a sample of test images with predicted labels\nsample_test = test_data.sample(n=6)\nplt.figure(figsize=(24, 8))\n\nsubplot_index = 1\nfor _, row in sample_test.iterrows():\n    image_path = os.path.join(test_dir, row['Filename'])\n    img = mpimg.imread(image_path)\n    plt.subplot(2, 3, subplot_index)\n    plt.imshow(img)\n    plt.title(row['Label'])\n    plt.axis('off')\n    subplot_index += 1\n\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Submission DataFrame Preparation\n\nIn this code snippet, the 'test_data' DataFrame is copied to 'submission_df' for preparing the submission file. The 'id' column is extracted from the 'Filename' column by removing the file extension, and the 'label' column is renamed from 'Label'. Finally, the 'Filename' column is dropped, and the resulting DataFrame is saved to a CSV file named 'submission.csv'.\n","metadata":{}},{"cell_type":"code","source":"submission_df = test_data.copy()\nsubmission_df['id'] = submission_df['Filename'].str.split('.').str[0]\nsubmission_df['label'] = submission_df['Label']\nsubmission_df.drop(['Filename'], axis=1, inplace=True)\nsubmission_df.to_csv('submission.csv', index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"---\nEnjoyed this notebook? Feel free to give it an **upvote** if you found it helpful or interesting! Your support is greatly appreciated. Happy coding! 😊🚀\n___","metadata":{}}]}