{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":24800,"databundleVersionId":1831594,"sourceType":"competition"},{"sourceId":1799839,"sourceType":"datasetVersion","datasetId":1069682},{"sourceId":1800066,"sourceType":"datasetVersion","datasetId":1069809},{"sourceId":1800067,"sourceType":"datasetVersion","datasetId":1069810},{"sourceId":1800777,"sourceType":"datasetVersion","datasetId":1069787},{"sourceId":1800778,"sourceType":"datasetVersion","datasetId":1070222},{"sourceId":1800825,"sourceType":"datasetVersion","datasetId":1070245},{"sourceId":1832961,"sourceType":"datasetVersion","datasetId":1089494},{"sourceId":52422980,"sourceType":"kernelVersion"}],"dockerImageVersionId":30214,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# 💻 You Only Look Once (YOLO) Training and Cross Validation\n### Group: 4NN\n#### Dharani Palanisamy (z5260276)\n#### Faiyam Islam (z5258151)\n#### Pooja Saianand (z5312416)\n#### Priya Nandyal (z5312288)\n\n\nThe notebook computes loss function values, precision, recall, and mean average precision curves using cross validation of the dataset. We will also analyse the evaluation metrics such as mAP and IoU and instigate a conclusion on the accuracy of this object detection method.\n\nWe are running this notebook on GPU.\n\nWe've used the following sources which assisted our approach for YOLO:\n\nhttps://www.kaggle.com/code/kimse0ha/vinbigdata-eda-infer-analysis-with-yolov5\n\nhttps://www.kaggle.com/code/awsaf49/vinbigdata-cxr-ad-yolov5-14-class-infer/notebook\n\nhttps://www.kaggle.com/code/mrutyunjaybiswal/vbd-chest-x-ray-abnormalities-detection-eda/notebook\n\nhttps://www.kaggle.com/code/jamsilkaggle/quick-data-analysis-with-yolov5-at-a-glance","metadata":{}},{"cell_type":"markdown","source":"# Importing datasets and installing packages","metadata":{}},{"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\n# import numpy as np # linear algebra\n# import 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\n# import os\n# for 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_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install --upgrade seaborn","metadata":{"execution":{"iopub.status.busy":"2024-03-22T05:08:56.438178Z","iopub.execute_input":"2024-03-22T05:08:56.438941Z","iopub.status.idle":"2024-03-22T05:09:11.678299Z","shell.execute_reply.started":"2024-03-22T05:08:56.438856Z","shell.execute_reply":"2024-03-22T05:09:11.676857Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np, pandas as pd\nfrom glob import glob\nimport shutil, os\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import GroupKFold\nfrom tqdm.notebook import tqdm\nimport seaborn as sns","metadata":{"execution":{"iopub.status.busy":"2024-03-22T05:09:11.685595Z","iopub.execute_input":"2024-03-22T05:09:11.686324Z","iopub.status.idle":"2024-03-22T05:09:13.578128Z","shell.execute_reply.started":"2024-03-22T05:09:11.686257Z","shell.execute_reply":"2024-03-22T05:09:13.577274Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Analyzing the train dataset and obtaining class information","metadata":{}},{"cell_type":"code","source":"dim = 512\nfold = 4\ntrain_df = pd.read_csv(f'../input/vinbigdata-{dim}-image-dataset/vinbigdata/train.csv')\ntrain_df.head()","metadata":{"execution":{"iopub.status.busy":"2024-03-22T05:09:13.579267Z","iopub.execute_input":"2024-03-22T05:09:13.57957Z","iopub.status.idle":"2024-03-22T05:09:13.798423Z","shell.execute_reply.started":"2024-03-22T05:09:13.579543Z","shell.execute_reply":"2024-03-22T05:09:13.797404Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport cv2\nfrom tqdm import tqdm\n\n# Define the folder path containing the images\nimage_folder = \"/kaggle/input/vinbigdata-512-image-dataset/vinbigdata/train\"\n\n# Get a list of image paths\nimage_paths = [os.path.join(image_folder, filename) for filename in os.listdir(image_folder) if filename.endswith((\".jpg\", \".jpeg\", \".png\"))]\n\n# Apply CLAHE preprocessing with a loop and progress bar (adapt if using pandas progress_apply)\nfor image_path in tqdm(image_paths, desc=\"Applying CLAHE\"):\n  try:\n    # Load image using cv2.imread\n    image = cv2.imread(image_path)\n\n    # Convert to grayscale (adjust if working with color images)\n    image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n    # Create CLAHE object\n    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))\n\n    # Apply CLAHE\n    image_eq = clahe.apply(image_gray)\n\n    # Extract filename and directory from image path\n    filename = os.path.basename(image_path)\n    image_dir = \"/kaggle/working/\"\n\n    # Create the \"preprocessing\" subfolder within the original image directory if it doesn't exist\n    output_dir = os.path.join(image_dir, \"preprocessing\")\n    os.makedirs(output_dir, exist_ok=True)\n\n    # Save preprocessed image to the subfolder with the same filename\n    output_path = os.path.join(output_dir, filename + \".png\")\n    cv2.imwrite(output_path, image_eq)\n\n  except Exception as e:\n    print(f\"Error processing image {image_path}: {e}\")","metadata":{"execution":{"iopub.status.busy":"2024-03-22T05:10:56.476983Z","iopub.execute_input":"2024-03-22T05:10:56.47739Z","iopub.status.idle":"2024-03-22T05:15:40.861127Z","shell.execute_reply.started":"2024-03-22T05:10:56.477356Z","shell.execute_reply":"2024-03-22T05:15:40.860109Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# train_df['image_path'] = f'/kaggle/input/vinbigdata-{dim}-image-dataset/vinbigdata/train/preprocessing'+ train_df.image_id+('.png' if dim!='original' else '.jpg')\n# train_df.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df['image_path'] = f'/kaggle/working/preprocessing/'+ train_df.image_id+('.png' if dim!='original' else '.jpg')\ntrain_df.head()","metadata":{"execution":{"iopub.status.busy":"2024-03-22T05:16:19.164293Z","iopub.execute_input":"2024-03-22T05:16:19.164679Z","iopub.status.idle":"2024-03-22T05:16:19.209696Z","shell.execute_reply.started":"2024-03-22T05:16:19.164645Z","shell.execute_reply":"2024-03-22T05:16:19.208673Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Getting the number of classes \ntrain_df = train_df[train_df.class_id!=14].reset_index(drop = True)","metadata":{"execution":{"iopub.status.busy":"2024-03-22T05:16:28.617017Z","iopub.execute_input":"2024-03-22T05:16:28.617989Z","iopub.status.idle":"2024-03-22T05:16:28.641388Z","shell.execute_reply.started":"2024-03-22T05:16:28.617949Z","shell.execute_reply":"2024-03-22T05:16:28.640271Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Pre-processing the dataset by computing the values of x_min,x_max,x_mid,y_min,y_max,y_mid,height and width\n\ntrain_df['x_min'] = train_df.apply(lambda row: (row.x_min)/row.width, axis =1)\ntrain_df['x_max'] = train_df.apply(lambda row: (row.x_max)/row.width, axis =1)\ntrain_df['x_mid'] = train_df.apply(lambda row: (row.x_max+row.x_min)/2, axis =1)\n\ntrain_df['y_min'] = train_df.apply(lambda row: (row.y_min)/row.height, axis =1)\ntrain_df['y_max'] = train_df.apply(lambda row: (row.y_max)/row.height, axis =1)\ntrain_df['y_mid'] = train_df.apply(lambda row: (row.y_max+row.y_min)/2, axis =1)\n\ntrain_df['h'] = train_df.apply(lambda row: (row.y_max-row.y_min), axis =1) #height\ntrain_df['w'] = train_df.apply(lambda row: (row.x_max-row.x_min), axis =1) #width\n\ntrain_df['area'] = train_df['w']*train_df['h']\ntrain_df.head()","metadata":{"execution":{"iopub.status.busy":"2024-03-22T05:16:30.174471Z","iopub.execute_input":"2024-03-22T05:16:30.174832Z","iopub.status.idle":"2024-03-22T05:16:38.646385Z","shell.execute_reply.started":"2024-03-22T05:16:30.174804Z","shell.execute_reply":"2024-03-22T05:16:38.645067Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# The number of rows in the train_df for the feature columns\nfeatures = ['x_min', 'y_min', 'x_max', 'y_max', 'x_mid', 'y_mid', 'w', 'h', 'area']\ny = train_df['class_id']\nX = train_df[features]\nX.shape, y.shape","metadata":{"execution":{"iopub.status.busy":"2024-03-22T05:16:38.648568Z","iopub.execute_input":"2024-03-22T05:16:38.648946Z","iopub.status.idle":"2024-03-22T05:16:38.662979Z","shell.execute_reply.started":"2024-03-22T05:16:38.648911Z","shell.execute_reply":"2024-03-22T05:16:38.661923Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# To get a list of the class names\nclass_ids, class_names = list(zip(*set(zip(train_df.class_id, train_df.class_name))))\nclass_list = list(np.array(class_names)[np.argsort(class_ids)])\nclass_list = list(map(lambda x: str(x), class_list))\nclass_list\n","metadata":{"execution":{"iopub.status.busy":"2024-03-22T05:16:42.476951Z","iopub.execute_input":"2024-03-22T05:16:42.477739Z","iopub.status.idle":"2024-03-22T05:16:42.498255Z","shell.execute_reply.started":"2024-03-22T05:16:42.477705Z","shell.execute_reply":"2024-03-22T05:16:42.497203Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Splitting the dataset","metadata":{}},{"cell_type":"code","source":"# Split the dataset and drop all the x-rays that do not contain any abnormality\nfold = 4\ngkf  = GroupKFold(n_splits = 5)\ntrain_df['fold'] = -1\nfor fold, (train_idx, val_idx) in enumerate(gkf.split(train_df, groups = train_df.image_id.tolist())):\n    train_df.loc[val_idx, 'fold'] = fold\ntrain_df.head()","metadata":{"execution":{"iopub.status.busy":"2024-03-22T05:16:44.623709Z","iopub.execute_input":"2024-03-22T05:16:44.624435Z","iopub.status.idle":"2024-03-22T05:16:44.705202Z","shell.execute_reply.started":"2024-03-22T05:16:44.6244Z","shell.execute_reply":"2024-03-22T05:16:44.7042Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"val_files   = []\ntrain_files = []\nval_files += list(train_df[train_df.fold==fold].image_path.unique())\ntrain_files += list(train_df[train_df.fold!=fold].image_path.unique())\nprint(len(train_files)) #size of train dataset\nprint(len(val_files)) # size of validation set","metadata":{"execution":{"iopub.status.busy":"2024-03-22T05:16:46.633485Z","iopub.execute_input":"2024-03-22T05:16:46.633882Z","iopub.status.idle":"2024-03-22T05:16:46.659187Z","shell.execute_reply.started":"2024-03-22T05:16:46.633848Z","shell.execute_reply":"2024-03-22T05:16:46.65818Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Creating directories and copying files","metadata":{}},{"cell_type":"code","source":"os.makedirs('/kaggle/working/vinbigdata/labels/train', exist_ok = True)\nos.makedirs('/kaggle/working/vinbigdata/labels/val', exist_ok = True)\nos.makedirs('/kaggle/working/vinbigdata/images/train', exist_ok = True)\nos.makedirs('/kaggle/working/vinbigdata/images/val', exist_ok = True)\nlabel_dir = '/kaggle/input/vinbigdata-yolo-labels-dataset/labels'\nfor file in tqdm(train_files): # we use tqdm to see the progress of the copying of files\n    shutil.copy(file, '/kaggle/working/vinbigdata/images/train')\n    filename = file.split('/')[-1].split('.')[0]\n    shutil.copy(os.path.join(label_dir, filename+'.txt'), '/kaggle/working/vinbigdata/labels/train')\n    \nfor file in tqdm(val_files):\n    shutil.copy(file, '/kaggle/working/vinbigdata/images/val')\n    filename = file.split('/')[-1].split('.')[0]\n    shutil.copy(os.path.join(label_dir, filename+'.txt'), '/kaggle/working/vinbigdata/labels/val')","metadata":{"execution":{"iopub.status.busy":"2024-03-22T05:16:49.438261Z","iopub.execute_input":"2024-03-22T05:16:49.438906Z","iopub.status.idle":"2024-03-22T05:16:49.472534Z","shell.execute_reply.started":"2024-03-22T05:16:49.438873Z","shell.execute_reply":"2024-03-22T05:16:49.471325Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Setting up YOLOv5","metadata":{}},{"cell_type":"code","source":"# Creating a yaml file \nfrom os import listdir\nfrom os.path import isfile, join\nimport yaml\nimport albumentations as A\n\n\ncwd = '/kaggle/working/'\n\ntrain_transforms = A.Compose([\n    # Define your desired augmentations here, for example:\n    A.CLAHE(clip_limit=2.0, tile_grid_size=(8, 8), p=1.0)  # Apply Contrast Limited Adaptive Histogram Equalization\n    A.ShiftScaleRotate(shift_limit=0.0625, scale_limit=0.2, rotate_limit=30, p=0.2),  # Rotate less than 30 degrees\n])\n\nwith open(join( cwd , 'train.txt'), 'w') as f:\n    for path in glob('/kaggle/working/vinbigdata/images/train/*'):\n        f.write(path+'\\n')\n            \nwith open(join( cwd , 'val.txt'), 'w') as f:\n    for path in glob('/kaggle/working/vinbigdata/images/val/*'):\n        f.write(path+'\\n')\n\ndata = dict(\n    train =  join( cwd , 'train.txt') ,\n    val   =  join( cwd , 'val.txt' ),\n    nc    = 14,\n    names = class_list\n    augmentations=train_transforms\n    )\n\nwith open(join( cwd , 'vinbigdata.yaml'), 'w') as outfile:\n    yaml.dump(data, outfile, default_flow_style=False)\n\nf = open(join( cwd , 'vinbigdata.yaml'), 'r')\nprint('\\nyaml contents:')\nprint(f.read())","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nfrom IPython.display import Image, clear_output  # to display images and clear outputs ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install ultralytics","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# # rmtree removes any yolov5 directory existing in the kaggle directory before creating a new one\n# # Running this function would result in an error if there is not yolov5 directory on the kaggle working directory\n# shutil.rmtree('/kaggle/working/yolov5')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# # Setting up yolov5\n# shutil.copytree('/kaggle/input/yolov5-official-v31-dataset/yolov5', '/kaggle/working/yolov5')\n# os.chdir('/kaggle/working/yolov5')\n\n# clear_output()\n# print('Setup complete. Using torch %s %s' % (torch.__version__, torch.cuda.get_device_properties(0) if torch.cuda.is_available() else 'CPU'))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# pwd","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Training the dataset and cross validation","metadata":{}},{"cell_type":"code","source":"# # training and cross validating the dataset using yolov5 \n# !WANDB_MODE=\"dryrun\" python train.py --img 640 --batch 16 --epochs 30 --data /kaggle/working/vinbigdata.yaml --weights yolov5x.pt --cache","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install -U ultralytics","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from ultralytics import YOLO\n\n# Build a YOLOv9c model from scratch\nmodel = YOLO('yolov9c.yaml')\n\n# Build a YOLOv9c model from pretrained weight\nmodel = YOLO('yolov9c.pt')\n\n# Display model information (optional)\nmodel.info()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from ultralytics import RTDETR\n\nmodel = RTDETR(\"rtdetr-l.pt\")\n\n# Display model information (optional)\nmodel.info()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results = model.train(data='/kaggle/working/vinbigdata.yaml', batch = 8 ,epochs=120, imgsz = 640, optimizer='SGD', project = 'vin_RTDETR')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# model.train(data='/kaggle/working/vinbigdata.yaml', batch = 8 ,epochs=120, imgsz = 640, optimizer='SGD', project = 'vin_yolo_v8')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.val(data='/kaggle/working/vinbigdata.yaml', conf=0.3)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Confusion matrix","metadata":{}},{"cell_type":"code","source":"!zip -r /kaggle/working/vin_yolo_v8 /kaggle/working/.","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!zip -r /kaggle/working/vin_yolo_v8 /kaggle/working/","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# A confusion matrix is produced when training the datasets\nplt.figure(figsize=(30,15))\nplt.axis('off')\nplt.imshow(plt.imread('/kaggle/working/vin_yolo_v8/train/confusion_matrix_normalized.png'));","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# A confusion matrix is produced when training the datasets\nplt.figure(figsize=(30,15))\nplt.axis('off')\nplt.imshow(plt.imread('/kaggle/working/vin_yolo_v8/val/confusion_matrix_normalized.png'));","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Plots for our model","metadata":{}},{"cell_type":"code","source":"# Training the data computes loss, precision, recall and mAP values for different thresholds\nplt.figure(figsize=(30,15))\nplt.axis('off')\nplt.imshow(plt.imread('/kaggle/working/vin_yolo_v8/train/results.png'));","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}