{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","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":30559,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# Unzip Dataset\n!unzip -q /kaggle/input/dogs-vs-cats/test1.zip\n!unzip -q /kaggle/input/dogs-vs-cats/train.zip","metadata":{"execution":{"iopub.status.busy":"2023-11-08T11:21:38.683124Z","iopub.execute_input":"2023-11-08T11:21:38.683994Z","iopub.status.idle":"2023-11-08T11:21:56.581669Z","shell.execute_reply.started":"2023-11-08T11:21:38.683942Z","shell.execute_reply":"2023-11-08T11:21:56.580518Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Requirements\nimport numpy as np\nimport cv2\nimport os\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.applications import InceptionV3\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Dense, GlobalAveragePooling2D\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.utils import to_categorical\nimport matplotlib.pyplot as plt\nimport random\nfrom tensorflow.keras import models, layers, optimizers","metadata":{"execution":{"iopub.status.busy":"2023-11-08T11:22:13.103690Z","iopub.execute_input":"2023-11-08T11:22:13.104062Z","iopub.status.idle":"2023-11-08T11:22:13.110326Z","shell.execute_reply.started":"2023-11-08T11:22:13.104032Z","shell.execute_reply":"2023-11-08T11:22:13.109269Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load and preprocess the image\ndef load_and_preprocess_image(path):\n    image = cv2.imread(path)  # Example: Using OpenCV to load the image\n    image = cv2.resize(image, (150, 150))  # Example: Resize the image to (150, 150)\n    image = image.astype(np.float32)  # Example: Convert the image to float32\n    image /= 255.0  # Example: Normalize the image by dividing by 255.0\n    return image\n\n# Add Rain Effect\ndef add_rain_effect(image, raindrops=random.randint(200, 300), thickness=1, length=20, angle=10):\n    height, width, _ = image.shape\n\n    for _ in range(raindrops):\n        x = np.random.randint(0, width)\n        y = np.random.randint(0, height)\n        l = np.random.randint(1, length)\n        theta = np.random.randint(80, 100)\n\n        dx = int(l * np.cos(np.deg2rad(theta)))\n        dy = int(l * np.sin(np.deg2rad(theta)))\n\n        cv2.line(image, (x, y), (x + dx, y + dy), (200, 200, 200), thickness)\n\n    return image\n\n# Add Snow Effect\ndef add_snow_effect(image, snowflakes=random.randint(100, 150), speed=1):\n    height, width, _ = image.shape\n    random_size = random.randint(1,2)\n    size=(random_size, random_size)\n    \n    snowflakes_coords = np.zeros((snowflakes, 2), dtype=np.int32)\n    snowflakes_coords[:, 0] = np.random.randint(0, width, snowflakes_coords.shape[0])\n    snowflakes_coords[:, 1] = np.random.randint(0, height, snowflakes_coords.shape[0])\n\n    for (x, y) in snowflakes_coords:\n        snow_color = random.randint(200, 255)  # Random color between gray and white\n        cv2.ellipse(image, (x, y), size, 0, 0, 360, (snow_color, snow_color, snow_color), -1)\n        y += speed\n        if y > height:\n            y = 0\n            x = np.random.randint(0, width)\n        cv2.ellipse(image, (x, y), size, 0, 0, 360, (snow_color, snow_color, snow_color), -1)\n\n    return image\n\n\ndef add_blur(image_HLS, x, y, hw):\n    image_copy = np.copy(image_HLS)\n    image_copy[y:y+hw, x:x+hw, 1] = image_copy[y:y+hw, x:x+hw, 1] + 1\n    image_copy[:, :, 1][image_copy[:, :, 1] > 255] = 255\n    image_copy[y:y+hw, x:x+hw, 1] = cv2.blur(image_copy[y:y+hw, x:x+hw, 1], (10, 10))\n    return image_copy\n\n\ndef generate_random_blur_coordinates(imshape, hw):\n    haze_points = []\n    midx = int(imshape[1] / 2)\n    midy = int(imshape[0] / 2)    \n    index = 1\n    while(index < 10):\n        x = np.random.randint(midx - 2 * hw, midx + 2 * hw)\n        y = np.random.randint(midy - 2 * hw, midy + 2 * hw)\n        if x < 0 or y < 0 or x >= imshape[1] - hw or y >= imshape[0] - hw:\n            continue\n        haze_points.append((x, y))\n        index += 1\n    return haze_points\n\n\n# Add Fog Effect\ndef add_fog_effect(image, foginess=0.5):\n    image_HLS = cv2.cvtColor(image, cv2.COLOR_RGB2HLS)\n    \n    # Generate a white image with the same size as the input image\n    fog = np.ones_like(image) * 255\n\n    # Calculate the kernel size based on the foginess level\n    ksize = max(1, int(foginess * 20))\n    if ksize % 2 == 0:\n        ksize += 1\n\n    # Apply Gaussian blur to the fog image based on the kernel size\n    fog = cv2.GaussianBlur(fog, (ksize, ksize), 0)\n\n    # Blend the fog image with the input image using alpha blending\n    alpha = 1 - foginess\n    image_with_fog = cv2.addWeighted(image, alpha, fog, foginess, 0)\n    \n    image_with_fog_HLS = cv2.cvtColor(image_with_fog, cv2.COLOR_RGB2HLS)\n    mask = np.zeros_like(image_with_fog)\n\n    imshape = image_with_fog.shape\n    hw = 100\n\n    image_with_fog_HLS[:, :, 1] = image_with_fog_HLS[:, :, 1] * 0.8\n\n    haze_list = generate_random_blur_coordinates(imshape, hw)\n\n    for haze_points in haze_list:\n        image_with_fog_HLS[:, :, 1][image_with_fog_HLS[:, :, 1] > 255] = 255\n        image_with_fog_HLS = add_blur(image_with_fog_HLS, haze_points[0], haze_points[1], hw)\n\n    image_with_fog_RGB = cv2.cvtColor(image_with_fog_HLS, cv2.COLOR_HLS2RGB)\n    \n    return image_with_fog_RGB","metadata":{"execution":{"iopub.status.busy":"2023-11-08T11:22:16.735263Z","iopub.execute_input":"2023-11-08T11:22:16.735657Z","iopub.status.idle":"2023-11-08T11:22:16.758869Z","shell.execute_reply.started":"2023-11-08T11:22:16.735624Z","shell.execute_reply":"2023-11-08T11:22:16.757782Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import random\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\n# Example data and parameters\ntrain_directory = \"/kaggle/working/train\"  # Directory containing training images\nbatch_size = 32  # Batch size for training\nnum_images = 10000  # Number of original images to use\n\n# Split train images into training and validation sets\npaths = np.array([os.path.join(train_directory, file) for file in os.listdir(train_directory)])\nlabels = np.array([1 if file.split('.')[0] == 'dog' else 0 for file in os.listdir(train_directory)])\n\n# Randomly select num_images\nindices = random.sample(range(len(paths)), num_images)\npaths = paths[indices]\nlabels = labels[indices]\n\ntrain_paths, val_paths, train_labels, val_labels = train_test_split(paths, labels, test_size=0.2, random_state=42)","metadata":{"execution":{"iopub.status.busy":"2023-11-08T11:22:42.383924Z","iopub.execute_input":"2023-11-08T11:22:42.384591Z","iopub.status.idle":"2023-11-08T11:22:42.507710Z","shell.execute_reply.started":"2023-11-08T11:22:42.384556Z","shell.execute_reply":"2023-11-08T11:22:42.506474Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"num_classes = len(set(labels))  # Number of classes\n\n# Load and preprocess the training images\ntrain_images = []\nfor path in train_paths:\n    image = load_and_preprocess_image(path)\n    train_images.append(image)\n\ntrain_images = np.array(train_images)\n\n# Load and preprocess the validation images\nval_images = []\nfor path in val_paths:\n    image = load_and_preprocess_image(path)\n    val_images.append(image)\n\nval_images = np.array(val_images)\n\n# Augment the training images with rain or snow effects\naugmented_images = []\naugmented_labels = []\nfor ind, image in enumerate(train_images):\n    img = image.copy()\n    augmentation_type = np.random.choice(['rain', 'snow'])\n    if augmentation_type == 'rain':\n        augmented_image = add_rain_effect(img)\n    else:\n        augmented_image = add_snow_effect(img)\n\n    augmented_images.append(augmented_image)\n    augmented_labels.append(train_labels[ind])\n\naugmented_images = np.array(augmented_images)\naugmented_labels = np.array(augmented_labels)\n\n# Concatenate the original images with augmented images\nall_train_images = np.concatenate([train_images, augmented_images], axis=0)\nall_train_labels = np.concatenate([train_labels, augmented_labels], axis=0)\n\n# Print the shapes of train_images and train_labels\nprint(all_train_images.shape, all_train_labels.shape)","metadata":{"execution":{"iopub.status.busy":"2023-11-08T11:24:11.266484Z","iopub.execute_input":"2023-11-08T11:24:11.266848Z","iopub.status.idle":"2023-11-08T11:25:17.322228Z","shell.execute_reply.started":"2023-11-08T11:24:11.266821Z","shell.execute_reply":"2023-11-08T11:25:17.321322Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import random\nimport matplotlib.pyplot as plt\n\n# Randomly select 10 indices from the training set\nrandom_indices = random.sample(range(len(all_train_labels)), 10)\n\n# Create subplots to display images\nfig, axs = plt.subplots(2, 5, figsize=(12, 6))\naxs = axs.flatten()\n\n# Iterate over the selected indices\nfor i, index in enumerate(random_indices):\n    # Get the image and label\n    image = all_train_images[index]\n    label = all_train_labels[index]\n\n    # If the image has 2 channels, convert it to RGB\n    if image.shape[-1] == 2:\n        image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)\n\n    # Display the image with its label\n    axs[i].imshow(image)\n    if label:\n        name='dog'\n    else:\n        name=\"cat\"\n    axs[i].set_title(\"Label: {}\".format(name))\n    axs[i].axis(\"off\")\n\n# Show the plot\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-11-08T11:25:35.322250Z","iopub.execute_input":"2023-11-08T11:25:35.323132Z","iopub.status.idle":"2023-11-08T11:25:36.870326Z","shell.execute_reply.started":"2023-11-08T11:25:35.323090Z","shell.execute_reply":"2023-11-08T11:25:36.869268Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load the InceptionV3 model without the top (fully connected) layers\nbase_model = InceptionV3(weights='imagenet', include_top=False, input_shape=(150, 150, 3))\nbase_model.trainable = False\n\n# Add a custom head on top of the base model\nmodel = models.Sequential()\n\n# Add the InceptionV3 base model\nmodel.add(base_model)\n\n# Add the custom layers\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(256, activation='relu'))\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.Dense(1, activation='sigmoid'))\n\n# Compile the model\nmodel.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\n\n# Define the number of training steps and validation steps per epoch\ntrain_steps = len(train_images) // batch_size\nval_steps = len(val_images) // batch_size\n\n# Train the model\nhistory = model.fit(\n    train_images,\n    train_labels,\n    batch_size=batch_size,\n    steps_per_epoch=train_steps,\n    epochs=10,\n    validation_data=(val_images, val_labels),\n    validation_steps=val_steps\n)","metadata":{"execution":{"iopub.status.busy":"2023-11-08T11:25:51.369847Z","iopub.execute_input":"2023-11-08T11:25:51.370212Z","iopub.status.idle":"2023-11-08T11:27:47.087978Z","shell.execute_reply.started":"2023-11-08T11:25:51.370181Z","shell.execute_reply":"2023-11-08T11:27:47.087024Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Evaluate the model\neval_results = model.evaluate(val_images, val_labels)\n\n# Print evaluation results\nprint(\"Validation Loss:\", eval_results[0])\nprint(\"Validation Accuracy:\", eval_results[1])\n\n# Plot loss and accuracy\nimport matplotlib.pyplot as plt\n\n# Get the training and validation loss from the history object\ntrain_loss = history.history['loss']\nval_loss = history.history['val_loss']\n\n# Get the training and validation accuracy from the history object\ntrain_acc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\n\n# Plot the loss\nplt.figure(figsize=(12, 6))\nplt.subplot(1, 2, 1)\nplt.plot(range(1, len(train_loss) + 1), train_loss, label='Training Loss')\nplt.plot(range(1, len(val_loss) + 1), val_loss, label='Validation Loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.title('Training and Validation Loss')\nplt.legend()\n# Save the loss plot\nplt.savefig('loss_plot_inceptionv3.png')\n\n# Plot the accuracy\nplt.subplot(1, 2, 2)\nplt.plot(range(1, len(train_acc) + 1), train_acc, label='Training Accuracy')\nplt.plot(range(1, len(val_acc) + 1), val_acc, label='Validation Accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.title('Training and Validation Accuracy')\nplt.legend()\n# Save the accuracy plot\nplt.savefig('accuracy_plot_inceptionv3.png')\n\n# Show the plots\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-11-08T11:28:38.289662Z","iopub.execute_input":"2023-11-08T11:28:38.294912Z","iopub.status.idle":"2023-11-08T11:28:43.442881Z","shell.execute_reply.started":"2023-11-08T11:28:38.294873Z","shell.execute_reply":"2023-11-08T11:28:43.441902Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"The things that you can see in the last epoch of the model are being fitted, which may be due to the low data in the input, the reason for increasing the training speed is that we have only used the part of the training data, or because of the small number of epoch.","metadata":{}},{"cell_type":"code","source":"# Save the model\nmodel.save('/kaggle/working/my_InceptionV3.h5')","metadata":{"execution":{"iopub.status.busy":"2023-11-08T08:55:13.580438Z","iopub.execute_input":"2023-11-08T08:55:13.581537Z","iopub.status.idle":"2023-11-08T08:55:14.241306Z","shell.execute_reply.started":"2023-11-08T08:55:13.581496Z","shell.execute_reply":"2023-11-08T08:55:14.240294Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Training on RandomForest Classifier\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import accuracy_score\n\n# Flatten the images\ntrain_images_flat = train_images.reshape(train_images.shape[0], -1)\nval_images_flat = val_images.reshape(val_images.shape[0], -1)\nall_train_images_flat = all_train_images.reshape(all_train_images.shape[0], -1)\n\n# Create a Random Forest Classifier\nclf = RandomForestClassifier(n_estimators=100, random_state=42)\n\n# Train the classifier\nclf.fit(all_train_images_flat, all_train_labels)\n\n# Make predictions on the validation set\nval_predictions = clf.predict(val_images_flat)\n\n# Calculate accuracy\nval_accuracy = accuracy_score(val_labels, val_predictions)\nprint(\"Validation Accuracy:\", val_accuracy)","metadata":{"execution":{"iopub.status.busy":"2023-11-08T11:48:56.570588Z","iopub.execute_input":"2023-11-08T11:48:56.571261Z","iopub.status.idle":"2023-11-08T11:54:33.716333Z","shell.execute_reply.started":"2023-11-08T11:48:56.571229Z","shell.execute_reply":"2023-11-08T11:54:33.715324Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.applications import MobileNetV2\n\nbase_model = MobileNetV2(weights='imagenet', include_top=False, input_shape=(150, 150, 3))\nbase_model.trainable = False\n\n# Add a custom head on top of the base model\nmodel_mobilenet = models.Sequential()\n\n# Add the MobileNetV2 base model\nmodel_mobilenet.add(base_model)\n\n# Add the custom layers\nmodel_mobilenet.add(layers.GlobalAveragePooling2D())\nmodel_mobilenet.add(layers.Dense(256, activation='relu'))\nmodel_mobilenet.add(layers.Dropout(0.5))\nmodel_mobilenet.add(layers.Dense(1, activation='sigmoid'))\n\n# Compile the model\nmodel_mobilenet.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\n\n# Define the number of training steps and validation steps per epoch\ntrain_steps = len(train_images) // batch_size\nval_steps = len(val_images) // batch_size\n\n# Train the model\nhistory_MobileNetV2 = model_mobilenet.fit(\n    train_images,\n    train_labels,\n    batch_size=batch_size,\n    steps_per_epoch=train_steps,\n    epochs=10,\n    validation_data=(val_images, val_labels),\n    validation_steps=val_steps\n)","metadata":{"execution":{"iopub.status.busy":"2023-11-08T11:57:12.436565Z","iopub.execute_input":"2023-11-08T11:57:12.436941Z","iopub.status.idle":"2023-11-08T11:58:27.930518Z","shell.execute_reply.started":"2023-11-08T11:57:12.436916Z","shell.execute_reply":"2023-11-08T11:58:27.929470Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Evaluate the model\neval_results = model_mobilenet.evaluate(val_images, val_labels)\n\n# Print evaluation results\nprint(\"Validation Loss:\", eval_results[0])\nprint(\"Validation Accuracy:\", eval_results[1])\n\n\n# Get the training and validation loss from the history object\ntrain_loss = history_MobileNetV2.history['loss']\nval_loss = history_MobileNetV2.history['val_loss']\n\n# Get the training and validation accuracy from the history object\ntrain_acc = history_MobileNetV2.history['accuracy']\nval_acc = history_MobileNetV2.history['val_accuracy']\n\n# Plot the loss\nplt.figure(figsize=(12, 6))\nplt.subplot(1, 2, 1)\nplt.plot(range(1, len(train_loss) + 1), train_loss, label='Training Loss')\nplt.plot(range(1, len(val_loss) + 1), val_loss, label='Validation Loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.title('Training and Validation Loss')\nplt.legend()\n# Save the loss plot\nplt.savefig('loss_plot_mobilenetv222222.png')\n\n# Plot the accuracy\nplt.subplot(1, 2, 2)\nplt.plot(range(1, len(train_acc) + 1), train_acc, label='Training Accuracy')\nplt.plot(range(1, len(val_acc) + 1), val_acc, label='Validation Accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.title('Training and Validation Accuracy')\nplt.legend()\n# Save the loss plot\nplt.savefig('accuracy_plot_mobilenetv22222.png')\n\n# Show the plots\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-11-08T12:04:18.236225Z","iopub.execute_input":"2023-11-08T12:04:18.237224Z","iopub.status.idle":"2023-11-08T12:04:22.242018Z","shell.execute_reply.started":"2023-11-08T12:04:18.237172Z","shell.execute_reply":"2023-11-08T12:04:22.240989Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Training Model on MobileNetV2 has better validation accuracy rather than training on InceptionV3.(with these Hyperparameters)","metadata":{}},{"cell_type":"code","source":"# Save the model\nmodel.save('/kaggle/working/my_MobileNetV2.h5')","metadata":{"execution":{"iopub.status.busy":"2023-11-08T09:02:11.991051Z","iopub.execute_input":"2023-11-08T09:02:11.992151Z","iopub.status.idle":"2023-11-08T09:02:12.969477Z","shell.execute_reply.started":"2023-11-08T09:02:11.992111Z","shell.execute_reply":"2023-11-08T09:02:12.968597Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras import models, layers\n\nmodel_cnn = models.Sequential()\n\n# Add the convolutional layers\nmodel_cnn.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)))\nmodel_cnn.add(layers.MaxPooling2D((2, 2)))\nmodel_cnn.add(layers.Conv2D(64, (3, 3), activation='relu'))\nmodel_cnn.add(layers.MaxPooling2D((2, 2)))\nmodel_cnn.add(layers.Conv2D(128, (3, 3), activation='relu'))\nmodel_cnn.add(layers.MaxPooling2D((2, 2)))\n\n# Flatten the output from the convolutional layers\nmodel_cnn.add(layers.Flatten())\n\n# Add the fully connected layers\nmodel_cnn.add(layers.Dense(256, activation='relu'))\nmodel_cnn.add(layers.Dropout(0.5))\nmodel_cnn.add(layers.Dense(1, activation='sigmoid'))\n\n# Compile the model\nmodel_cnn.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\n\n# Define the number of training steps and validation steps per epoch\ntrain_steps = len(train_images) // batch_size\nval_steps = len(val_images) // batch_size\n\n# Train the model\nhistory_cnn = model_cnn.fit(\n    train_images,\n    train_labels,\n    batch_size=batch_size,\n    steps_per_epoch=train_steps,\n    epochs=10,\n    validation_data=(val_images, val_labels),\n    validation_steps=val_steps\n)","metadata":{"execution":{"iopub.status.busy":"2023-11-08T12:02:30.374495Z","iopub.execute_input":"2023-11-08T12:02:30.374886Z","iopub.status.idle":"2023-11-08T12:03:41.391544Z","shell.execute_reply.started":"2023-11-08T12:02:30.374857Z","shell.execute_reply":"2023-11-08T12:03:41.390528Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Evaluate the model\neval_results = model_cnn.evaluate(val_images, val_labels)\n\n# Print evaluation results\nprint(\"Validation Loss:\", eval_results[0])\nprint(\"Validation Accuracy:\", eval_results[1])\n\n# Plot loss and accuracy\nimport matplotlib.pyplot as plt\n\n# Get the training and validation loss from the history object\ntrain_loss = history_cnn.history['loss']\nval_loss = history_cnn.history['val_loss']\n\n# Get the training and validation accuracy from the history object\ntrain_acc = history_cnn.history['accuracy']\nval_acc = history_cnn.history['val_accuracy']\n\n# Plot the loss\nplt.figure(figsize=(12, 6))\nplt.subplot(1, 2, 1)\nplt.plot(range(1, len(train_loss) + 1), train_loss, label='Training Loss')\nplt.plot(range(1, len(val_loss) + 1), val_loss, label='Validation Loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.title('Training and Validation Loss')\nplt.legend()\n# Save the loss plot\nplt.savefig('loss_plot_cnn.png')\n\n# Plot the accuracy\nplt.subplot(1, 2, 2)\nplt.plot(range(1, len(train_acc) + 1), train_acc, label='Training Accuracy')\nplt.plot(range(1, len(val_acc) + 1), val_acc, label='Validation Accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.title('Training and Validation Accuracy')\nplt.legend()\n# Save the loss plot\nplt.savefig('accuracy_plot_cnn.png')\n\n# Show the plots\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-11-08T12:09:36.065167Z","iopub.execute_input":"2023-11-08T12:09:36.065549Z","iopub.status.idle":"2023-11-08T12:09:38.939989Z","shell.execute_reply.started":"2023-11-08T12:09:36.065520Z","shell.execute_reply":"2023-11-08T12:09:38.938981Z"},"trusted":true},"execution_count":null,"outputs":[]}]}