{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.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":13836,"databundleVersionId":1718836,"sourceType":"competition"}],"dockerImageVersionId":31089,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# import numpy as np\n# import pandas as pd\n# import os\n# import matplotlib.pyplot as plt\n# import seaborn as sns\n# import tensorflow as tf\n# from sklearn.model_selection import train_test_split\n# from tensorflow.keras.preprocessing.image import ImageDataGenerator\n# from tensorflow.keras.applications import MobileNetV2, EfficientNetB0, ResNet50, InceptionV3\n# from tensorflow.keras.models import Model\n# from tensorflow.keras.layers import Input, GlobalAveragePooling2D, Dropout, Dense\n# from tensorflow.keras.optimizers import Adam\n\n# # 1. Load CSV\n# df = pd.read_csv('/kaggle/input/cassava-leaf-disease-classification/train.csv')\n\n# # Map numeric labels to string class names\n# label_map = {\n#     0: 'CBB', 1: 'CBSD', 2: 'CGM', 3: 'CMD', 4: 'Healthy'\n# }\n# df['label_name'] = df['label'].map(label_map)\n\n# # Plot distribution\n# plt.figure(figsize=(7,4))\n# sns.countplot(x='label_name', data=df)\n# plt.title('Class Distribution')\n# plt.xticks(rotation=30)\n# plt.show()\n\n# # Add full image paths\n# df['image_path'] = df['image_id'].apply(\n#     lambda x: os.path.join('/kaggle/input/cassava-leaf-disease-classification/train_images', x)\n# )\n\n# # Train-validation split\n# train_df, val_df = train_test_split(df,\n#                                     test_size=0.2,\n#                                     stratify=df['label_name'],\n#                                     random_state=42)\n\n# # 2. Image generators\n# IMG_SIZE = (224,224)\n# train_datagen = ImageDataGenerator(rescale=1./255,\n#                                    rotation_range=20,\n#                                    zoom_range=0.2,\n#                                    horizontal_flip=True)\n# val_datagen = ImageDataGenerator(rescale=1./255)\n\n# train_gen = train_datagen.flow_from_dataframe(\n#     train_df,\n#     x_col='image_path',\n#     y_col='label_name',\n#     target_size=IMG_SIZE,\n#     class_mode='categorical',\n#     batch_size=32\n# )\n\n# val_gen = val_datagen.flow_from_dataframe(\n#     val_df,\n#     x_col='image_path',\n#     y_col='label_name',\n#     target_size=IMG_SIZE,\n#     class_mode='categorical',\n#     batch_size=32\n# )\n\n# # 3. Model builder\n# def build_model(base_cls, name):\n#     base = base_cls(include_top=False, input_shape=(224,224,3), weights='imagenet')\n#     base.trainable = False\n#     inp = Input(shape=(224,224,3))\n#     x = base(inp, training=False)\n#     x = GlobalAveragePooling2D()(x)\n#     x = Dropout(0.3)(x)\n#     out = Dense(5, activation='softmax')(x)\n#     model = Model(inputs=inp, outputs=out, name=name)\n#     model.compile(optimizer=Adam(), loss='categorical_crossentropy', metrics=['accuracy'])\n#     return model\n\n# # 4. Build & train models\n# models = {\n#     'MobileNetV2': MobileNetV2,\n#     'EfficientNetB0': EfficientNetB0,\n#     'ResNet50': ResNet50,\n#     'InceptionV3': InceptionV3\n# }\n# histories = {}\n\n# for model_name, cls in models.items():\n#     print(f\"Training {model_name}...\")\n#     model = build_model(cls, model_name)\n#     history = model.fit(\n#         train_gen,\n#         validation_data=val_gen,\n#         epochs=5,\n#         verbose=1\n#     )\n#     histories[model_name] = history\n\n# # 5. Plot comparison of validation accuracy\n# plt.figure(figsize=(10,6))\n# for name, hist in histories.items():\n#     plt.plot(hist.history['val_accuracy'], label=name)\n# plt.title(\"Validation Accuracy Comparison\")\n# plt.xlabel(\"Epochs\")\n# plt.ylabel(\"Accuracy\")\n# plt.legend()\n# plt.grid(True)\n# plt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-26T20:33:01.02407Z","iopub.execute_input":"2025-08-26T20:33:01.024648Z","iopub.status.idle":"2025-08-26T20:33:02.054742Z","shell.execute_reply.started":"2025-08-26T20:33:01.024619Z","shell.execute_reply":"2025-08-26T20:33:02.053646Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# import matplotlib.pyplot as plt\n\n# # Replace these with your actual model history objects\n# histories = {\n#     'MobileNetV2': history_mobilenet,\n#     'EfficientNetB0': history_efficientnet,\n#     'ResNet50': history_resnet,\n#     'InceptionV3': history_inception\n# }\n\n# # Plot Validation Accuracy\n# plt.figure(figsize=(10, 6))\n# for name, hist in histories.items():\n#     plt.plot(hist.history['val_accuracy'], label=name)\n# plt.title('Validation Accuracy Comparison')\n# plt.xlabel('Epochs')\n# plt.ylabel('Accuracy')\n# plt.legend()\n# plt.grid(True)\n# plt.show()\n\n# # Plot Validation Loss\n# plt.figure(figsize=(10, 6))\n# for name, hist in histories.items():\n#     plt.plot(hist.history['val_loss'], label=name)\n# plt.title('Validation Loss Comparison')\n# plt.xlabel('Epochs')\n# plt.ylabel('Loss')\n# plt.legend()\n# plt.grid(True)\n# plt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-26T20:33:00.00576Z","iopub.status.idle":"2025-08-26T20:33:00.006024Z","shell.execute_reply.started":"2025-08-26T20:33:00.005903Z","shell.execute_reply":"2025-08-26T20:33:00.005914Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# # Example: Best Model is EfficientNetB0\n# best_model = history_efficientnet\n\n# plt.figure(figsize=(14, 5))\n\n# # Accuracy\n# plt.subplot(1, 2, 1)\n# plt.plot(best_model.history['accuracy'], label='Train Accuracy')\n# plt.plot(best_model.history['val_accuracy'], label='Val Accuracy')\n# plt.title('EfficientNetB0 Accuracy')\n# plt.xlabel('Epochs')\n# plt.ylabel('Accuracy')\n# plt.legend()\n# plt.grid(True)\n\n# # Loss\n# plt.subplot(1, 2, 2)\n# plt.plot(best_model.history['loss'], label='Train Loss')\n# plt.plot(best_model.history['val_loss'], label='Val Loss')\n# plt.title('EfficientNetB0 Loss')\n# plt.xlabel('Epochs')\n# plt.ylabel('Loss')\n# plt.legend()\n# plt.grid(True)\n\n# plt.tight_layout()\n# plt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-26T20:33:00.006786Z","iopub.status.idle":"2025-08-26T20:33:00.00702Z","shell.execute_reply.started":"2025-08-26T20:33:00.006902Z","shell.execute_reply":"2025-08-26T20:33:00.006911Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications import MobileNetV2, EfficientNetB0, ResNet50, InceptionV3\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input, GlobalAveragePooling2D, Dropout, Dense\nfrom tensorflow.keras.optimizers import Adam\nimport warnings\nwarnings.filterwarnings('ignore')\n# 1. Load CSV\ndf = pd.read_csv('/kaggle/input/cassava-leaf-disease-classification/train.csv')\n\n# Map numeric labels to string class names\nlabel_map = {\n    0: 'CBB', 1: 'CBSD', 2: 'CGM', 3: 'CMD', 4: 'Healthy'\n}\ndf['label_name'] = df['label'].map(label_map)\n\n# Plot distribution\nplt.figure(figsize=(7,4))\nsns.countplot(x='label_name', data=df)\nplt.title('Class Distribution')\nplt.xticks(rotation=30)\nplt.show()\n\n# Add full image paths\ndf['image_path'] = df['image_id'].apply(\n    lambda x: os.path.join('/kaggle/input/cassava-leaf-disease-classification/train_images', x)\n)\n\n# Train-validation split\ntrain_df, val_df = train_test_split(df,\n                                    test_size=0.2,\n                                    stratify=df['label_name'],\n                                    random_state=42)\n\n# 2. Image generators\nIMG_SIZE = (224,224)\nBATCH_SIZE = 32\n\ntrain_datagen = ImageDataGenerator(rescale=1./255,\n                                   rotation_range=20,\n                                   zoom_range=0.2,\n                                   horizontal_flip=True)\nval_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_gen = train_datagen.flow_from_dataframe(\n    train_df,\n    x_col='image_path',\n    y_col='label_name',\n    target_size=IMG_SIZE,\n    class_mode='categorical',\n    batch_size=BATCH_SIZE,\n    shuffle=True\n)\n\nval_gen = val_datagen.flow_from_dataframe(\n    val_df,\n    x_col='image_path',\n    y_col='label_name',\n    target_size=IMG_SIZE,\n    class_mode='categorical',\n    batch_size=BATCH_SIZE,\n    shuffle=False\n)\n\n# 3. Model builder\ndef build_model(base_cls, name):\n    base = base_cls(include_top=False, input_shape=(224,224,3), weights='imagenet')\n    base.trainable = False\n    inp = Input(shape=(224,224,3))\n    x = base(inp, training=False)\n    x = GlobalAveragePooling2D()(x)\n    x = Dropout(0.3)(x)\n    out = Dense(5, activation='softmax')(x)\n    model = Model(inputs=inp, outputs=out, name=name)\n    model.compile(optimizer=Adam(), loss='categorical_crossentropy', metrics=['accuracy'])\n    return model\n\n# 4. Build & train models\nmodels = {\n    'MobileNetV2': MobileNetV2,\n    'EfficientNetB0': EfficientNetB0,\n    'ResNet50': ResNet50,\n    'InceptionV3': InceptionV3\n}\nhistories = {}\n\nfor model_name, cls in models.items():\n    print(f\"Training {model_name}...\")\n    model = build_model(cls, model_name)\n    history = model.fit(\n        train_gen,\n        validation_data=val_gen,\n        epochs=5,\n        verbose=1\n    )\n    histories[model_name] = history\n\n# 5. Plot comparison of validation accuracy and loss\n\nplt.figure(figsize=(10,6))\nfor name, hist in histories.items():\n    plt.plot(hist.history['val_accuracy'], label=name)\nplt.title(\"Validation Accuracy Comparison\")\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Accuracy\")\nplt.legend()\nplt.grid(True)\nplt.show()\n\nplt.figure(figsize=(10,6))\nfor name, hist in histories.items():\n    plt.plot(hist.history['val_loss'], label=name)\nplt.title('Validation Loss Comparison')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\nplt.grid(True)\nplt.show()\n\n# Example: Best Model is EfficientNetB0 (change if another is best)\nbest_model_history = histories['EfficientNetB0']\n\nplt.figure(figsize=(14, 5))\n\n# Accuracy\nplt.subplot(1, 2, 1)\nplt.plot(best_model_history.history['accuracy'], label='Train Accuracy')\nplt.plot(best_model_history.history['val_accuracy'], label='Val Accuracy')\nplt.title('EfficientNetB0 Accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend()\nplt.grid(True)\n\n# Loss\nplt.subplot(1, 2, 2)\nplt.plot(best_model_history.history['loss'], label='Train Loss')\nplt.plot(best_model_history.history['val_loss'], label='Val Loss')\nplt.title('EfficientNetB0 Loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\nplt.grid(True)\n\nplt.tight_layout()\nplt.show()\n\nfrom sklearn.metrics import mean_squared_error, r2_score\nimport numpy as np\n\n# We'll use val_gen to get the validation set\n# Get the true labels and predictions for the entire validation set\ndef get_val_labels_and_preds(model, val_gen):\n    # Get all true labels (one-hot) and predictions\n    y_true = []\n    y_pred = []\n    for i in range(len(val_gen)):\n        x_batch, y_batch = val_gen[i]\n        preds = model.predict(x_batch)\n        y_true.append(y_batch)\n        y_pred.append(preds)\n    y_true = np.concatenate(y_true)\n    y_pred = np.concatenate(y_pred)\n    return y_true, y_pred\n\nresults = []\nfor model_name, cls in models.items():\n    print(f\"Evaluating {model_name}...\")\n    model = build_model(cls, model_name)\n    # Load trained weights if you saved them, or use the model immediately after training\n    history = histories[model_name]\n    # Use the trained model (make sure it is trained and not rebuilt here!)\n    # If you have your trained model objects, use them instead of building a new one\n    \n    # If you trained and deleted models, use model.load_weights() if you saved them\n\n    # Here, assuming you have each model object after training:\n    # e.g. model = trained_models[model_name]\n    # For the example, let's suppose you have a dict trained_models\n    model = trained_models[model_name]\n    \n    y_true, y_pred = get_val_labels_and_preds(model, val_gen)\n    # Convert from one-hot to class indices\n    y_true_idx = np.argmax(y_true, axis=1)\n    y_pred_idx = np.argmax(y_pred, axis=1)\n    \n    accuracy = np.mean(y_true_idx == y_pred_idx)\n    mse = mean_squared_error(y_true, y_pred)\n    r2 = r2_score(y_true, y_pred)\n    \n    results.append({\n        \"Model\": model_name,\n        \"Accuracy\": f\"{accuracy*100:.2f}%\",\n        \"MSE\": f\"{mse:.4f}\",\n        \"R2 Score\": f\"{r2:.2f}\"\n    })\n\n# Print results as a table\nprint(f\"|    Model         | Accuracy |   MSE   | R2 Score |\")\nprint(f\"|------------------|----------|---------|----------|\")\nfor r in results:\n    print(f\"| {r['Model']:15} | {r['Accuracy']:8} | {r['MSE']:7} | {r['R2 Score']:8} |\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-26T20:40:12.204729Z","iopub.execute_input":"2025-08-26T20:40:12.20504Z","iopub.status.idle":"2025-08-26T22:10:17.503728Z","shell.execute_reply.started":"2025-08-26T20:40:12.205018Z","shell.execute_reply":"2025-08-26T22:10:17.502346Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}