{"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":"code","source":"!pip install --upgrade seaborn","metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"papermill":{"duration":9.633907,"end_time":"2021-01-01T09:44:53.448657","exception":false,"start_time":"2021-01-01T09:44:43.81475","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-07-25T11:30:32.07544Z","iopub.execute_input":"2021-07-25T11:30:32.07584Z","iopub.status.idle":"2021-07-25T11:30:32.081565Z","shell.execute_reply.started":"2021-07-25T11:30:32.075796Z","shell.execute_reply":"2021-07-25T11:30:32.079298Z"},"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":{"papermill":{"duration":0.926929,"end_time":"2021-01-01T09:44:54.403588","exception":false,"start_time":"2021-01-01T09:44:53.476659","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-07-25T11:30:32.094838Z","iopub.execute_input":"2021-07-25T11:30:32.095529Z","iopub.status.idle":"2021-07-25T11:30:33.093169Z","shell.execute_reply.started":"2021-07-25T11:30:32.095488Z","shell.execute_reply":"2021-07-25T11:30:33.092235Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fold = 0","metadata":{"execution":{"iopub.status.busy":"2021-07-25T11:30:33.095893Z","iopub.execute_input":"2021-07-25T11:30:33.096329Z","iopub.status.idle":"2021-07-25T11:30:33.101455Z","shell.execute_reply.started":"2021-07-25T11:30:33.096286Z","shell.execute_reply":"2021-07-25T11:30:33.100199Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = pd.read_csv(f'../input/siim-covid19-detection/train_image_level.csv')\ntrain_df.head()","metadata":{"papermill":{"duration":0.262045,"end_time":"2021-01-01T09:44:54.691965","exception":false,"start_time":"2021-01-01T09:44:54.42992","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-07-25T11:30:33.10359Z","iopub.execute_input":"2021-07-25T11:30:33.104104Z","iopub.status.idle":"2021-07-25T11:30:33.200694Z","shell.execute_reply.started":"2021-07-25T11:30:33.104061Z","shell.execute_reply":"2021-07-25T11:30:33.199505Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import GroupKFold\ndf = train_df\n\ngkf  = GroupKFold(n_splits = 5)\ndf['fold'] = -1\nfor fold, (train_idx, val_idx) in enumerate(gkf.split(df, groups = df.StudyInstanceUID.tolist())):\n    df.loc[val_idx, 'fold'] = fold","metadata":{"execution":{"iopub.status.busy":"2021-07-25T11:30:33.202383Z","iopub.execute_input":"2021-07-25T11:30:33.202827Z","iopub.status.idle":"2021-07-25T11:30:33.252732Z","shell.execute_reply.started":"2021-07-25T11:30:33.202784Z","shell.execute_reply":"2021-07-25T11:30:33.251664Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = df","metadata":{"execution":{"iopub.status.busy":"2021-07-25T11:30:33.256455Z","iopub.execute_input":"2021-07-25T11:30:33.256908Z","iopub.status.idle":"2021-07-25T11:30:33.262278Z","shell.execute_reply.started":"2021-07-25T11:30:33.256872Z","shell.execute_reply":"2021-07-25T11:30:33.261026Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df['image_path'] = f'/kaggle/input/siimcovid19-512-img-png-600-study-png/image/' + train_df.id + '.png'\ntrain_df.head()","metadata":{"papermill":{"duration":0.086788,"end_time":"2021-01-01T09:44:54.805857","exception":false,"start_time":"2021-01-01T09:44:54.719069","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-07-25T11:30:33.265431Z","iopub.execute_input":"2021-07-25T11:30:33.266269Z","iopub.status.idle":"2021-07-25T11:30:33.303666Z","shell.execute_reply.started":"2021-07-25T11:30:33.266214Z","shell.execute_reply":"2021-07-25T11:30:33.302549Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"classes = ['0. opacity']","metadata":{"papermill":{"duration":0.050418,"end_time":"2021-01-01T09:45:03.002944","exception":false,"start_time":"2021-01-01T09:45:02.952526","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-07-25T11:30:33.30589Z","iopub.execute_input":"2021-07-25T11:30:33.306469Z","iopub.status.idle":"2021-07-25T11:30:33.311694Z","shell.execute_reply.started":"2021-07-25T11:30:33.306418Z","shell.execute_reply":"2021-07-25T11:30:33.310456Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_files = []\nval_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())\nlen(train_files), len(val_files)","metadata":{"papermill":{"duration":0.086817,"end_time":"2021-01-01T09:47:56.443789","exception":false,"start_time":"2021-01-01T09:47:56.356972","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-07-25T11:30:33.313491Z","iopub.execute_input":"2021-07-25T11:30:33.314011Z","iopub.status.idle":"2021-07-25T11:30:33.334748Z","shell.execute_reply.started":"2021-07-25T11:30:33.313966Z","shell.execute_reply":"2021-07-25T11:30:33.333544Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Copying Files","metadata":{"papermill":{"duration":0.083752,"end_time":"2021-01-01T09:47:56.584924","exception":false,"start_time":"2021-01-01T09:47:56.501172","status":"completed"},"tags":[]}},{"cell_type":"code","source":"os.makedirs('/kaggle/working/siim-cov19/labels/train', exist_ok = True)\nos.makedirs('/kaggle/working/siim-cov19/labels/val', exist_ok = True)\nos.makedirs('/kaggle/working/siim-cov19/images/train', exist_ok = True)\nos.makedirs('/kaggle/working/siim-cov19/images/val', exist_ok = True)\nlabel_dir = '/kaggle/input/siim-covid-19-yolo-txt'\nfor file in tqdm(train_files):\n    shutil.copy(file, '/kaggle/working/siim-cov19/images/train')\n    filename = file.split('/')[-1].split('.')[0]\n    shutil.copy(os.path.join(label_dir, filename+'.txt'), '/kaggle/working/siim-cov19/labels/train')\n    \nfor file in tqdm(val_files):\n    shutil.copy(file, '/kaggle/working/siim-cov19/images/val')\n    filename = file.split('/')[-1].split('.')[0]\n    shutil.copy(os.path.join(label_dir, filename+'.txt'), '/kaggle/working/siim-cov19/labels/val')","metadata":{"papermill":{"duration":124.654777,"end_time":"2021-01-01T09:50:01.331041","exception":false,"start_time":"2021-01-01T09:47:56.676264","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-07-25T11:30:33.336782Z","iopub.execute_input":"2021-07-25T11:30:33.33727Z","iopub.status.idle":"2021-07-25T11:32:25.295577Z","shell.execute_reply.started":"2021-07-25T11:30:33.337222Z","shell.execute_reply":"2021-07-25T11:32:25.294656Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Get Class Name","metadata":{"papermill":{"duration":0.068822,"end_time":"2021-01-01T09:50:01.458337","exception":false,"start_time":"2021-01-01T09:50:01.389515","status":"completed"},"tags":[]}},{"cell_type":"code","source":"classes = ['0. opacity']","metadata":{"papermill":{"duration":0.082234,"end_time":"2021-01-01T09:50:01.601574","exception":false,"start_time":"2021-01-01T09:50:01.51934","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-07-25T11:32:25.297282Z","iopub.execute_input":"2021-07-25T11:32:25.297858Z","iopub.status.idle":"2021-07-25T11:32:25.303443Z","shell.execute_reply.started":"2021-07-25T11:32:25.297811Z","shell.execute_reply":"2021-07-25T11:32:25.302098Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# [YOLOv5](https://github.com/ultralytics/yolov5)\n![](https://user-images.githubusercontent.com/26833433/98699617-a1595a00-2377-11eb-8145-fc674eb9b1a7.jpg)\n![](https://user-images.githubusercontent.com/26833433/90187293-6773ba00-dd6e-11ea-8f90-cd94afc0427f.png)","metadata":{"papermill":{"duration":0.056257,"end_time":"2021-01-01T09:50:01.716608","exception":false,"start_time":"2021-01-01T09:50:01.660351","status":"completed"},"tags":[]}},{"cell_type":"markdown","source":"# YOLOv5 Stuff","metadata":{"papermill":{"duration":0.055699,"end_time":"2021-01-01T09:50:01.82747","exception":false,"start_time":"2021-01-01T09:50:01.771771","status":"completed"},"tags":[]}},{"cell_type":"code","source":"from 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/siim-cov19/images/train/*'):\n        f.write(path+'\\n')\n            \nwith open(join( cwd , 'val.txt'), 'w') as f:\n    for path in glob('/kaggle/working/siim-cov19/images/val/*'):\n        f.write(path+'\\n')\n\ndata = dict(\n    train =  join( cwd , 'train.txt') ,\n    val   =  join( cwd , 'val.txt' ),\n    nc    = 1,\n    names = classes\n    )\n\nwith open(join( cwd , 'siim-cov19.yaml'), 'w') as outfile:\n    yaml.dump(data, outfile, default_flow_style=False)\n\nf = open(join( cwd , 'siim-cov19.yaml'), 'r')\nprint('\\nyaml:')\nprint(f.read())","metadata":{"papermill":{"duration":0.113001,"end_time":"2021-01-01T09:50:01.996448","exception":false,"start_time":"2021-01-01T09:50:01.883447","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-07-25T11:32:25.305184Z","iopub.execute_input":"2021-07-25T11:32:25.306047Z","iopub.status.idle":"2021-07-25T11:32:25.398989Z","shell.execute_reply.started":"2021-07-25T11:32:25.305992Z","shell.execute_reply":"2021-07-25T11:32:25.397878Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# https://www.kaggle.com/ultralytics/yolov5\n!git clone https://github.com/ultralytics/yolov5 # clone repo\n%cd yolov5\n# shutil.copytree('/kaggle/input/yolov5-official-v31-dataset/yolov5', '/kaggle/working/yolov5')\n# os.chdir('/kaggle/working/yolov5')\n%pip install -qr requirements.txt # install dependencies\n\nimport torch\nfrom IPython.display import Image, clear_output  # to display images\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":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","papermill":{"duration":6.702428,"end_time":"2021-01-01T09:50:08.784153","exception":false,"start_time":"2021-01-01T09:50:02.081725","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-07-25T11:32:25.400554Z","iopub.execute_input":"2021-07-25T11:32:25.401038Z","iopub.status.idle":"2021-07-25T11:34:07.141541Z","shell.execute_reply.started":"2021-07-25T11:32:25.400968Z","shell.execute_reply":"2021-07-25T11:34:07.140369Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!python detect.py --weights yolov5s.pt --img 640 --conf 0.25 --source data/images/\nImage(filename='runs/detect/exp/zidane.jpg', width=600)","metadata":{"papermill":{"duration":10.410768,"end_time":"2021-01-01T09:50:19.303402","exception":false,"start_time":"2021-01-01T09:50:08.892634","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-07-25T11:34:07.143618Z","iopub.execute_input":"2021-07-25T11:34:07.144057Z","iopub.status.idle":"2021-07-25T11:34:21.668929Z","shell.execute_reply.started":"2021-07-25T11:34:07.144016Z","shell.execute_reply":"2021-07-25T11:34:21.667731Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Pretrained Checkpoints:\n\n| Model | AP<sup>val</sup> | AP<sup>test</sup> | AP<sub>50</sub> | Speed<sub>GPU</sub> | FPS<sub>GPU</sub> || params | FLOPS |\n|---------- |------ |------ |------ | -------- | ------| ------ |------  |  :------: |\n| [YOLOv5s](https://github.com/ultralytics/yolov5/releases/tag/v3.0)    | 37.0     | 37.0     | 56.2     | **2.4ms** | **416** || 7.5M   | 13.2B\n| [YOLOv5m](https://github.com/ultralytics/yolov5/releases/tag/v3.0)    | 44.3     | 44.3     | 63.2     | 3.4ms     | 294     || 21.8M  | 39.4B\n| [YOLOv5l](https://github.com/ultralytics/yolov5/releases/tag/v3.0)    | 47.7     | 47.7     | 66.5     | 4.4ms     | 227     || 47.8M  | 88.1B\n| [YOLOv5x](https://github.com/ultralytics/yolov5/releases/tag/v3.0)    | **49.2** | **49.2** | **67.7** | 6.9ms     | 145     || 89.0M  | 166.4B\n| | | | | | || |\n| [YOLOv5x](https://github.com/ultralytics/yolov5/releases/tag/v3.0) + TTA|**50.8**| **50.8** | **68.9** | 25.5ms    | 39      || 89.0M  | 354.3B\n| | | | | | || |\n| [YOLOv3-SPP](https://github.com/ultralytics/yolov5/releases/tag/v3.0) | 45.6     | 45.5     | 65.2     | 4.5ms     | 222     || 63.0M  | 118.0B","metadata":{"papermill":{"duration":0.064911,"end_time":"2021-01-01T09:50:19.435746","exception":false,"start_time":"2021-01-01T09:50:19.370835","status":"completed"},"tags":[]}},{"cell_type":"markdown","source":"# Selecting Models\nIn this notebok I'm using `v5s`. To select your prefered model just replace `--cfg models/yolov5s.yaml --weights yolov5s.pt` with the following command:\n* `v5s` : `--cfg models/yolov5s.yaml --weights yolov5s.pt`\n* `v5m` : `--cfg models/yolov5m.yaml --weights yolov5m.pt`\n* `v5l` : `--cfg models/yolov5l.yaml --weights yolov5l.pt`\n* `v5x` : `--cfg models/yolov5x.yaml --weights yolov5x.pt`","metadata":{"papermill":{"duration":0.064016,"end_time":"2021-01-01T09:50:19.564859","exception":false,"start_time":"2021-01-01T09:50:19.500843","status":"completed"},"tags":[]}},{"cell_type":"markdown","source":"# Train","metadata":{"papermill":{"duration":0.064553,"end_time":"2021-01-01T09:50:19.6938","exception":false,"start_time":"2021-01-01T09:50:19.629247","status":"completed"},"tags":[]}},{"cell_type":"code","source":"%%writefile /kaggle/working/hyp.scratch.yaml\n\n# Hyperparameters for COCO training from scratch\n# python train.py --batch 40 --cfg yolov5m.yaml --weights '' --data coco.yaml --img 640 --epochs 300\n# See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials\n\n\nlr0: 0.01\nlrf: 0.032\nmomentum: 0.937\nweight_decay: 0.0005\nwarmup_epochs: 3.0\nwarmup_momentum: 0.8\nwarmup_bias_lr: 0.1\nbox: 0.1\ncls: 1.0\ncls_pw: 0.5\nobj: 2.0\nobj_pw: 0.5\niou_t: 0.2\nanchor_t: 4.0\nanchors: 0\nfl_gamma: 0.0\nhsv_h: 0.015\nhsv_s: 0.7\nhsv_v: 0.4\ndegrees: 0.0\ntranslate: 0.2\nscale: 0.6\nshear: 0.0\nperspective: 0.0\nflipud: 0.2\nfliplr: 0.5\nmosaic: 1.0\nmixup: 0.0\ncopy_paste: 0.0","metadata":{"execution":{"iopub.status.busy":"2021-07-25T11:38:45.580852Z","iopub.execute_input":"2021-07-25T11:38:45.58128Z","iopub.status.idle":"2021-07-25T11:38:45.588531Z","shell.execute_reply.started":"2021-07-25T11:38:45.581242Z","shell.execute_reply":"2021-07-25T11:38:45.58736Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# !WANDB_MODE=\"dryrun\" python train.py --img 640 --batch 16 --epochs 3 --data coco128.yaml --weights yolov5s.pt --nosave --cache \n!WANDB_MODE=\"dryrun\" python train.py --img 512 --batch 24 --epochs 35 --data /kaggle/working/siim-cov19.yaml --hyp /kaggle/working/hyp.scratch.yaml --weights yolov5s6.pt --cache","metadata":{"papermill":{"duration":19916.498298,"end_time":"2021-01-01T15:22:16.289734","exception":false,"start_time":"2021-01-01T09:50:19.791436","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2021-07-25T11:38:50.348323Z","iopub.execute_input":"2021-07-25T11:38:50.348696Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"shutil.rmtree('/kaggle/working/siim-cov19')","metadata":{"papermill":{"duration":5.709202,"end_time":"2021-01-01T15:24:22.413173","exception":false,"start_time":"2021-01-01T15:24:16.703971","status":"completed"},"tags":[],"_kg_hide-input":true,"_kg_hide-output":true,"execution":{"iopub.status.busy":"2021-07-25T11:35:35.044796Z","iopub.status.idle":"2021-07-25T11:35:35.045814Z"},"trusted":true},"execution_count":null,"outputs":[]}]}