{"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":"none","dataSources":[{"sourceId":4104,"databundleVersionId":46661,"sourceType":"competition"},{"sourceId":265751,"sourceType":"datasetVersion","datasetId":110097}],"dockerImageVersionId":30732,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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","execution":{"iopub.status.busy":"2024-06-16T17:15:43.279469Z","iopub.execute_input":"2024-06-16T17:15:43.279861Z","iopub.status.idle":"2024-06-16T17:15:43.288718Z","shell.execute_reply.started":"2024-06-16T17:15:43.279831Z","shell.execute_reply":"2024-06-16T17:15:43.287325Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n# from keras.preprocessing.image import img_to_array\n# from keras.preprocessing.image import array_to_img\n# from sklearn.model_selection import train_test_split\n# from PIL import Image\n# import scipy\n\nimport tensorflow as tf\nfrom tensorflow.keras.applications import *\nfrom tensorflow.keras.optimizers import *\nfrom tensorflow.keras.losses import *\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.models import *\nfrom tensorflow.keras.callbacks import *\nfrom tensorflow.keras.preprocessing.image import *\nfrom tensorflow.keras.utils import *\n# import pydot\nfrom sklearn.metrics import *\nfrom sklearn.model_selection import *\nimport tensorflow.keras.backend as K\n\n# from tqdm import tqdm, tqdm_notebook\n# from colorama import Fore\n# import json\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom glob import glob\nfrom skimage.io import *\n%config Completer.use_jedi = False\n# import time\n# from sklearn.decomposition import PCA\n# from sklearn.svm import LinearSVC\n# from sklearn.linear_model import LogisticRegression\n# from sklearn.metrics import accuracy_score\n# import lightgbm as lgb\n# import xgboost as xgb\n# !pip install livelossplot\n# import livelossplot\n# from livelossplot import PlotLossesKeras\nimport warnings\nwarnings.filterwarnings('ignore')\nprint(\"All modules have been imported\")","metadata":{"execution":{"iopub.status.busy":"2024-06-16T17:15:45.624601Z","iopub.execute_input":"2024-06-16T17:15:45.624981Z","iopub.status.idle":"2024-06-16T17:15:45.639681Z","shell.execute_reply.started":"2024-06-16T17:15:45.624951Z","shell.execute_reply":"2024-06-16T17:15:45.638511Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import itertools\ndef plot_confusion_matrix(cm, classes,\n                          normalize=False,\n                          title='Confusion matrix',\n                          cmap=plt.cm.Blues):\n    \"\"\"\n    This function prints and plots the confusion matrix.\n    Normalization can be applied by setting `normalize=True`.\n    \"\"\"\n    plt.figure(figsize = (6,6))\n    plt.imshow(cm, interpolation='nearest', cmap=cmap)\n    plt.title(title)\n    plt.colorbar()\n    tick_marks = np.arange(len(classes))\n    plt.xticks(tick_marks, classes, rotation=90)\n    plt.yticks(tick_marks, classes)\n    if normalize:\n        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n\n    thresh = cm.max() / 2.\n    cm = np.round(cm,2)\n    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n        plt.text(j, i, cm[i, j],\n                 horizontalalignment=\"center\",\n                 color=\"white\" if cm[i, j] > thresh else \"black\")\n    plt.tight_layout()\n    plt.ylabel('True label')\n    plt.xlabel('Predicted label')\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-16T17:14:00.947302Z","iopub.execute_input":"2024-06-16T17:14:00.947710Z","iopub.status.idle":"2024-06-16T17:14:00.957404Z","shell.execute_reply.started":"2024-06-16T17:14:00.947680Z","shell.execute_reply":"2024-06-16T17:14:00.956248Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Loading data\ninfo = pd.read_csv(\"../input/prepossessed-arrays-of-binary-data/1000_Binary Dataframe\")\ninfo = info.drop('Unnamed: 0', axis=1)\nBinary_90 = np.load('../input/prepossessed-arrays-of-binary-data/1000_Binary_images_data_90.npz')\nX_90 = Binary_90['a']\nBinary_128 = np.load('../input/prepossessed-arrays-of-binary-data/1000_Binary_images_data_128.npz')\nX_128 = Binary_128['a']\nBinary_264 = np.load('../input/prepossessed-arrays-of-binary-data/1000_Binary_images_data_264.npz')\nX_264 = Binary_264['a']\ny = info['level'].values","metadata":{"execution":{"iopub.status.busy":"2024-06-16T17:47:04.836964Z","iopub.execute_input":"2024-06-16T17:47:04.837666Z","iopub.status.idle":"2024-06-16T17:47:16.854683Z","shell.execute_reply.started":"2024-06-16T17:47:04.837629Z","shell.execute_reply":"2024-06-16T17:47:16.852933Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Reshape images\nX_90 = X_90.reshape(1000, 90, 90, 3)\nX_128 = X_128.reshape(1000, 128, 128, 3)\nX_264 = X_264.reshape(1000, 264, 264, 3)","metadata":{"execution":{"iopub.status.busy":"2024-06-16T17:47:18.996380Z","iopub.execute_input":"2024-06-16T17:47:18.996807Z","iopub.status.idle":"2024-06-16T17:47:19.003759Z","shell.execute_reply.started":"2024-06-16T17:47:18.996772Z","shell.execute_reply":"2024-06-16T17:47:19.002383Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Display images\nplt.title(\"90*90*3 Image\")\nplt.imshow(X_90[1])\nplt.show()\n\nplt.title(\"128*128*3 Image\")\nplt.imshow(X_128[1])\nplt.show()\n\nplt.title(\"264*264*3 Image\")\nplt.imshow(X_264[1])\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-16T17:47:30.364601Z","iopub.execute_input":"2024-06-16T17:47:30.365472Z","iopub.status.idle":"2024-06-16T17:47:31.212957Z","shell.execute_reply.started":"2024-06-16T17:47:30.365434Z","shell.execute_reply":"2024-06-16T17:47:31.211784Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# Prepare data for training\nX = np.array(X_264)\nY = np.array(y)\nY = to_categorical(Y, 5)\nx_train, x_test1, y_train, y_test1 = train_test_split(X, Y, test_size=0.4, random_state=42)\nx_val, x_test, y_val, y_test = train_test_split(x_test1, y_test1, test_size=0.5, random_state=42)\nprint(len(x_train), len(x_val), len(x_test))","metadata":{"execution":{"iopub.status.busy":"2024-06-16T17:47:50.314709Z","iopub.execute_input":"2024-06-16T17:47:50.315101Z","iopub.status.idle":"2024-06-16T17:47:51.739232Z","shell.execute_reply.started":"2024-06-16T17:47:50.315070Z","shell.execute_reply":"2024-06-16T17:47:51.738008Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Data augmentation\ntrain_datagen = ImageDataGenerator(\n    rescale=1./255,\n    rotation_range=20,\n    zoom_range=0.15,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    shear_range=0.15,\n    horizontal_flip=True,\n    fill_mode=\"nearest\"\n)\n\nval_datagen = ImageDataGenerator(rescale=1./255)","metadata":{"execution":{"iopub.status.busy":"2024-06-16T17:48:07.260768Z","iopub.execute_input":"2024-06-16T17:48:07.261150Z","iopub.status.idle":"2024-06-16T17:48:07.266707Z","shell.execute_reply.started":"2024-06-16T17:48:07.261121Z","shell.execute_reply":"2024-06-16T17:48:07.265642Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Callbacks\nc3 = ReduceLROnPlateau(\n    monitor=\"val_loss\",\n    factor=0.1,\n    patience=2,\n    mode=\"auto\",\n    min_delta=0.0001,\n    cooldown=0,\n    min_lr=0.001\n)\n\nearly_stopping = EarlyStopping(\n    monitor='val_loss',\n    patience=5,\n    restore_best_weights=True\n)","metadata":{"execution":{"iopub.status.busy":"2024-06-16T17:48:20.478472Z","iopub.execute_input":"2024-06-16T17:48:20.478871Z","iopub.status.idle":"2024-06-16T17:48:20.487636Z","shell.execute_reply.started":"2024-06-16T17:48:20.478840Z","shell.execute_reply":"2024-06-16T17:48:20.486519Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Model with transfer learning (VGG16)\nbase_model = VGG16(weights='imagenet', include_top=False, input_shape=(264, 264, 3))\n\nfor layer in base_model.layers:\n    layer.trainable = False\n\nmodel = Sequential([\n    base_model,\n    Flatten(),\n    Dense(512, activation='relu'),\n    Dropout(0.5),\n    Dense(5, activation='softmax')\n])\n","metadata":{"execution":{"iopub.status.busy":"2024-06-16T17:48:46.345452Z","iopub.execute_input":"2024-06-16T17:48:46.345840Z","iopub.status.idle":"2024-06-16T17:48:50.164377Z","shell.execute_reply.started":"2024-06-16T17:48:46.345812Z","shell.execute_reply":"2024-06-16T17:48:50.163473Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Compile the model with the Adam optimizer, categorical cross-entropy loss, and metrics for accuracy and AUC\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy', 'AUC'])\n\n# Training the model with fewer epochs (e.g., 20), smaller batch size (e.g., 8), and callbacks for early stopping and learning rate reduction\nhistory = model.fit(\n    train_datagen.flow(x_train, y_train, batch_size=8),\n    validation_data=val_datagen.flow(x_val, y_val),\n    epochs=20,\n    callbacks=[ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=2, min_lr=0.00001), \n               EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)]\n)\n\n# Evaluate the model on the test data\nevaluation = model.evaluate(x_test, y_test)\nprint(f'Test Accuracy: {evaluation[1]*100:.2f}%')","metadata":{"execution":{"iopub.status.busy":"2024-06-16T17:52:37.742769Z","iopub.execute_input":"2024-06-16T17:52:37.743160Z","iopub.status.idle":"2024-06-16T18:12:34.921462Z","shell.execute_reply.started":"2024-06-16T17:52:37.743127Z","shell.execute_reply":"2024-06-16T18:12:34.920377Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_test=np.argmax(y_test, axis=1)\npred=np.argmax(model.predict(x_test),axis=-1)","metadata":{"execution":{"iopub.status.busy":"2024-06-16T18:14:24.297965Z","iopub.execute_input":"2024-06-16T18:14:24.298422Z","iopub.status.idle":"2024-06-16T18:15:32.241175Z","shell.execute_reply.started":"2024-06-16T18:14:24.298389Z","shell.execute_reply":"2024-06-16T18:15:32.239454Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Performance Report:\")\ny_pred6=np.argmax(model.predict(x_test),axis=-1)\nY_test=to_categorical(y_test,5)\ny_pred_prb6=model.predict(x_test)\ntarget=['0','1']\nfrom sklearn import metrics\nprint('Accuracy score is :', metrics.accuracy_score(y_test, y_pred6))\nprint('Precision score is :', metrics.precision_score(y_test, y_pred6, average='weighted'))\nprint('Recall score is :',metrics.recall_score(y_test,y_pred6, average='weighted'))\nprint('F1 Score is :', metrics.f1_score(y_test, y_pred6,average='weighted'))\nprint('Cohen Kappa Score:', metrics.cohen_kappa_score(y_test, y_pred6))\nprint('\\t\\tClassification Report:\\n', metrics.classification_report(y_test,pred,target_names=target))","metadata":{"execution":{"iopub.status.busy":"2024-06-16T18:23:21.265931Z","iopub.execute_input":"2024-06-16T18:23:21.266633Z","iopub.status.idle":"2024-06-16T18:25:50.996616Z","shell.execute_reply.started":"2024-06-16T18:23:21.266585Z","shell.execute_reply":"2024-06-16T18:25:50.995469Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Extracting the metrics using correct keys\nauc = history.history['AUC']\nval_auc = history.history['val_AUC']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\n# Plotting the metrics\nepochs = range(len(auc))\nplt.figure(figsize=(18, 4.8))\n\n# Plotting Training and Validation AUC\nplt.subplot(1, 3, 1)\nplt.plot(epochs, auc, 'r', label='Training AUC')\nplt.plot(epochs, val_auc, 'b', label='Validation AUC')\nplt.ylim(0, 1)\nplt.title('Training and Validation AUC')\nplt.legend(loc=0)\n\n# Plotting Training and Validation Loss\nplt.subplot(1, 3, 2)\nplt.plot(epochs, loss, 'y-.', label='Training Loss')\nplt.plot(epochs, val_loss, 'g-.', label='Validation Loss')\nplt.title('Training and Validation Loss')\nplt.ylim(0, 2)\nplt.legend(loc=0)\n\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-06-16T18:39:20.615649Z","iopub.execute_input":"2024-06-16T18:39:20.616763Z","iopub.status.idle":"2024-06-16T18:39:21.110635Z","shell.execute_reply.started":"2024-06-16T18:39:20.616709Z","shell.execute_reply":"2024-06-16T18:39:21.109469Z"},"trusted":true},"execution_count":null,"outputs":[]}]}