{"metadata":{"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":11848,"databundleVersionId":862157,"sourceType":"competition"},{"sourceId":999617,"sourceType":"datasetVersion","datasetId":209316},{"sourceId":207626973,"sourceType":"kernelVersion"}],"dockerImageVersionId":30787,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true},"kernelspec":{"display_name":"Python 3","language":"python","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"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"## 1. Load Library","metadata":{}},{"cell_type":"code","source":"!pip install -U efficientnet -qq","metadata":{"execution":{"iopub.status.busy":"2024-11-16T04:43:58.423959Z","iopub.execute_input":"2024-11-16T04:43:58.424807Z","iopub.status.idle":"2024-11-16T04:44:09.904687Z","shell.execute_reply.started":"2024-11-16T04:43:58.424766Z","shell.execute_reply":"2024-11-16T04:44:09.903679Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\n\nimport numpy as np\nimport tensorflow.keras.layers as tfl\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.initializers import random_uniform, glorot_uniform\nimport efficientnet.tfkeras as efn\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import * \nimport os\nimport shutil\nimport json\n\nfrom PIL import Image","metadata":{"execution":{"iopub.status.busy":"2024-11-16T04:44:14.823675Z","iopub.execute_input":"2024-11-16T04:44:14.824078Z","iopub.status.idle":"2024-11-16T04:44:14.831454Z","shell.execute_reply.started":"2024-11-16T04:44:14.824039Z","shell.execute_reply":"2024-11-16T04:44:14.830410Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ndef train_img_path(id_str):\n    return os.path.join(r\"/kaggle/input/histopathologic-cancer-detection/train\", f\"{id_str}.tif\")","metadata":{"execution":{"iopub.status.busy":"2024-11-16T04:44:16.740440Z","iopub.execute_input":"2024-11-16T04:44:16.741067Z","iopub.status.idle":"2024-11-16T04:44:16.745867Z","shell.execute_reply.started":"2024-11-16T04:44:16.741026Z","shell.execute_reply":"2024-11-16T04:44:16.744899Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 2. Exploratory Data Analysis","metadata":{}},{"cell_type":"code","source":"example_path = \"/kaggle/input/histopathologic-cancer-detection/train/f38a6374c348f90b587e046aac6079959adf3835.tif\"\nexample_img = Image.open(example_path)\nexample_array = np.array(example_img)\nprint(f\"Image Shape = {example_array.shape}\")\nplt.imshow(example_img)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-11-16T04:44:18.721063Z","iopub.execute_input":"2024-11-16T04:44:18.721755Z","iopub.status.idle":"2024-11-16T04:44:18.935169Z","shell.execute_reply.started":"2024-11-16T04:44:18.721712Z","shell.execute_reply":"2024-11-16T04:44:18.934341Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_labels_df = pd.read_csv('/kaggle/input/histopathologic-cancer-detection/train_labels.csv')\ntrain_labels_df[\"filename\"] = train_labels_df[\"id\"].apply(train_img_path)\ntrain_labels_df[\"label\"] = train_labels_df[\"label\"].astype(str)\ntrain_labels_df.head()","metadata":{"execution":{"iopub.status.busy":"2024-11-16T04:44:20.711693Z","iopub.execute_input":"2024-11-16T04:44:20.712053Z","iopub.status.idle":"2024-11-16T04:44:21.490684Z","shell.execute_reply.started":"2024-11-16T04:44:20.712020Z","shell.execute_reply":"2024-11-16T04:44:21.489738Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_labels_df.shape","metadata":{"execution":{"iopub.status.busy":"2024-11-16T04:44:22.788973Z","iopub.execute_input":"2024-11-16T04:44:22.789359Z","iopub.status.idle":"2024-11-16T04:44:22.795322Z","shell.execute_reply.started":"2024-11-16T04:44:22.789323Z","shell.execute_reply":"2024-11-16T04:44:22.794446Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_labels_df[\"label\"][0]","metadata":{"execution":{"iopub.status.busy":"2024-11-16T04:44:24.518162Z","iopub.execute_input":"2024-11-16T04:44:24.519054Z","iopub.status.idle":"2024-11-16T04:44:24.524976Z","shell.execute_reply.started":"2024-11-16T04:44:24.519013Z","shell.execute_reply":"2024-11-16T04:44:24.524039Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"set(train_labels_df['label'])","metadata":{"execution":{"iopub.status.busy":"2024-11-16T04:44:26.050691Z","iopub.execute_input":"2024-11-16T04:44:26.051062Z","iopub.status.idle":"2024-11-16T04:44:26.088437Z","shell.execute_reply.started":"2024-11-16T04:44:26.051026Z","shell.execute_reply":"2024-11-16T04:44:26.087481Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(15,7))\nax = sns.countplot(data=train_labels_df , x=train_labels_df['label'])\n\nplt.xlabel('classes 0=not cancerous , 1=cancerous')\nplt.ylabel('Number of Recourd')\nplt.title('Count of images in each class', fontsize=20)\nax.bar_label(ax.containers[0])\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-11-16T04:44:45.170357Z","iopub.execute_input":"2024-11-16T04:44:45.171077Z","iopub.status.idle":"2024-11-16T04:44:45.693711Z","shell.execute_reply.started":"2024-11-16T04:44:45.171037Z","shell.execute_reply":"2024-11-16T04:44:45.692820Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"We have 220,025 images in the train data set with 2 unique labels. 0 for not cancerous and 1 for cancerous tissues.","metadata":{}},{"cell_type":"markdown","source":"## Label 0 = Not-Cancerous\n## Label 1 = Cancerous","metadata":{}},{"cell_type":"code","source":"train_labels_df['label'].value_counts(normalize = True)","metadata":{"execution":{"iopub.status.busy":"2024-11-16T04:44:52.530187Z","iopub.execute_input":"2024-11-16T04:44:52.531023Z","iopub.status.idle":"2024-11-16T04:44:52.572923Z","shell.execute_reply.started":"2024-11-16T04:44:52.530974Z","shell.execute_reply":"2024-11-16T04:44:52.571949Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_data = np.empty((100, 96, 96, 3), dtype=np.uint8)\nsample_labels = np.empty(100, dtype=np.int8)\nfor i in range(len(train_labels_df))[:100]:\n    img_path = train_img_path(train_labels_df['id'][i])\n    img = Image.open(img_path)\n    sample_data[i] = np.array(img)\n    sample_labels[i] = train_labels_df['label'][i]","metadata":{"execution":{"iopub.status.busy":"2024-11-16T04:44:53.020195Z","iopub.execute_input":"2024-11-16T04:44:53.020543Z","iopub.status.idle":"2024-11-16T04:44:53.209096Z","shell.execute_reply.started":"2024-11-16T04:44:53.020508Z","shell.execute_reply":"2024-11-16T04:44:53.208413Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Non-Cancerous Images\")\n\nselected_images = np.random.choice(sample_data[sample_labels == 0].shape[0], 12, replace=False)\ngrid_size = int(np.ceil(np.sqrt(12)))\n\nfig, axs = plt.subplots(grid_size, grid_size, figsize=(5, 5))\n\nfor i, ax in enumerate(axs.flatten()):\n    if i < 12:\n        ax.imshow(sample_data[sample_labels == 0][selected_images[i]])\n        ax.axis('off') \n    else:\n        fig.delaxes(ax) \n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-11-16T04:44:54.202299Z","iopub.execute_input":"2024-11-16T04:44:54.203041Z","iopub.status.idle":"2024-11-16T04:44:54.662189Z","shell.execute_reply.started":"2024-11-16T04:44:54.203003Z","shell.execute_reply":"2024-11-16T04:44:54.661302Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Cancerous Images\")\n\nselected_images = np.random.choice(sample_data[sample_labels == 1].shape[0], 12, replace=False)\ngrid_size = int(np.ceil(np.sqrt(12)))\n\nfig, axs = plt.subplots(grid_size, grid_size, figsize=(5, 5))\n\nfor i, ax in enumerate(axs.flatten()):\n    if i < 12:\n        ax.imshow(sample_data[sample_labels == 1][selected_images[i]])\n        ax.axis('off') \n    else:\n        fig.delaxes(ax) \n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-11-16T04:44:55.560340Z","iopub.execute_input":"2024-11-16T04:44:55.561021Z","iopub.status.idle":"2024-11-16T04:44:56.046333Z","shell.execute_reply.started":"2024-11-16T04:44:55.560983Z","shell.execute_reply":"2024-11-16T04:44:56.045178Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 3. Model Designing","metadata":{}},{"cell_type":"code","source":"test_path = \"/kaggle/input/histopathologic-cancer-detection/test\"\ntest_ids = [filename[:-4] for filename in os.listdir(test_path)]\ntest_filenames = [os.path.join(test_path, filename) for filename in os.listdir(test_path)]\ntest_df = pd.DataFrame()\ntest_df[\"id\"] = test_ids\ntest_df[\"filename\"] = test_filenames","metadata":{"execution":{"iopub.status.busy":"2024-11-16T04:44:57.681332Z","iopub.execute_input":"2024-11-16T04:44:57.682165Z","iopub.status.idle":"2024-11-16T04:44:57.875981Z","shell.execute_reply.started":"2024-11-16T04:44:57.682123Z","shell.execute_reply":"2024-11-16T04:44:57.875210Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale = 1/255, validation_split = 0.2)","metadata":{"execution":{"iopub.status.busy":"2024-11-16T04:44:58.040316Z","iopub.execute_input":"2024-11-16T04:44:58.041075Z","iopub.status.idle":"2024-11-16T04:44:58.045438Z","shell.execute_reply.started":"2024-11-16T04:44:58.041032Z","shell.execute_reply":"2024-11-16T04:44:58.044470Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_generator = datagen.flow_from_dataframe(\n    shuffle = True,\n    dataframe = train_labels_df,\n    x_col = \"filename\",\n    y_col = \"label\",\n    target_size = (96, 96),\n    color_mode = \"rgb\",\n    batch_size = 32,\n    class_mode = \"binary\",\n    subset = \"training\",\n    validate_filenames = False,\n    seed = 10\n)\n\nvalidation_generator = datagen.flow_from_dataframe(\n    shuffle = True,\n    dataframe=train_labels_df,\n    x_col = \"filename\",\n    y_col = \"label\",\n    target_size=(96, 96),\n    color_mode = \"rgb\",\n    batch_size = 32,\n    class_mode = \"binary\",\n    subset = \"validation\",\n    validate_filenames = False,\n    seed = 10\n)","metadata":{"execution":{"iopub.status.busy":"2024-11-16T04:44:59.301417Z","iopub.execute_input":"2024-11-16T04:44:59.302029Z","iopub.status.idle":"2024-11-16T04:45:00.546786Z","shell.execute_reply.started":"2024-11-16T04:44:59.301990Z","shell.execute_reply":"2024-11-16T04:45:00.545887Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_generator = datagen.flow_from_dataframe(\n    dataframe = test_df,\n    x_col = \"filename\",\n    y_col = None,\n    target_size = (96, 96),\n    color_mode = \"rgb\",\n    batch_size = 64,\n    shuffle = False,\n    class_mode = None,\n    validate_filenames = False,\n    seed = 10\n)","metadata":{"execution":{"iopub.status.busy":"2024-11-16T04:45:01.710004Z","iopub.execute_input":"2024-11-16T04:45:01.710441Z","iopub.status.idle":"2024-11-16T04:45:01.825323Z","shell.execute_reply.started":"2024-11-16T04:45:01.710397Z","shell.execute_reply":"2024-11-16T04:45:01.824474Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_steps = 176020//32  \nval_steps = 44005//32  ","metadata":{"execution":{"iopub.status.busy":"2024-11-16T04:45:02.990395Z","iopub.execute_input":"2024-11-16T04:45:02.991684Z","iopub.status.idle":"2024-11-16T04:45:02.996586Z","shell.execute_reply.started":"2024-11-16T04:45:02.991623Z","shell.execute_reply":"2024-11-16T04:45:02.995505Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Scratch","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras import layers, models, optimizers\nfrom tensorflow.keras.layers import LSTM, Dropout, BatchNormalization\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau\n\ndef create_fine_tuned_cnn_rnn_hybrid_model(input_shape=(96, 96, 3), num_classes=2):\n    model = models.Sequential()\n\n    # CNN Blocks\n    model.add(layers.Conv2D(128, (3, 3), activation='relu', padding='same', input_shape=input_shape))\n    model.add(layers.BatchNormalization())\n    model.add(layers.MaxPooling2D((2, 2)))\n    model.add(layers.Dropout(0.2))  # Dropout for regularization\n\n    model.add(layers.Conv2D(256, (3, 3), activation='relu', padding='same'))\n    model.add(layers.BatchNormalization())\n    model.add(layers.MaxPooling2D((2, 2)))\n    model.add(layers.Dropout(0.3))\n\n    model.add(layers.Conv2D(1024, (3, 3), activation='relu', padding='same'))\n    model.add(layers.BatchNormalization())\n    model.add(layers.MaxPooling2D((2, 2)))\n    model.add(layers.Dropout(0.4))\n    \n    model.add(layers.Conv2D(1024, (3, 3), activation='relu', padding='same'))\n    model.add(layers.BatchNormalization())\n    model.add(layers.MaxPooling2D((2, 2)))\n    model.add(layers.Dropout(0.5))\n\n    # Global Average Pooling\n    model.add(layers.GlobalAveragePooling2D())\n\n    # Reshape for RNN layer\n    model.add(layers.Reshape((1, -1)))  # Adding time-step dimension for RNN compatibility\n\n    # RNN Layers\n    model.add(LSTM(256, activation='relu', return_sequences=True))\n    model.add(Dropout(0.3))\n    model.add(LSTM(64, activation='relu'))\n\n    # Fully Connected Layers\n    model.add(layers.Dense(256, activation='relu'))\n    model.add(BatchNormalization())\n    model.add(Dropout(0.4))\n\n    model.add(layers.Dense(256, activation='relu'))\n    model.add(BatchNormalization())\n    model.add(Dropout(0.3))\n\n    model.add(layers.Dense(128, activation='relu'))\n    model.add(BatchNormalization())\n\n    # Output layer\n    model.add(layers.Dense(num_classes, activation='softmax'))\n\n    return model\n\n# Create the model\nmodel_cnn_rnn_hybrid_fine_tuned = create_fine_tuned_cnn_rnn_hybrid_model()\n\n# Compile the model\noptimizer = optimizers.Adam(learning_rate=0.001)\nmodel_cnn_rnn_hybrid_fine_tuned.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy', metrics=['accuracy'])\n\n# Learning rate scheduler callback\nlr_scheduler = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=5, verbose=1)\n\n# Summary of the model architecture\nmodel_cnn_rnn_hybrid_fine_tuned.summary()\n","metadata":{"execution":{"iopub.status.busy":"2024-11-16T04:45:05.955842Z","iopub.execute_input":"2024-11-16T04:45:05.956199Z","iopub.status.idle":"2024-11-16T04:45:06.506794Z","shell.execute_reply.started":"2024-11-16T04:45:05.956166Z","shell.execute_reply":"2024-11-16T04:45:06.505938Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Training the model\nh3 = model_cnn_rnn_hybrid_fine_tuned.fit(\n    train_generator,\n    steps_per_epoch=train_steps,\n    validation_data=validation_generator,\n    validation_steps=val_steps,\n    epochs=10\n)\n\n# Saving the entire model\nmodel_cnn_rnn_hybrid_fine_tuned.save('CNN_RNN_HY.h5')\n","metadata":{"execution":{"iopub.status.busy":"2024-11-16T04:45:11.600725Z","iopub.execute_input":"2024-11-16T04:45:11.601670Z","iopub.status.idle":"2024-11-16T05:31:20.798286Z","shell.execute_reply.started":"2024-11-16T04:45:11.601625Z","shell.execute_reply":"2024-11-16T05:31:20.797224Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.models import load_model\nimport numpy as np\n\ndef load_and_preprocess_image(img_path, target_size=(96, 96)):\n    # Load and preprocess the image\n    img = image.load_img(img_path, target_size=target_size)\n    img_array = image.img_to_array(img)\n    img_array = np.expand_dims(img_array, axis=0)  # Add batch dimension\n    img_array = img_array / 255.0  # Normalize pixel values to [0, 1]\n    return img_array\n\ndef predict_image(model, img_path):\n    # Preprocess the image and make a prediction\n    img_array = load_and_preprocess_image(img_path)\n    prediction = model.predict(img_array)\n    return prediction\n\n# Example usage:\nimg_path = \"/kaggle/input/histopathologic-cancer-detection/test/000309e669fa3b18fb0ed6a253a2850cce751a95.tif\"\nprediction = predict_image(model_cnn_rnn_hybrid_fine_tuned, img_path)\n\n# Format the prediction to display up to 6 decimal places\nformatted_prediction = np.around(prediction, decimals=6)\n\n# Print the formatted prediction\nprint(\"Formatted Prediction:\", formatted_prediction)\n\n# Get the predicted class (binary classification, so use argmax)\npredicted_class = np.argmax(prediction, axis=-1)\nprint(\"Predicted class:\", predicted_class)\n","metadata":{"execution":{"iopub.status.busy":"2024-11-16T05:41:21.431426Z","iopub.execute_input":"2024-11-16T05:41:21.431814Z","iopub.status.idle":"2024-11-16T05:41:21.514923Z","shell.execute_reply.started":"2024-11-16T05:41:21.431776Z","shell.execute_reply":"2024-11-16T05:41:21.514012Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.models import load_model\nimport numpy as np\n\ndef load_and_preprocess_image(img_path, target_size=(96, 96)):\n    # Load and preprocess the image\n    img = image.load_img(img_path, target_size=target_size)\n    img_array = image.img_to_array(img)\n    img_array = np.expand_dims(img_array, axis=0)  # Add batch dimension\n    img_array = img_array / 255.0  # Normalize pixel values to [0, 1]\n    return img_array\n\ndef predict_image(model, img_path):\n    # Preprocess the image and make a prediction\n    img_array = load_and_preprocess_image(img_path)\n    prediction = model.predict(img_array)\n    return prediction\n\n# Example usage:\nimg_path = \"/kaggle/input/histopathologic-cancer-detection/test/00118bec91b7fae175791896f7011ff506b3d7dd.tif\"\nprediction = predict_image(model_cnn_rnn_hybrid_fine_tuned, img_path)\n\n# Format the prediction to display up to 6 decimal places\nformatted_prediction = np.around(prediction, decimals=6)\n\n# Print the formatted prediction\nprint(\"Formatted Prediction:\", formatted_prediction)\n\n# Get the predicted class (binary classification, so use argmax)\npredicted_class = np.argmax(prediction, axis=-1)\nprint(\"Predicted class:\", predicted_class)\n","metadata":{"execution":{"iopub.status.busy":"2024-11-16T05:41:43.963939Z","iopub.execute_input":"2024-11-16T05:41:43.964348Z","iopub.status.idle":"2024-11-16T05:41:44.040764Z","shell.execute_reply.started":"2024-11-16T05:41:43.964304Z","shell.execute_reply":"2024-11-16T05:41:44.039852Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.models import load_model\nimport numpy as np\n\ndef load_and_preprocess_image(img_path, target_size=(96, 96)):\n    # Load and preprocess the image\n    img = image.load_img(img_path, target_size=target_size)\n    img_array = image.img_to_array(img)\n    img_array = np.expand_dims(img_array, axis=0)  # Add batch dimension\n    img_array = img_array / 255.0  # Normalize pixel values to [0, 1]\n    return img_array\n\ndef predict_image(model, img_path):\n    # Preprocess the image and make a prediction\n    img_array = load_and_preprocess_image(img_path)\n    prediction = model.predict(img_array)\n    return prediction\n\n# Example usage:\nimg_path = \"/kaggle/input/histopathologic-cancer-detection/train/c3d660212bf2a11c994e0eadff13770a9927b731.tif\"\nprediction = predict_image(model_cnn_rnn_hybrid_fine_tuned, img_path)\n\n# Format the prediction to display up to 6 decimal places\nformatted_prediction = np.around(prediction, decimals=6)\n\n# Print the formatted prediction\nprint(\"Formatted Prediction:\", formatted_prediction)\n\n# Get the predicted class (binary classification, so use argmax)\npredicted_class = np.argmax(prediction, axis=-1)\nprint(\"Predicted class:\", predicted_class)\n","metadata":{"execution":{"iopub.status.busy":"2024-11-16T05:44:41.894036Z","iopub.execute_input":"2024-11-16T05:44:41.894810Z","iopub.status.idle":"2024-11-16T05:44:41.967605Z","shell.execute_reply.started":"2024-11-16T05:44:41.894771Z","shell.execute_reply":"2024-11-16T05:44:41.966699Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import precision_score, recall_score, accuracy_score\n\n# Calculate precision, recall, and accuracy for binary classification\nprecision = precision_score(y_true, y_pred_classes)  # Default average='binary' for binary classification\nrecall = recall_score(y_true, y_pred_classes)  # Default average='binary' for binary classification\naccuracy = accuracy_score(y_true, y_pred_classes)\nf1_score = f1_score(y_true, y_pred_classes)\n\n# Plotting the metrics\nmetrics = {'Accuracy': accuracy,'F1 Score': f1_score,'Precision': precision, 'Recall': recall}\nplt.bar(metrics.keys(), metrics.values(), color=['blue', 'green','orange','red'])\nplt.title('Model Metrics')\nplt.ylabel('Score')\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-11-16T05:55:59.260937Z","iopub.execute_input":"2024-11-16T05:55:59.261693Z","iopub.status.idle":"2024-11-16T05:55:59.442282Z","shell.execute_reply.started":"2024-11-16T05:55:59.261652Z","shell.execute_reply":"2024-11-16T05:55:59.441344Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nfrom sklearn.metrics import confusion_matrix\nimport seaborn as sns\nimport numpy as np\n\n# Predict on the validation set\ny_pred = model_t.predict(validation_generator)  # Using model_t for predictions\ny_pred_classes = np.argmax(y_pred, axis=1)  # Get predicted class labels\ny_true = validation_generator.classes  # Ground truth labels\n\n# Generate confusion matrix\ncm = confusion_matrix(y_true, y_pred_classes)\n\n# Normalize the confusion matrix by dividing by the sum of each row (true labels)\ncm_normalized = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n\n# Plotting the normalized confusion matrix\nplt.figure(figsize=(8, 6))\nsns.heatmap(cm_normalized, annot=True, fmt='.2f', cmap='Blues', \n            xticklabels=validation_generator.class_indices.keys(), \n            yticklabels=validation_generator.class_indices.keys())\nplt.title('Normalized Confusion Matrix')\nplt.xlabel('Predicted')\nplt.ylabel('True')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-11-16T05:58:24.363006Z","iopub.execute_input":"2024-11-16T05:58:24.363664Z","iopub.status.idle":"2024-11-16T05:58:24.635716Z","shell.execute_reply.started":"2024-11-16T05:58:24.363623Z","shell.execute_reply":"2024-11-16T05:58:24.634785Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}