{"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":"gpu","dataSources":[{"sourceId":1799839,"sourceType":"datasetVersion","datasetId":1069682},{"sourceId":2057341,"sourceType":"datasetVersion","datasetId":1232864},{"sourceId":8785422,"sourceType":"datasetVersion","datasetId":5281464}],"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# 1. ***Libraries Installation & Importing*** ","metadata":{}},{"cell_type":"code","source":"# Install necessary libraries\n!pip install --upgrade pip\n!pip install --upgrade ultralytics\n!pip install torchxrayvision  # X-ray vision models\n!pip install pydicom Pillow  # Medical image processing\n!pip install scikit-image  # Image processing\n!pip install tqdm --upgrade  # Progress bars\n!pip install ipywidgets --upgrade  # Jupyter widgets\n!pip install torch-xla  # PyTorch TPU support\n!pip install scikit-learn","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ✅ Standard libraries\nimport os\nimport shutil\nimport zipfile\nimport gc\nimport pprint\n\n# ✅ Scientific computing\nimport numpy as np\nimport pandas as pd\nimport yaml\nimport pydicom\nimport torch\nimport torchvision\nimport torchvision.transforms as T\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader, Dataset\nfrom glob import glob\n\n# ✅ Visualization\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom PIL import Image\nfrom IPython.display import display, FileLink\nimport random\nimport cv2\n\n# ✅ Data handling\nfrom tqdm.autonotebook import tqdm\nfrom concurrent.futures import ThreadPoolExecutor\nimport collections\nimport ast  # To safely convert string representations of lists\n\n# ✅ Machine learning\nfrom sklearn.model_selection import StratifiedGroupKFold\nfrom sklearn.manifold import TSNE\n\n# ✅ Deep learning & YOLO\nimport torchxrayvision as xrv  # X-ray processing\nfrom ultralytics import YOLO  # YOLO object detection\n\n# ✅ Image processing\nimport skimage.io\nimport skimage.transform\nimport albumentations as A  # Advanced augmentation library\n\n# ✅ Warnings\nimport warnings\nwarnings.filterwarnings('ignore')","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 📌 2. Data Preparation, Bounding Box Visualization, and Class Distribution","metadata":{}},{"cell_type":"code","source":"# ✅ Load dataset\nlabel_data_file = \"/kaggle/input/vinbigdata-1024-image-dataset/vinbigdata/train.csv\"\ntrain_df = pd.read_csv(label_data_file)\n\n# ✅ Add image_path column\ntrain_df['image_path'] = '/kaggle/input/vinbigdata-1024-image-dataset/vinbigdata/train/' + train_df.image_id + '.png'\n\n# ✅ Remove class 14 (No Finding) and class 2 (Calcification) completely\ntrain_df = train_df[~train_df.class_id.isin([14, 2])].reset_index(drop=True)\n\n# ✅ Print remaining images to confirm\nprint(f\"✅ Number of images remaining: {train_df['image_id'].nunique()}\")\n\n# ✅ Convert VinBigData bbox format to YOLO format\ntrain_df['x_mid'] = (train_df['x_min'] + train_df['x_max']) / (2 * train_df['width'])\ntrain_df['y_mid'] = (train_df['y_min'] + train_df['y_max']) / (2 * train_df['height'])\ntrain_df['w'] = (train_df['x_max'] - train_df['x_min']) / train_df['width']\ntrain_df['h'] = (train_df['y_max'] - train_df['y_min']) / train_df['height']\n\ntrain_df['source_dataset'] = 'vinbig'\n\ntrain_df.head()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ✅ Load the new NIH dataset\nnew_nih_file = \"/kaggle/input/nih-chest-xray-dataset-bbox-for-vinbigdata/nih.csv\"\nnew_nih_df = pd.read_csv(new_nih_file)\n\n# ✅ Add image path for new NIH dataset\nnew_nih_df['image_path'] = '/kaggle/input/nih-chest-xray-dataset-bbox-for-vinbigdata/nih/' + new_nih_df['image_id'] + '.png'\n\n# ✅ Remove rows with unmapped class names (NaN)\nnew_nih_df = new_nih_df.dropna(subset=['class_name'])\n\n# ✅ Define the class_name_to_id mapping\nclass_name_to_id = {\n    \"Aortic enlargement\": 0,\n    \"Cardiomegaly\": 2,  \n    \"Consolidation\": 3,\n    \"ILD\": 4,\n    \"Infiltration\": 5,\n    \"Lung Opacity\": 6,\n    \"Nodule/Mass\": 7,\n    \"Other lesion\": 8,\n    \"Pleural effusion\": 9,\n    \"Pleural thickening\": 10,\n    \"Pneumothorax\": 11,\n    \"Pulmonary fibrosis\": 12,\n    \"Atelectasis\": 1\n}\n\n# ✅ Assign class_id based on class_name\nnew_nih_df[\"class_id\"] = new_nih_df[\"class_name\"].map(class_name_to_id)\n\n# ✅ Calculate actual image width and height\nimage_widths = []\nimage_heights = []\n\nfor path in new_nih_df[\"image_path\"]:\n    image = cv2.imread(path)\n    if image is not None:\n        height, width = image.shape[:2]\n    else:\n        height, width = -1, -1  # Handle missing/corrupted image case\n    image_widths.append(width)\n    image_heights.append(height)\n\n# ✅ Store as 'width' and 'height' (actual image dimensions, not bbox)\nnew_nih_df[\"width\"] = image_widths\nnew_nih_df[\"height\"] = image_heights\n\n# ✅ Convert bbox to YOLO format (1-step calculation + normalization)\nnew_nih_df['x_mid'] = (new_nih_df['x_min'] + new_nih_df['x_max']) / (2 * new_nih_df['width'])\nnew_nih_df['y_mid'] = (new_nih_df['y_min'] + new_nih_df['y_max']) / (2 * new_nih_df['height'])\nnew_nih_df['w'] = (new_nih_df['x_max'] - new_nih_df['x_min']) / new_nih_df['width']\nnew_nih_df['h'] = (new_nih_df['y_max'] - new_nih_df['y_min']) / new_nih_df['height']\n\nnew_nih_df['source_dataset'] = 'nih_for_vin'\n\n# ✅ Select relevant columns (now width/height = image size)\nnew_nih_df = new_nih_df[[\n    'image_id', 'class_name', 'class_id', 'rad_id',\n    'x_mid', 'y_mid', 'w', 'h',\n    'x_min', 'y_min', 'x_max', 'y_max',\n    'width', 'height', 'image_path', 'source_dataset'\n]]\n\n# ✅ Merge with existing train_df\ntrain_df = pd.concat([train_df, new_nih_df], ignore_index=True)\n\n# ✅ Check for NaN class IDs after merging\nprint(f\"Number of NaN class IDs after merge: {train_df['class_id'].isna().sum()}\")  # Should be 0\n\n# ✅ Print final dataset details\nprint(f\"✅ Number of unique images after final merge: {train_df['image_id'].nunique()}\")\ntrain_df.head()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def visualize_bboxes(image_paths, bboxes_list, labels_list, image_sizes, num_images=5):\n    num_images = min(num_images, len(image_paths))  \n    fig, axes = plt.subplots(1, num_images, figsize=(50, 30))\n\n    if num_images == 1:\n        axes = [axes]\n\n    for idx in range(num_images):\n        image_path, bboxes, labels, (orig_width, orig_height) = (\n            image_paths[idx], bboxes_list[idx], labels_list[idx], image_sizes[idx])\n\n        image = cv2.imread(image_path)\n        if image is None:\n            print(f\"⚠️ Error: Could not read {image_path}\")\n            continue\n\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)  \n        height, width, _ = image.shape  \n\n        # ✅ Rescale bounding boxes\n        for i in range(len(bboxes)):\n            x_min, y_min, x_max, y_max = bboxes[i]\n            bboxes[i] = [\n                int((x_min / orig_width) * width),\n                int((y_min / orig_height) * height),\n                int((x_max / orig_width) * width),\n                int((y_max / orig_height) * height),\n            ]\n            cv2.rectangle(image, (bboxes[i][0], bboxes[i][1]), (bboxes[i][2], bboxes[i][3]), (0, 255, 0), 2)\n            cv2.putText(image, labels[i], (bboxes[i][0], bboxes[i][1] - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)\n\n        axes[idx].imshow(image)\n        axes[idx].axis(\"off\")\n\n    plt.show()\n    return bboxes_list  # Return updated bounding boxes","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ✅ Select a random sample of unique images\nnum_samples = 5\nsampled_images = train_df[\"image_id\"].drop_duplicates().sample(n=min(num_samples, train_df[\"image_id\"].nunique())).tolist()\n\n# ✅ Prepare lists for visualization\nimage_paths, bboxes_list, labels_list, image_sizes = [], [], [], []\n\nfor image_id in sampled_images:\n    sample_df = train_df[train_df[\"image_id\"] == image_id]\n    image_path = sample_df[\"image_path\"].iloc[0]\n    print(f\"🔍 Visualizing image: {image_path}\")  # <-- ✅ Print the image path here\n    image_paths.append(image_path)\n    bboxes_list.append(sample_df[[\"x_min\", \"y_min\", \"x_max\", \"y_max\"]].values.tolist())\n    labels_list.append(sample_df[\"class_name\"].tolist())\n    image_sizes.append(sample_df[[\"width\", \"height\"]].iloc[0].tolist())\n\n# ✅ Visualize & Update Bounding Boxes\nbboxes_list_updated = visualize_bboxes(image_paths, bboxes_list, labels_list, image_sizes, num_images=num_samples)\n\n# ✅ Update train_df with new bounding boxes\nfor i, image_id in enumerate(sampled_images):\n    sample_df = train_df[train_df[\"image_id\"] == image_id].copy()\n    updated_bboxes = bboxes_list_updated[i]\n    \n    for j, bbox in enumerate(updated_bboxes):\n        train_df.loc[sample_df.index[j], ['x_min', 'y_min', 'x_max', 'y_max']] = bbox\n\nprint(\"✅ Bounding boxes updated in train_df!\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ✅ Load NIH dataset\nnih_bbox_file = \"/kaggle/input/nih-chest-x-rays-bbox-version/BBox_List_2017.csv\"\nnih_df = pd.read_csv(nih_bbox_file)\n\n# ✅ Add image path\nnih_df['image_path'] = '/kaggle/input/nih-chest-x-rays-bbox-version/bbox_img/' + nih_df['Image Index']\n\n# ✅ Map class names\nnih_class_mapping = {\n    \"Infiltrate\": \"Infiltration\",\n    \"Atelectasis\": \"Atelectasis\",\n    \"Pneumonia\": \"Pneumonia\",\n    \"Cardiomegaly\": \"Cardiomegaly\",\n    \"Effusion\": \"Pleural effusion\",\n    \"Pneumothorax\": \"Pneumothorax\",\n    \"Mass\": \"Nodule/Mass\",\n    \"Nodule\": \"Nodule/Mass\"\n}\nnih_df['class_name'] = nih_df['Finding Label'].map(nih_class_mapping)\nnih_df = nih_df.dropna(subset=['class_name'])\n\n# ✅ Rename bbox columns\nnih_df = nih_df.rename(columns={\n    \"Image Index\": \"image_id\",\n    \"Bbox [x\": \"x_min\",\n    \"y\": \"y_min\",\n    \"w\": \"w\",\n    \"h]\": \"h\"\n})\n\n# ✅ Compute x_max, y_max\nnih_df['x_max'] = nih_df['x_min'] + nih_df['w']\nnih_df['y_max'] = nih_df['y_min'] + nih_df['h']\n\n# ✅ Assume fixed image size if actual dimensions are not available (e.g., 1024x1024)\nnih_df['width'] = 1024\nnih_df['height'] = 1024\n\n# ✅ Compute YOLO format in one step\nnih_df['x_mid'] = (nih_df['x_min'] + nih_df['x_max']) / (2 * nih_df['width'])\nnih_df['y_mid'] = (nih_df['y_min'] + nih_df['y_max']) / (2 * nih_df['height'])\nnih_df['w'] = (nih_df['x_max'] - nih_df['x_min']) / nih_df['width']\nnih_df['h'] = (nih_df['y_max'] - nih_df['y_min']) / nih_df['height']\n\nnih_df['source_dataset'] = 'nih'\n\n# ✅ Final column selection\nnih_df = nih_df[['image_id', 'class_name', 'x_mid', 'y_mid', 'w', 'h', 'x_min', 'y_min', 'x_max', 'y_max', 'width', 'height', 'image_path','source_dataset']]\n\n# ✅ Merge with train_df\ntrain_df = pd.concat([train_df, nih_df], ignore_index=True)\n\n# ✅ Assign class_id\nclass_name_to_id = {\n    \"Aortic enlargement\": 0,\n    \"Cardiomegaly\": 2,  \n    \"Consolidation\": 3,\n    \"ILD\": 4,\n    \"Infiltration\": 5,\n    \"Lung Opacity\": 6,\n    \"Nodule/Mass\": 7,\n    \"Other lesion\": 8,\n    \"Pleural effusion\": 9,\n    \"Pleural thickening\": 10,\n    \"Pneumothorax\": 11,\n    \"Pulmonary fibrosis\": 12,\n    \"Atelectasis\": 1,\n    \"Pneumonia\": 13 \n}\ntrain_df[\"class_id\"] = train_df[\"class_name\"].map(class_name_to_id)\n\n# ✅ Check + summary\nprint(f\"Number of NaN class IDs: {train_df['class_id'].isna().sum()}\")\nprint(f\"✅ Number of unique images after merging: {train_df['image_id'].nunique()}\")\n\ntrain_df.head()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ✅ Group by image_id and get unique classes per image\nunique_class_per_image = train_df.groupby(\"image_id\")[\"class_name\"].unique()\n\n# ✅ Count how many images each class appears in\nclass_counts = unique_class_per_image.explode().value_counts()\n\n# ✅ Map class_name to class_id\nclass_name_to_id = train_df.drop_duplicates(\"class_name\")[[\"class_name\", \"class_id\"]].set_index(\"class_name\")[\"class_id\"].to_dict()\n\n# ✅ Add class_id to the labels\nclass_labels_with_ids = [f\"{cls} (ID {class_name_to_id.get(cls, 'Unknown')})\" for cls in class_counts.index]\n\n# ✅ Sort class counts\nclass_counts = class_counts.sort_values(ascending=False)\nclass_labels_with_ids = [label for _, label in sorted(zip(class_counts.values, class_labels_with_ids), reverse=True)]\n\n# ✅ Create color palette\ncolors = sns.color_palette(\"tab20\", len(class_counts))\n\n# ✅ Plot the class distribution\nplt.figure(figsize=(14, 6))\nbars = plt.bar(class_labels_with_ids, class_counts.values, color=colors)\nplt.title('Class Distribution Across Images (Unique Occurrences)', fontsize=16)\nplt.xlabel('Class Name (with Class ID)', fontsize=12)\nplt.ylabel('Number of Images', fontsize=12)\nplt.xticks(rotation=45, ha='right')\n\n# ✅ Annotate counts on top of bars\nfor i, bar in enumerate(bars):\n    height = bar.get_height()\n    plt.text(bar.get_x() + bar.get_width() / 2, height + 1, str(height), ha='center', va='bottom', fontsize=10)\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 🔄 3. Class Mapping","metadata":{}},{"cell_type":"code","source":"# ✅ Define the class mapping dictionary\nclass_mapping = {\n    0: \"Cardiac & Vascular\", \n    1: \"Lung Collapse\",  \n    2: \"Cardiac & Vascular\",\n    3: \"Lung Opacity\", \n    4: \"Fibrosis & ILD\", \n    5: \"Lung Opacity\",  \n    6: \"Lung Opacity\",  \n    7: \"Nodule/Mass or Other Lesion\", \n    8: \"Nodule/Mass or Other Lesion\",  \n    9: \"Pleural Abnormalities\",\n    10: \"Pleural Abnormalities\",  \n    11: \"Lung Collapse\",  \n    12: \"Fibrosis & ILD\",\n    13: \"Lung Opacity\"\n}\n\n# ✅ Apply class mapping to create `mapped_class_name`\ntrain_df['mapped_class_name'] = train_df['class_id'].map(class_mapping)\n\n# ✅ Debugging: Check for unmapped class IDs\nunmapped_classes = train_df[train_df['mapped_class_name'].isna()]['class_id'].unique()\nif len(unmapped_classes) > 0:\n    print(f\"⚠️ Warning: Some class IDs are not mapped! Unmapped class IDs: {unmapped_classes}\")\n\n# ✅ Remove any NaN values before creating unique class names\ntrain_df = train_df.dropna(subset=['mapped_class_name'])\n\n# ✅ Get unique class names (ensuring correct count)\nclass_names = sorted(train_df['mapped_class_name'].unique())\n\n# ✅ Explicitly map class names to correct indices\nnew_class_ids = {name: idx for idx, name in enumerate(class_names)}\n\n# ✅ Apply the new mapping\ntrain_df['new_class_id'] = train_df['mapped_class_name'].map(new_class_ids)\n\n# ✅ Create the final new class mapping\nnew_class_mapping = {idx: name for name, idx in new_class_ids.items()}\n\n# ✅ Verify the new class mapping\nprint(f\"✅ New class mapping (new class IDs): {new_class_mapping}\")\ntrain_df.head()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ✅ Function to visualize images with bounding boxes and show image path\ndef visualize_bboxes(image_paths, bboxes_list, labels_list, image_sizes, num_images=5):\n    num_images = min(num_images, len(image_paths))  \n    fig, axes = plt.subplots(1, num_images, figsize=(50, 30))\n\n    if num_images == 1:\n        axes = [axes]\n\n    for idx in range(num_images):\n        image_path, bboxes, labels, (orig_width, orig_height) = (\n            image_paths[idx], bboxes_list[idx], labels_list[idx], image_sizes[idx])\n        \n        # ✅ Print image path to console/log\n        print(f\"\\n🖼 Visualizing image {idx + 1}/{num_images}: {image_path}\")\n        \n        image = cv2.imread(image_path)\n        if image is None:\n            print(f\"⚠️ Error: Could not read {image_path}\")\n            continue\n    \n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)  \n        height, width, _ = image.shape  \n    \n        # ✅ Rescale and draw bounding boxes\n        for i in range(len(bboxes)):\n            x_min, y_min, x_max, y_max = bboxes[i]\n            x_min = int((x_min / orig_width) * width)\n            y_min = int((y_min / orig_height) * height)\n            x_max = int((x_max / orig_width) * width)\n            y_max = int((y_max / orig_height) * height)\n            bboxes[i] = [x_min, y_min, x_max, y_max]\n            cv2.rectangle(image, (x_min, y_min), (x_max, y_max), (0, 255, 0), 2)\n            cv2.putText(image, labels[i], (x_min, y_min - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)\n    \n        axes[idx].imshow(image)\n        axes[idx].axis(\"off\")\n        axes[idx].set_title(image_path.split('/')[-1], fontsize=14, color='blue')  # Optional shorter title\n\n    plt.tight_layout()\n    plt.show()\n    return bboxes_list  # Return updated bounding boxes\n\n# ✅ Select a random sample of unique images\nnum_samples = 5\nsampled_images = train_df[\"image_id\"].drop_duplicates().sample(n=min(num_samples, train_df[\"image_id\"].nunique())).tolist()\n\n# ✅ Prepare lists for visualization\nimage_paths, bboxes_list, labels_list, image_sizes = [], [], [], []\n\nfor image_id in sampled_images:\n    sample_df = train_df[train_df[\"image_id\"] == image_id]\n    image_paths.append(sample_df[\"image_path\"].iloc[0])\n    bboxes_list.append(sample_df[[\"x_min\", \"y_min\", \"x_max\", \"y_max\"]].values.tolist())\n    labels_list.append(sample_df[\"mapped_class_name\"].tolist())  # Use mapped class names\n    image_sizes.append(sample_df[[\"width\", \"height\"]].iloc[0].tolist())\n\n# ✅ Visualize and update bounding boxes\nbboxes_list_updated = visualize_bboxes(image_paths, bboxes_list, labels_list, image_sizes, num_images=num_samples)\n\n# ✅ Update train_df with new bounding boxes\nfor i, image_id in enumerate(sampled_images):\n    sample_df = train_df[train_df[\"image_id\"] == image_id].copy()\n    updated_bboxes = bboxes_list_updated[i]\n    \n    for j, bbox in enumerate(updated_bboxes):\n        train_df.loc[sample_df.index[j], ['x_min', 'y_min', 'x_max', 'y_max']] = bbox\n\nprint(\"✅ Bounding boxes updated in train_df!\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ✅ Group by image_id and mapped_class_name, counting unique classes per image\nunique_classes_per_image = train_df.groupby(\"image_id\")[\"mapped_class_name\"].nunique()\n\n# ✅ Count how many images have each unique class (counting each class once per image)\nclass_counts = train_df.groupby(\"mapped_class_name\")[\"image_id\"].nunique()\nclass_counts = class_counts.sort_values(ascending=False)\n\n# ✅ Create a color palette for the plot\ncolors = sns.color_palette(\"Set2\", len(class_counts))\n\n# ✅ Plot the class distribution showing how many images each class appeared in\nplt.figure(figsize=(12, 6))\nclass_counts.plot(kind='bar', color=colors)\nfor i, value in enumerate(class_counts.values):\n    plt.text(i, value + 1, str(value), ha='center', va='bottom', fontsize=10)\nplt.title('Mapped Class Distribution Across Images (Unique Occurrences)', fontsize=16)\nplt.xlabel('Mapped Class Name', fontsize=12)\nplt.ylabel('Number of Images', fontsize=12)\nplt.xticks(rotation=45, ha='right')\nplt.tight_layout()\nplt.show()\n\n# ✅ Display the class distribution\nprint(f\"Mapped class distribution (counting each class once per image):\\n{class_counts}\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ✅ Count how many times each class appears in each image (including duplicates for multiple bboxes)\nclass_occurrences = train_df.groupby([\"image_id\", \"mapped_class_name\"]).size().reset_index(name=\"count\")\n\n# ✅ Sum the counts of each class across all images\nclass_counts = class_occurrences.groupby(\"mapped_class_name\")[\"count\"].sum()\n\n# ✅ Sort by count (optional, for better visualization)\nclass_counts = class_counts.sort_values(ascending=False)\n\n# ✅ Create a color palette\ncolors = sns.color_palette(\"Set2\", len(class_counts))\n\n# ✅ Plot the class distribution with annotations\nplt.figure(figsize=(12, 6))\nbarplot = class_counts.plot(kind='bar', color=colors)\n\n# ✅ Add value annotations above each bar\nfor i, value in enumerate(class_counts.values):\n    plt.text(i, value + max(class_counts.values) * 0.01, str(value), ha='center', va='bottom', fontsize=10)\n\nplt.title('Mapped Class Distribution Across All Images (Total Bounding Box Occurrences)', fontsize=16)\nplt.xlabel('Mapped Class Name', fontsize=12)\nplt.ylabel('Total Number of Bounding Boxes', fontsize=12)\nplt.xticks(rotation=45, ha='right')\nplt.grid(axis='y', linestyle='--', alpha=0.5)\nplt.tight_layout()\nplt.show()\n\n# ✅ Print the full distribution as a summary\nprint(\"\\n📊 Mapped class distribution (counting total bounding box occurrences across images):\")\nprint(class_counts)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 3. ***Data Split***","metadata":{}},{"cell_type":"code","source":"# ✅ Create a multi-label column (set of unique class IDs per image)\ntrain_df_multi = train_df.groupby('image_id')['class_id'].agg(lambda x: list(set(x))).reset_index()\n\n# ✅ Merge the multi-labels back to the original dataframe\ntrain_df = train_df.merge(train_df_multi, on='image_id', suffixes=(\"\", \"_multi\"))\n\n# ✅ Convert multi-labels to strings for stratification\ntrain_df['multi_class_str'] = train_df['class_id_multi'].astype(str)\n\n# ✅ Initialize StratifiedGroupKFold\nsgkf = StratifiedGroupKFold(n_splits=4, shuffle=True, random_state=42)\n\n# ✅ Perform the split (take only the first fold)\nfor train_idx, val_idx in sgkf.split(train_df, train_df['multi_class_str'], groups=train_df['image_id']):\n    train_df_split = train_df.iloc[train_idx].reset_index(drop=True)\n    val_df_split = train_df.iloc[val_idx].reset_index(drop=True)\n    break\n\n# ✅ Drop temporary helper columns\ntrain_df_split.drop(columns=['class_id_multi', 'multi_class_str'], inplace=True)\nval_df_split.drop(columns=['class_id_multi', 'multi_class_str'], inplace=True)\n\n# ✅ Display summary\nprint(f\"✅ Train Images: {train_df_split['image_id'].nunique()}\")\nprint(f\"✅ Val Images: {val_df_split['image_id'].nunique()}\")\nprint(train_df_split['source_dataset'].value_counts(normalize=True))\nprint(val_df_split['source_dataset'].value_counts(normalize=True))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ✅ Create necessary directories for YOLO\nos.makedirs('data/images/train', exist_ok=True)\nos.makedirs('data/images/val', exist_ok=True)\nos.makedirs('data/labels/train', exist_ok=True)\nos.makedirs('data/labels/val', exist_ok=True)\n\n# ✅ Function to prepare YOLO labels and move the images to appropriate directories\ndef prepare_yolo_labels(df, image_dest_dir, label_dest_dir):\n    # ✅ Remove duplicate bounding boxes before writing\n    df = df.drop_duplicates(subset=['image_id', 'new_class_id', 'x_mid', 'y_mid', 'w', 'h'])\n\n    for image_id, group in tqdm(df.groupby('image_id'), desc=f\"Processing {image_dest_dir}\"):\n        image_path = group.iloc[0]['image_path']\n        label_file = os.path.join(label_dest_dir, os.path.basename(image_path).replace('.png', '.txt'))\n\n        # ✅ Copy image\n        shutil.copy(image_path, os.path.join(image_dest_dir, os.path.basename(image_path)))\n\n        # ✅ Write all labels in one go\n        with open(label_file, 'w') as f:\n            for _, row in group.iterrows():\n                f.write(f\"{row['new_class_id']} {row['x_mid']} {row['y_mid']} {row['w']} {row['h']}\\n\")\n\n\n# ✅ Prepare and move train and validation data (images and labels) with progress bars\nprepare_yolo_labels(train_df_split, 'data/images/train', 'data/labels/train')\nprepare_yolo_labels(val_df_split, 'data/images/val', 'data/labels/val')\n\n# ✅ Function to remove exact duplicate lines from YOLO label files\ndef deduplicate_yolo_labels(label_dir):\n    label_paths = glob(os.path.join(label_dir, \"*.txt\"))\n    total_files = len(label_paths)\n    deduplicated_count = 0\n    duplicate_files = []\n\n    for path in label_paths:\n        with open(path, 'r') as f:\n            lines = f.readlines()\n        original_count = len(lines)\n        deduped = list(set([line.strip() for line in lines]))\n        deduped_count = len(deduped)\n\n        if deduped_count < original_count:\n            deduplicated_count += 1\n            duplicate_files.append((os.path.basename(path), original_count - deduped_count))\n            with open(path, 'w') as f:\n                f.write('\\n'.join(deduped) + '\\n')\n\n    print(f\"✅ Deduplicated {deduplicated_count}/{total_files} files in: {label_dir}\")\n    if duplicate_files:\n        print(\"🔍 Files with duplicates removed:\")\n        for fname, dup_count in duplicate_files:\n            print(f\"{fname}: {dup_count} duplicates removed\")\n\n# ✅ Deduplicate labels for both train and val\ndeduplicate_yolo_labels('data/labels/train')\ndeduplicate_yolo_labels('data/labels/val')\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 5. ***data.yaml file & YOLO11 Training***","metadata":{}},{"cell_type":"code","source":"# ✅ Create the data.yaml file for YOLOv11\ndata_yaml = \"\"\"  \ntrain: /kaggle/working/data/images/train  \nval: /kaggle/working/data/images/val  \n\nnc: 6 \nnames: [  \n  \"Cardiac & Vascular\",  \n  \"Lung Collapse\",  \n  \"Lung Opacity\",  \n  \"Fibrosis & ILD\",  \n  \"Nodule/Mass or Other Lesion\",  \n  \"Pleural Abnormalities\"  \n]\n\"\"\"\n\n# ✅ Save the YAML file to the working directory\nwith open('/kaggle/working/data.yaml', 'w') as f:  \n    f.write(data_yaml)  \n\nprint(\"✅ data.yaml file has been created!\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 6. ***YOLO12 Training***","metadata":{}},{"cell_type":"code","source":"# ✅ Check available GPUs\nnum_gpus = torch.cuda.device_count()\nprint(f\"Available GPUs: {num_gpus}\")\nfor i in range(num_gpus):\n    print(f\"GPU {i}: {torch.cuda.get_device_name(i)}\")\n\n# ✅ Set device for training (use the first GPU if available, otherwise use CPU)\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\nprint(f\"Using {device} for training\")\n\n# ✅ Load YOLOv12-M model\nmodel = YOLO(\"yolo12m.pt\")  # Load pre-trained YOLOv12-M weights\n\n# ✅ Move model to the appropriate device (single GPU or CPU)\nmodel = model.to(device)\n\n# ✅ Optimize CUDA memory allocation\ntorch.cuda.empty_cache()\nos.environ[\"PYTORCH_CUDA_ALLOC_CONF\"] = \"expandable_segments:True\"\n\n# ✅ Train the model using the correct training method (from YOLOv12 docs)\ntrain_results = model.train(\n    data=\"/kaggle/working/data.yaml\",  # Path to dataset YAML\n    epochs=70,\n    batch=8,  # Increase batch size for multiple GPUs\n    imgsz=640,\n    device=device,\n    half=True,\n    workers=4,  # Increase workers to match GPUs\n    project=\"yolov12-training\",\n    name=\"yolo12m-vinbigdata\",\n    exist_ok=True,\n    save=True,\n    save_period=10,\n)\n\n# ✅ Check training results\nprint(\"✅ Training results:\")\nprint(train_results)\n\n# ✅ Validate the model\nmetrics = model.val()\n\n# ✅ Print evaluation metrics\nprint(\"Evaluation metrics:\")\nprint(metrics)\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}