{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"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":"markdown","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"}},{"cell_type":"code","source":"!pip install --upgrade seaborn","metadata":{"execution":{"iopub.status.busy":"2023-09-21T07:48:59.599513Z","iopub.execute_input":"2023-09-21T07:48:59.600093Z","iopub.status.idle":"2023-09-21T07:49:14.997657Z","shell.execute_reply.started":"2023-09-21T07:48:59.599984Z","shell.execute_reply":"2023-09-21T07:49:14.996445Z"},"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":"2023-09-21T11:16:45.548889Z","iopub.execute_input":"2023-09-21T11:16:45.549642Z","iopub.status.idle":"2023-09-21T11:16:46.283115Z","shell.execute_reply.started":"2023-09-21T11:16:45.549604Z","shell.execute_reply":"2023-09-21T11:16:46.282042Z"},"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()\ntrain_df=train_df[:15000]","metadata":{"execution":{"iopub.status.busy":"2023-09-21T11:19:07.106222Z","iopub.execute_input":"2023-09-21T11:19:07.106647Z","iopub.status.idle":"2023-09-21T11:19:07.235058Z","shell.execute_reply.started":"2023-09-21T11:19:07.106599Z","shell.execute_reply":"2023-09-21T11:19:07.233862Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\npd.unique(train_df['class_name'])\n#len(train_df['class_name'])","metadata":{"execution":{"iopub.status.busy":"2023-09-21T11:19:36.720069Z","iopub.execute_input":"2023-09-21T11:19:36.720538Z","iopub.status.idle":"2023-09-21T11:19:36.73329Z","shell.execute_reply.started":"2023-09-21T11:19:36.720496Z","shell.execute_reply":"2023-09-21T11:19:36.732201Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df['image_path'] = f'/kaggle/input/vinbigdata-{dim}-image-dataset/vinbigdata/train/'+ train_df.image_id+('.png' if dim!='original' else '.jpg')\ntrain_df.head()","metadata":{"execution":{"iopub.status.busy":"2023-09-21T11:20:40.526948Z","iopub.execute_input":"2023-09-21T11:20:40.527714Z","iopub.status.idle":"2023-09-21T11:20:40.562149Z","shell.execute_reply.started":"2023-09-21T11:20:40.527676Z","shell.execute_reply":"2023-09-21T11:20:40.560864Z"},"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":"2023-09-21T11:20:40.564287Z","iopub.execute_input":"2023-09-21T11:20:40.564627Z","iopub.status.idle":"2023-09-21T11:20:40.578496Z","shell.execute_reply.started":"2023-09-21T11:20:40.564597Z","shell.execute_reply":"2023-09-21T11:20:40.577374Z"},"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":"2023-09-21T11:20:40.581144Z","iopub.execute_input":"2023-09-21T11:20:40.581848Z","iopub.status.idle":"2023-09-21T11:20:42.67296Z","shell.execute_reply.started":"2023-09-21T11:20:40.581805Z","shell.execute_reply":"2023-09-21T11:20:42.671716Z"},"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":"2023-09-21T11:20:42.676208Z","iopub.execute_input":"2023-09-21T11:20:42.677363Z","iopub.status.idle":"2023-09-21T11:20:42.689679Z","shell.execute_reply.started":"2023-09-21T11:20:42.677316Z","shell.execute_reply":"2023-09-21T11:20:42.688062Z"},"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":"2023-09-21T11:20:42.69157Z","iopub.execute_input":"2023-09-21T11:20:42.69261Z","iopub.status.idle":"2023-09-21T11:20:42.709601Z","shell.execute_reply.started":"2023-09-21T11:20:42.692561Z","shell.execute_reply":"2023-09-21T11:20:42.708225Z"},"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":"2023-09-21T11:20:42.71195Z","iopub.execute_input":"2023-09-21T11:20:42.712516Z","iopub.status.idle":"2023-09-21T11:20:42.771262Z","shell.execute_reply.started":"2023-09-21T11:20:42.712472Z","shell.execute_reply":"2023-09-21T11:20:42.769908Z"},"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":"2023-09-21T11:20:42.773428Z","iopub.execute_input":"2023-09-21T11:20:42.773869Z","iopub.status.idle":"2023-09-21T11:20:42.792827Z","shell.execute_reply.started":"2023-09-21T11:20:42.773825Z","shell.execute_reply":"2023-09-21T11:20:42.791691Z"},"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":"2023-09-21T11:20:42.79469Z","iopub.execute_input":"2023-09-21T11:20:42.795235Z","iopub.status.idle":"2023-09-21T11:21:30.957156Z","shell.execute_reply.started":"2023-09-21T11:20:42.795189Z","shell.execute_reply":"2023-09-21T11:21:30.956061Z"},"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\n\ncwd = '/kaggle/working/'\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    )\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":{"execution":{"iopub.status.busy":"2023-09-21T11:21:30.958679Z","iopub.execute_input":"2023-09-21T11:21:30.959739Z","iopub.status.idle":"2023-09-21T11:21:31.032762Z","shell.execute_reply.started":"2023-09-21T11:21:30.959696Z","shell.execute_reply":"2023-09-21T11:21:31.031492Z"},"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":{"execution":{"iopub.status.busy":"2023-09-21T11:21:31.037254Z","iopub.execute_input":"2023-09-21T11:21:31.037574Z","iopub.status.idle":"2023-09-21T11:21:32.493251Z","shell.execute_reply.started":"2023-09-21T11:21:31.037544Z","shell.execute_reply":"2023-09-21T11:21:32.491958Z"},"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\nshutil.rmtree('/kaggle/working/yolov5')","metadata":{"execution":{"iopub.status.busy":"2023-09-21T11:21:32.495081Z","iopub.execute_input":"2023-09-21T11:21:32.495811Z","iopub.status.idle":"2023-09-21T11:21:32.568045Z","shell.execute_reply.started":"2023-09-21T11:21:32.495773Z","shell.execute_reply":"2023-09-21T11:21:32.566431Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Setting up yolov5\nshutil.copytree('/kaggle/input/yolov5-official-v31-dataset/yolov5', '/kaggle/working/yolov5')\nos.chdir('/kaggle/working/yolov5')\n\nclear_output()\nprint('Setup complete. Using torch %s %s' % (torch.__version__, torch.cuda.get_device_properties(0) if torch.cuda.is_available() else 'CPU'))","metadata":{"execution":{"iopub.status.busy":"2023-09-21T11:21:54.744728Z","iopub.execute_input":"2023-09-21T11:21:54.74515Z","iopub.status.idle":"2023-09-21T11:21:55.229225Z","shell.execute_reply.started":"2023-09-21T11:21:54.745113Z","shell.execute_reply":"2023-09-21T11:21:55.228039Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pwd","metadata":{"execution":{"iopub.status.busy":"2023-09-21T11:21:59.120242Z","iopub.execute_input":"2023-09-21T11:21:59.120982Z","iopub.status.idle":"2023-09-21T11:21:59.130347Z","shell.execute_reply.started":"2023-09-21T11:21:59.120944Z","shell.execute_reply":"2023-09-21T11:21:59.129059Z"},"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 6 --data /kaggle/working/vinbigdata.yaml --weights yolov5x.pt --cache","metadata":{"execution":{"iopub.status.busy":"2023-09-21T11:22:04.64974Z","iopub.execute_input":"2023-09-21T11:22:04.65017Z","iopub.status.idle":"2023-09-21T11:41:50.305198Z","shell.execute_reply.started":"2023-09-21T11:22:04.650134Z","shell.execute_reply":"2023-09-21T11:41:50.303792Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\n\n# Load the trained model (change the path if needed)\nmodel = torch.load('yolov5x.pt', map_location='cuda' if torch.cuda.is_available() else 'cpu')\n\n# Save the model's state dictionary as a checkpoint file\ntorch.save(model, '/kaggle/working/yolov5_checkpoint.pth')\n","metadata":{"execution":{"iopub.status.busy":"2023-09-21T11:50:26.996551Z","iopub.execute_input":"2023-09-21T11:50:26.996949Z","iopub.status.idle":"2023-09-21T11:50:27.921324Z","shell.execute_reply.started":"2023-09-21T11:50:26.996915Z","shell.execute_reply":"2023-09-21T11:50:27.919566Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nimport h5py\n\n# Load the saved checkpoint\nstate_dict = torch.load('/kaggle/working/yolov5_checkpoint.pth', map_location='cuda' if torch.cuda.is_available() else 'cpu')\n\n# Create an H5 file to save the model\nwith h5py.File('/kaggle/working/yolov5_model.h5', 'w') as h5file:\n    # Iterate through the state_dict and save each parameter\n    for key, value in state_dict.items():\n        if isinstance(value, torch.Tensor):\n            h5file.create_dataset(key, data=value.cpu().numpy())\n","metadata":{"execution":{"iopub.status.busy":"2023-09-21T11:52:15.162475Z","iopub.execute_input":"2023-09-21T11:52:15.16288Z","iopub.status.idle":"2023-09-21T11:52:15.447165Z","shell.execute_reply.started":"2023-09-21T11:52:15.162847Z","shell.execute_reply":"2023-09-21T11:52:15.445923Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!WANDB_MODE=\"dryrun\" python train.py --img 640 --batch 16 --epochs 30 --data /kaggle/working/vinbigdata.yaml --weights yolov5x.pt --cache\n","metadata":{"execution":{"iopub.status.busy":"2023-09-21T11:21:32.577346Z","iopub.status.idle":"2023-09-21T11:21:32.578499Z","shell.execute_reply.started":"2023-09-21T11:21:32.578193Z","shell.execute_reply":"2023-09-21T11:21:32.578221Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import shutil\n\n# Specify the source directory of the best model checkpoint\nsource_dir = 'runs/train/expX/weights/'\n# Specify the destination directory where you want to save the model\ndestination_dir = '/kaggle/working/saved_models/'\n# Move the best model checkpoint to the destination directory\nshutil.move(source_dir + 'best.pt', destination_dir)","metadata":{"execution":{"iopub.status.busy":"2023-09-21T11:21:32.58026Z","iopub.status.idle":"2023-09-21T11:21:32.580804Z","shell.execute_reply.started":"2023-09-21T11:21:32.580522Z","shell.execute_reply":"2023-09-21T11:21:32.580547Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Confusion matrix","metadata":{}},{"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('runs/train/exp/confusion_matrix.png'));","metadata":{"execution":{"iopub.status.busy":"2023-09-21T11:21:32.582814Z","iopub.status.idle":"2023-09-21T11:21:32.583395Z","shell.execute_reply.started":"2023-09-21T11:21:32.583103Z","shell.execute_reply":"2023-09-21T11:21:32.583129Z"},"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('runs/train/exp/results.png'));","metadata":{"execution":{"iopub.status.busy":"2023-09-21T11:21:32.585449Z","iopub.status.idle":"2023-09-21T11:21:32.58604Z","shell.execute_reply.started":"2023-09-21T11:21:32.585708Z","shell.execute_reply":"2023-09-21T11:21:32.585734Z"},"trusted":true},"execution_count":null,"outputs":[]}]}