{"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":84209,"databundleVersionId":9414711,"sourceType":"competition"}],"dockerImageVersionId":30804,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2024-12-20T11:19:02.500637Z","iopub.execute_input":"2024-12-20T11:19:02.501043Z","iopub.status.idle":"2024-12-20T11:19:12.123831Z","shell.execute_reply.started":"2024-12-20T11:19:02.500993Z","shell.execute_reply":"2024-12-20T11:19:12.122822Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Loading Libraries","metadata":{}},{"cell_type":"code","source":"#random data point selection\nimport random\n\n#numerical calculations and data manipulation\nimport numpy as np\nimport pandas as pd\n\n#data visualization\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n#reading images\nimport matplotlib.image as mpimg\n\n#deep learning packages\nfrom keras.models import Sequential, Model\nfrom keras.applications.vgg16 import VGG16\nfrom tensorflow.keras.utils import img_to_array, load_img\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, BatchNormalization, Dropout\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator \n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T11:19:51.390573Z","iopub.execute_input":"2024-12-20T11:19:51.391064Z","iopub.status.idle":"2024-12-20T11:20:04.663485Z","shell.execute_reply.started":"2024-12-20T11:19:51.391030Z","shell.execute_reply":"2024-12-20T11:20:04.662674Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Loading the Data","metadata":{}},{"cell_type":"code","source":"#Parent Directory\npar_dir='/kaggle/input/computer-vision-xm'\n\n# Image Path\nimage_dir = os.path.join(par_dir, 'images/kaggle/working/Reorganized_Data/images')\n\n# Image Training Labels\ntrain_df=pd.read_csv('/kaggle/input/computer-vision-xm/train.csv')\n\n# Image Testing Labels\n\ntest_df=pd.read_csv('/kaggle/input/computer-vision-xm/test.csv')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T11:20:25.910151Z","iopub.execute_input":"2024-12-20T11:20:25.911764Z","iopub.status.idle":"2024-12-20T11:20:25.945213Z","shell.execute_reply.started":"2024-12-20T11:20:25.911705Z","shell.execute_reply":"2024-12-20T11:20:25.943994Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import cv2\n\n# Image size and batch size\nIMG_SIZE = 128\nBATCH_SIZE = 32\n\n# Load and resize images\ndef load_and_process_image(image_path):\n    image = cv2.imread(image_path)\n    image = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\n    image = image / 255.0  # normalize image size\n    return image\n\n# Apply preprocessing to all images\nimages = []\nlabels = []\n\nfor i, row in train_df.iterrows():\n    image_path = os.path.join(image_dir, row['Images'])\n    images.append(load_and_process_image(image_path))\n    labels.append(row['Labels'])\n\n# Convert lists to numpy arrays\nX = np.array(images)\ny = np.array(labels)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T11:20:51.460453Z","iopub.execute_input":"2024-12-20T11:20:51.460824Z","iopub.status.idle":"2024-12-20T11:31:15.047457Z","shell.execute_reply.started":"2024-12-20T11:20:51.460792Z","shell.execute_reply":"2024-12-20T11:31:15.046680Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Visualizing Images","metadata":{}},{"cell_type":"code","source":"train_file_names = os.listdir(image_dir)\n\n\nfig = plt.figure(figsize=(16, 8))\nfig.set_size_inches(16, 16)\n\nleaf_img_paths = [os.path.join(image_dir, file_name) for file_name in train_file_names[:8]]\n\n\nfor i, img_path in enumerate(leaf_img_paths):\n    ax = plt.subplot(4, 4, i + 1)\n    ax.axis('Off')\n\n    img = mpimg.imread(img_path)\n    plt.imshow(img)\n\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T11:31:25.969857Z","iopub.execute_input":"2024-12-20T11:31:25.970592Z","iopub.status.idle":"2024-12-20T11:31:43.871175Z","shell.execute_reply.started":"2024-12-20T11:31:25.970554Z","shell.execute_reply":"2024-12-20T11:31:43.870277Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### As the leaf shapes vary, we will use Data Augmentation to leverage the translational invariance of our model.  First we will split our data into a training and validation set to avoid data leakage.","metadata":{}},{"cell_type":"code","source":"# Splitting our data\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)\n\nprint(f\"Training data: {X_train.shape}, Validation data: {X_val.shape}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T11:31:57.181748Z","iopub.execute_input":"2024-12-20T11:31:57.182614Z","iopub.status.idle":"2024-12-20T11:31:57.740542Z","shell.execute_reply.started":"2024-12-20T11:31:57.182576Z","shell.execute_reply":"2024-12-20T11:31:57.739508Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Data Augmentation","metadata":{}},{"cell_type":"code","source":"# All images to be rescaled by 1/255.\ntrain_datagen = ImageDataGenerator(horizontal_flip = True,\n                              vertical_flip = False, \n                              height_shift_range= 0.1, \n                              width_shift_range=0.1, \n                              rotation_range=20, \n                              shear_range = 0.1,\n                              zoom_range=0.1)\nval_datagen  = ImageDataGenerator()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T11:32:00.804992Z","iopub.execute_input":"2024-12-20T11:32:00.805387Z","iopub.status.idle":"2024-12-20T11:32:00.811073Z","shell.execute_reply.started":"2024-12-20T11:32:00.805354Z","shell.execute_reply":"2024-12-20T11:32:00.809880Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Flowing the augmented images into the training and validation set\n\ntrain_generator = train_datagen.flow(X_train, y_train, batch_size=BATCH_SIZE)\nval_generator = val_datagen.flow(X_val, y_val, batch_size=BATCH_SIZE)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T11:32:05.412449Z","iopub.execute_input":"2024-12-20T11:32:05.412816Z","iopub.status.idle":"2024-12-20T11:32:05.693565Z","shell.execute_reply.started":"2024-12-20T11:32:05.412785Z","shell.execute_reply":"2024-12-20T11:32:05.692508Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Viewing the augmented images\n\nimages, labels = next(train_generator)\nfig, axes = plt.subplots(4, 4, figsize = (16, 8))\nfig.set_size_inches(16, 16)\nfor (image, label, ax) in zip(images, labels, axes.flatten()):\n    ax.imshow(image)\n    if label == 1: \n        ax.set_title('Diseased Leaf')\n    else:\n        ax.set_title('Healthy Leaf')\n    ax.axis('off')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T11:32:08.189472Z","iopub.execute_input":"2024-12-20T11:32:08.189868Z","iopub.status.idle":"2024-12-20T11:32:10.472629Z","shell.execute_reply.started":"2024-12-20T11:32:08.189835Z","shell.execute_reply":"2024-12-20T11:32:10.471182Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Transfer Learning using VGG16","metadata":{}},{"cell_type":"code","source":"# viewing the VGG16 architecture\nmodel=VGG16(weights='imagenet')\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T11:32:26.665301Z","iopub.execute_input":"2024-12-20T11:32:26.665902Z","iopub.status.idle":"2024-12-20T11:32:32.116256Z","shell.execute_reply.started":"2024-12-20T11:32:26.665862Z","shell.execute_reply":"2024-12-20T11:32:32.115128Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.applications import VGG16\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Flatten, Dense\n\n# Load the VGG16 model without the top layers and specify the input shape\nvgg_model = VGG16(weights='imagenet', include_top=False, input_shape=(128, 128, 3))\n\n# Freeze the convolutional base (optional)\nfor layer in vgg_model.layers:\n    layer.trainable = False\n\n# Create a new Sequential model\nnew_model = Sequential()\n\n# Add the VGG16 model as the base\nnew_model.add(vgg_model)\n\n# Add a Flatten layer\nnew_model.add(Flatten())\n\n# Add custom dense layers\nnew_model.add(Dense(64, activation='relu'))\nnew_model.add(Dense(32, activation='relu'))\nnew_model.add(Dense(1, activation='sigmoid'))  # Binary classification\n\n# Forcefully build the model by providing an input tensor\nnew_model.build(input_shape=(None, 128, 128, 3))\n\n# Compile the model\nnew_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\n\n# Display the model summary\nnew_model.summary()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T11:32:35.368967Z","iopub.execute_input":"2024-12-20T11:32:35.369816Z","iopub.status.idle":"2024-12-20T11:32:36.074905Z","shell.execute_reply.started":"2024-12-20T11:32:35.369778Z","shell.execute_reply":"2024-12-20T11:32:36.073936Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Training the Model","metadata":{}},{"cell_type":"code","source":"\nfrom tensorflow.keras.callbacks import EarlyStopping  # Regularization method to prevent the overfitting\nfrom tensorflow.keras.callbacks import ModelCheckpoint\n\n# The following lines of code saves the best model's parameters if training accuracy goes down on further training\nes = EarlyStopping(monitor = 'val_loss', mode = 'min', verbose = 1, patience = 5)\nmc = ModelCheckpoint('best_model.keras', monitor = 'val_accuracy', mode = 'max', verbose = 1, save_best_only = True) # Changed the file extension to .keras\n\n# Fitting the model with 30 epochs and validation_split as 10%\nhistory=new_model.fit(train_generator, \n                      validation_data=val_generator,\n                      epochs=15,\n                      callbacks = [es, mc])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T11:32:44.694283Z","iopub.execute_input":"2024-12-20T11:32:44.694667Z","iopub.status.idle":"2024-12-20T11:35:12.726025Z","shell.execute_reply.started":"2024-12-20T11:32:44.694634Z","shell.execute_reply":"2024-12-20T11:35:12.725059Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Plotting the training and validation accuracies for each epoch\n\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'validation'], loc='upper left')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T11:37:43.177373Z","iopub.execute_input":"2024-12-20T11:37:43.178059Z","iopub.status.idle":"2024-12-20T11:37:43.392726Z","shell.execute_reply.started":"2024-12-20T11:37:43.178020Z","shell.execute_reply":"2024-12-20T11:37:43.391710Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# importing metrics\nfrom sklearn.metrics import accuracy_score, classification_report, confusion_matrix\n\n# Predictions on validation data\ny_pred = new_model.predict(X_val)\ny_pred_classes = np.where(y_pred > 0.5, 1, 0)\n\n# Evaluate performance\nprint(f\"Accuracy: {accuracy_score(y_val, y_pred_classes)}\")\nprint(\"Classification Report:\")\nprint(classification_report(y_val, y_pred_classes))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T11:37:46.189788Z","iopub.execute_input":"2024-12-20T11:37:46.190172Z","iopub.status.idle":"2024-12-20T11:37:48.468807Z","shell.execute_reply.started":"2024-12-20T11:37:46.190138Z","shell.execute_reply":"2024-12-20T11:37:48.467835Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Plotting the heatmap using confusion matrix\ncm = confusion_matrix(y_val, y_pred_classes)\nplt.figure(figsize = (8, 5))\nsns.heatmap(cm, annot = True,  fmt = '.0f', xticklabels = ['Healthy', 'Diseased'], yticklabels=['Healthy', 'Diseased'])\nplt.ylabel('Actual')\nplt.xlabel('Predicted')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T11:37:50.689297Z","iopub.execute_input":"2024-12-20T11:37:50.690093Z","iopub.status.idle":"2024-12-20T11:37:50.943214Z","shell.execute_reply.started":"2024-12-20T11:37:50.690059Z","shell.execute_reply":"2024-12-20T11:37:50.942274Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Evaluating on the Test Set","metadata":{}},{"cell_type":"code","source":"# Image size and batch size\nIMG_SIZE = 128\nBATCH_SIZE = 32\n\n# Load and resize images\ndef load_and_process_image(image_path):\n    image = cv2.imread(image_path)\n    image = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\n    image = image / 255.0  # normalize image size\n    return image\n\n# Apply preprocessing to all images\nimages = []\n\n\nfor i, row in test_df.iterrows():\n    image_path = os.path.join(image_dir, row['Images'])\n    images.append(load_and_process_image(image_path))\n    \n\n# Convert lists to numpy arrays\nX_test = np.array(images)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T11:37:53.928717Z","iopub.execute_input":"2024-12-20T11:37:53.929573Z","iopub.status.idle":"2024-12-20T11:39:26.881290Z","shell.execute_reply.started":"2024-12-20T11:37:53.929534Z","shell.execute_reply":"2024-12-20T11:39:26.880232Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(f\"Test data: {X_test.shape}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T11:45:42.486800Z","iopub.execute_input":"2024-12-20T11:45:42.487219Z","iopub.status.idle":"2024-12-20T11:45:42.492877Z","shell.execute_reply.started":"2024-12-20T11:45:42.487181Z","shell.execute_reply":"2024-12-20T11:45:42.491745Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Predicting on our test set\n\n#predictions=new_model.predict(X_test)\n#predicted_classes =  np.where(y_pred > 0.5, 1, 0)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T11:57:09.598396Z","iopub.execute_input":"2024-12-20T11:57:09.598773Z","iopub.status.idle":"2024-12-20T11:57:11.303596Z","shell.execute_reply.started":"2024-12-20T11:57:09.598740Z","shell.execute_reply":"2024-12-20T11:57:11.302526Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Predict on test set\npredictions = new_model.predict(X_test)\nprint(f\"Shape of predictions: {predictions.shape}\")\n\n# Check if binary or multi-class classification\nif predictions.shape[1] == 1:  # Binary classification\n    predicted_classes = (predictions > 0.5).astype(int).flatten()\nelse:\n    raise ValueError(\"Unexpected shape for predictions.\")\n    \nprint(f\"Shape of predicted_classes: {predicted_classes.shape}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T12:14:31.448009Z","iopub.execute_input":"2024-12-20T12:14:31.448748Z","iopub.status.idle":"2024-12-20T12:14:33.194154Z","shell.execute_reply.started":"2024-12-20T12:14:31.448713Z","shell.execute_reply":"2024-12-20T12:14:33.193008Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"predictions_rescaled = (predictions * 255).astype(np.uint8)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T11:57:15.060192Z","iopub.execute_input":"2024-12-20T11:57:15.060616Z","iopub.status.idle":"2024-12-20T11:57:15.065131Z","shell.execute_reply.started":"2024-12-20T11:57:15.060580Z","shell.execute_reply":"2024-12-20T11:57:15.064007Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\n\n# Ensure Images column contains identifiers or paths, not arrays\nprint(f\"Type of test_df['Images']: {type(test_df['Images'])}\")\nprint(f\"First 5 entries in test_df['Images']: {test_df['Images'][:5]}\")\n\n# Flatten predicted_classes if necessary\nif isinstance(predicted_classes, np.ndarray):\n    predicted_classes = predicted_classes.flatten().tolist()\n\n# Debugging lengths\nprint(f\"Length of test_df['Images']: {len(test_df['Images'])}\")\nprint(f\"Length of predicted_classes: {len(predicted_classes)}\")\nassert len(test_df['Images']) == len(predicted_classes), \"Lengths do not match!\"\n\n# Create DataFrame\nsubmission_df = pd.DataFrame({\n    'Images': test_df['Images'],\n    'Labels': predicted_classes\n})\n\nprint(submission_df.head())\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T12:14:42.082281Z","iopub.execute_input":"2024-12-20T12:14:42.082920Z","iopub.status.idle":"2024-12-20T12:14:42.092826Z","shell.execute_reply.started":"2024-12-20T12:14:42.082884Z","shell.execute_reply":"2024-12-20T12:14:42.091698Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Creating the submission file\nsubmission_df.to_csv('submission.csv', index=False)\nprint('Submission file was created.')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T12:14:58.057392Z","iopub.execute_input":"2024-12-20T12:14:58.057729Z","iopub.status.idle":"2024-12-20T12:14:58.065882Z","shell.execute_reply.started":"2024-12-20T12:14:58.057702Z","shell.execute_reply":"2024-12-20T12:14:58.065124Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Neural Network Decision Making using LIME","metadata":{}},{"cell_type":"code","source":"!pip install lime","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T12:40:51.613254Z","iopub.execute_input":"2024-12-20T12:40:51.613700Z","iopub.status.idle":"2024-12-20T12:41:00.625451Z","shell.execute_reply.started":"2024-12-20T12:40:51.613663Z","shell.execute_reply":"2024-12-20T12:41:00.624387Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# importing lime packages\n\nfrom lime import lime_image\nfrom skimage.segmentation import mark_boundaries\nfrom skimage.color import gray2rgb","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T12:41:39.881025Z","iopub.execute_input":"2024-12-20T12:41:39.881456Z","iopub.status.idle":"2024-12-20T12:41:40.176634Z","shell.execute_reply.started":"2024-12-20T12:41:39.881418Z","shell.execute_reply":"2024-12-20T12:41:40.175583Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# defining our function\n\ndef predict_fn(images):\n    processed_images=images/255.0\n    return new_model.predict(processed_images)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T12:42:40.446530Z","iopub.execute_input":"2024-12-20T12:42:40.448131Z","iopub.status.idle":"2024-12-20T12:42:40.452969Z","shell.execute_reply.started":"2024-12-20T12:42:40.448090Z","shell.execute_reply":"2024-12-20T12:42:40.452016Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# create the explainer\n\nexplainer=lime_image.LimeImageExplainer()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T12:43:08.565127Z","iopub.execute_input":"2024-12-20T12:43:08.565535Z","iopub.status.idle":"2024-12-20T12:43:08.570107Z","shell.execute_reply.started":"2024-12-20T12:43:08.565503Z","shell.execute_reply":"2024-12-20T12:43:08.569091Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_image=X_test[0]\n\nprint(test_image.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T12:47:14.554835Z","iopub.execute_input":"2024-12-20T12:47:14.555243Z","iopub.status.idle":"2024-12-20T12:47:14.560726Z","shell.execute_reply.started":"2024-12-20T12:47:14.555204Z","shell.execute_reply":"2024-12-20T12:47:14.559635Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Testing LIME on a single image\n\ntest_image=X_test[0]\n\n# Explaining the prediction\n\nexplanation=explainer.explain_instance(\n    image=test_image,\n    classifier_fn=predict_fn,\n    top_labels=3,\n    hide_color=0,\n    num_samples=1000\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T12:47:30.454566Z","iopub.execute_input":"2024-12-20T12:47:30.455216Z","iopub.status.idle":"2024-12-20T12:47:43.303214Z","shell.execute_reply.started":"2024-12-20T12:47:30.455167Z","shell.execute_reply":"2024-12-20T12:47:43.301903Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Visualizing the Explanation\n\ntop_label= np.argmax(predict_fn(np.expand_dims(test_image, axis=0))[0])\n\n# Get the mask\n\ntemp, mask = explanation.get_image_and_mask(\n    label=top_label,\n    positive_only=True,\n    num_features=5,\n    hide_rest=True\n)\n\n# Plot the mask\n\nplt.figure(figsize=(10,10))\nplt.imshow(mark_boundaries(test_image,mask))\nplt.title(f\"LIME Explanation {top_label}\")\nplt.axis('off')\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T12:51:34.822866Z","iopub.execute_input":"2024-12-20T12:51:34.823682Z","iopub.status.idle":"2024-12-20T12:51:35.141212Z","shell.execute_reply.started":"2024-12-20T12:51:34.823643Z","shell.execute_reply":"2024-12-20T12:51:35.140245Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Iterating through images using LIME\n\nfor i in range(10):\n    test_image=X_test[i]\n    explanation=explainer.explain_instance(\n        image=test_image,\n        classifier_fn=predict_fn,\n        top_labels=3,\n        hide_color=0,\n        num_samples=1000\n    )\n\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T12:53:42.944819Z","iopub.execute_input":"2024-12-20T12:53:42.945539Z","iopub.status.idle":"2024-12-20T12:55:28.326778Z","shell.execute_reply.started":"2024-12-20T12:53:42.945499Z","shell.execute_reply":"2024-12-20T12:55:28.325898Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Visualizing the Explanation\n\ndef plot_explanations(images, labels, model, num_images=5):\n    explainer = lime_image.LimeImageExplainer()\n\n    # Select the number of images to explain\n    num_images = min(num_images, len(images))\n    plt.figure(figsize=(15, num_images * 5))\n\n    for i in range(num_images):\n        test_image = X_test[i]\n\n        # Predict the label for the current image\n        predicted_label = np.argmax(model.predict(np.expand_dims(test_image, axis=0))[0])\n\n        # Generate LIME explanation\n        explanation = explainer.explain_instance(\n            image=test_image,\n            classifier_fn=lambda x: model.predict(x),\n            top_labels=1,\n            hide_color=0,\n            num_samples=1000\n        )\n\n        # Get explanation mask\n        temp, mask = explanation.get_image_and_mask(\n            label=predicted_label,\n            positive_only=True,\n            num_features=5,\n            hide_rest=False\n        )\n\n        # Display the explanation\n        plt.subplot(num_images, 1, i + 1)\n        plt.imshow(mark_boundaries(test_image, mask))\n        plt.title(f\"Image {i + 1} - Predicted Label: {predicted_label}\")\n        plt.axis(\"off\")\n\n    plt.tight_layout()\n    plt.show()\n\n# Call the function with your test dataset and model\nplot_explanations(X_test, predicted_classes, new_model, num_images=5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T13:02:03.285507Z","iopub.execute_input":"2024-12-20T13:02:03.285876Z","iopub.status.idle":"2024-12-20T13:02:56.000113Z","shell.execute_reply.started":"2024-12-20T13:02:03.285844Z","shell.execute_reply":"2024-12-20T13:02:55.999127Z"}},"outputs":[],"execution_count":null}]}