{"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":19989,"databundleVersionId":1160143,"sourceType":"competition"},{"sourceId":6063590,"sourceType":"datasetVersion","datasetId":3470137},{"sourceId":7210148,"sourceType":"datasetVersion","datasetId":4116260},{"sourceId":8438567,"sourceType":"datasetVersion","datasetId":5026588}],"dockerImageVersionId":30588,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"## Previous Training method\n\n1. coco_dataset: https://www.kaggle.com/code/ishlove7/how-to-make-coco-dataset \n2. MM Detection FasterRCNN[Training] : https://www.kaggle.com/code/ishlove7/mm-detection-faster-rcnn-train\n3. MM Detection Resnext + CascadeRNN[Training] : https://www.kaggle.com/code/ishlove7/mm-detection-resnext-101-cascadercnn-training\n4. MM Detection Convnext + CascadeRCNN[Training] : https://www.kaggle.com/code/ishlove7/global-wheat-detection-convnext-cascadercnn\n5. MM Detection Submission[Infer] : https://www.kaggle.com/code/ishlove7/wheat-detection-inference-tta-wbf/notebook?scriptVersionId=178769791","metadata":{}},{"cell_type":"markdown","source":"## Install Package","metadata":{}},{"cell_type":"code","source":"from IPython.display import clear_output\n\n!pip install --no-index --no-deps /kaggle/input/mmdetectron-31-wheel/pycocotools-2.0.6-cp310-cp310-linux_x86_64.whl\n!pip install --no-index --no-deps /kaggle/input/mmdetectron-31-wheel/torch-1.12.1+cu116-cp310-cp310-linux_x86_64.whl\n!pip install --no-index --no-deps /kaggle/input/mmdetectron-31-wheel/torchvision-0.13.1+cu116-cp310-cp310-linux_x86_64.whl\n!pip install --no-index --no-deps /kaggle/input/mmdetectron-31-wheel/mmcv-2.0.1-cp310-cp310-manylinux1_x86_64.whl \n!pip install --no-index --no-deps /kaggle/input/mmdetectron-31-wheel/openmim-0.3.9-py2.py3-none-any.whl\n!pip install --no-index --no-deps /kaggle/input/mmdetectron-31-wheel/mmengine-0.7.4-py3-none-any.whl\n!pip install --no-index --no-deps /kaggle/input/mmdetectron-31-wheel/addict-2.4.0-py3-none-any.whl\n!pip install yapf==0.40.1\n\nclear_output()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Importing the required pakages","metadata":{}},{"cell_type":"code","source":"from tqdm.notebook import tqdm\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\nfrom glob import glob\nimport matplotlib.pyplot as plt","metadata":{"execution":{"iopub.status.busy":"2024-05-18T13:49:24.673503Z","iopub.execute_input":"2024-05-18T13:49:24.673822Z","iopub.status.idle":"2024-05-18T13:49:25.117633Z","shell.execute_reply.started":"2024-05-18T13:49:24.673791Z","shell.execute_reply":"2024-05-18T13:49:25.115898Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!git clone -bv3.1.0 https://github.com/open-mmlab/mmdetection.git\n%cd /kaggle/working/mmdetection\n!pip install -v -e .\n\nclear_output()","metadata":{"execution":{"iopub.status.busy":"2024-05-18T13:49:25.118975Z","iopub.execute_input":"2024-05-18T13:49:25.119450Z","iopub.status.idle":"2024-05-18T13:49:54.197691Z","shell.execute_reply.started":"2024-05-18T13:49:25.119415Z","shell.execute_reply":"2024-05-18T13:49:54.196408Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch, torchvision,mmdet\nprint(\"PyTorch version= \",torch.__version__,torch.cuda.is_available())\nprint(\"mmdet version= \",mmdet.__version__)\n\nfrom mmcv.ops import get_compiling_cuda_version\nprint(\"THE CUDA version \", get_compiling_cuda_version())","metadata":{"execution":{"iopub.status.busy":"2024-05-18T13:49:54.200639Z","iopub.execute_input":"2024-05-18T13:49:54.201046Z","iopub.status.idle":"2024-05-18T13:49:56.359724Z","shell.execute_reply.started":"2024-05-18T13:49:54.201007Z","shell.execute_reply":"2024-05-18T13:49:56.358672Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install -U openmim\nclear_output()","metadata":{"execution":{"iopub.status.busy":"2024-05-18T13:49:56.360838Z","iopub.execute_input":"2024-05-18T13:49:56.361301Z","iopub.status.idle":"2024-05-18T13:50:26.655332Z","shell.execute_reply.started":"2024-05-18T13:49:56.361272Z","shell.execute_reply":"2024-05-18T13:50:26.654241Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!mkdir -p configs/wheat","metadata":{"execution":{"iopub.status.busy":"2024-05-18T13:50:26.657097Z","iopub.execute_input":"2024-05-18T13:50:26.657895Z","iopub.status.idle":"2024-05-18T13:50:27.661692Z","shell.execute_reply.started":"2024-05-18T13:50:26.657852Z","shell.execute_reply":"2024-05-18T13:50:27.660429Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%writefile configs/wheat/custom_config.py\n\n_base_ = '/kaggle/working/mmdetection/configs/cascade_rcnn/cascade-rcnn_x101-32x4d_fpn_20e_coco.py'\nmodel = dict(\n    roi_head=dict(\n         bbox_head=[\n             dict(\n                type='Shared2FCBBoxHead',\n                in_channels=256,\n                fc_out_channels=1024,\n                roi_feat_size=7,\n                num_classes=1,\n                bbox_coder=dict(\n                    type='DeltaXYWHBBoxCoder',\n                    target_means=[0., 0., 0., 0.],\n                    target_stds=[0.1, 0.1, 0.2, 0.2]),\n                reg_class_agnostic=True,\n                loss_cls=dict(\n                    type='CrossEntropyLoss',\n                    use_sigmoid=False,\n                    loss_weight=1.0),\n                loss_bbox=dict(type='SmoothL1Loss', beta=1.0,\n                               loss_weight=1.0)),\n            dict(\n                type='Shared2FCBBoxHead',\n                in_channels=256,\n                fc_out_channels=1024,\n                roi_feat_size=7,\n                num_classes=1,\n                bbox_coder=dict(\n                    type='DeltaXYWHBBoxCoder',\n                    target_means=[0., 0., 0., 0.],\n                    target_stds=[0.05, 0.05, 0.1, 0.1]),\n                reg_class_agnostic=True,\n                loss_cls=dict(\n                    type='CrossEntropyLoss',\n                    use_sigmoid=False,\n                    loss_weight=1.0),\n                loss_bbox=dict(type='SmoothL1Loss', beta=1.0,\n                               loss_weight=1.0)),\n            dict(\n                type='Shared2FCBBoxHead',\n                in_channels=256,\n                fc_out_channels=1024,\n                roi_feat_size=7,\n                num_classes=1,\n                bbox_coder=dict(\n                    type='DeltaXYWHBBoxCoder',\n                    target_means=[0., 0., 0., 0.],\n                    target_stds=[0.033, 0.033, 0.067, 0.067]),\n                reg_class_agnostic=True,\n                loss_cls=dict(\n                    type='CrossEntropyLoss',\n                    use_sigmoid=False,\n                    loss_weight=1.0),\n                loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0))\n            ]\n    )\n)\n            \n\nclasses = ('wheat',) # Added\nbackend_args = None\ndata_root = '/kaggle/input/wheat-data/' # Modified\ntrain_cfg = dict(type='EpochBasedTrainLoop', max_epochs=12, val_interval=1)\nval_cfg = dict(type='ValLoop')\ntest_cfg = dict(type='TestLoop')\n\n\nparam_scheduler = [\n    dict(type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500),\n    dict(\n        type='MultiStepLR',\n        begin=0,\n        end=12,\n        by_epoch=True,\n        milestones=[8, 11],\n        gamma=0.1)\n]\n\n\n\ntrain_pipeline = [\n    dict(type='LoadImageFromFile', backend_args=backend_args),\n    dict(type='LoadAnnotations', with_bbox=True),\n    dict(type='Resize', scale=(1024, 1024), keep_ratio=True),\n    dict(type='RandomFlip', prob=0.5),\n    dict(type='PhotoMetricDistortion',\n         brightness_delta=32, contrast_range=(0.5, 1.5),\n         saturation_range=(0.5, 1.5), hue_delta=18),\n    dict(type='PackDetInputs')\n]\ntest_pipeline = [\n    dict(type='LoadImageFromFile', backend_args=backend_args),\n    dict(type='Resize', scale=(1024, 1024), keep_ratio=True),\n    # If you don't have a gt annotation, delete the pipeline\n    dict(type='LoadAnnotations', with_bbox=True),\n    dict(\n        type='PackDetInputs',\n        meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape',\n                   'scale_factor'))\n]\ntrain_dataloader = dict(\n    batch_size=4,\n    num_workers=2,\n    persistent_workers=True,\n    dataset=dict(\n        type='CocoDataset',\n        data_root=data_root,\n        metainfo=dict(classes=classes),\n        ann_file=data_root + 'annotations_train.json',\n        data_prefix=dict(img='train2017/'),\n        pipeline=train_pipeline,\n        backend_args=backend_args))\nval_dataloader = dict(\n    batch_size=4,\n    num_workers=2,\n    persistent_workers=True,\n    drop_last=False,\n    dataset=dict(\n        type='CocoDataset',\n        data_root=data_root,\n        metainfo=dict(classes=classes),\n        ann_file=data_root + 'annotations_valid.json',\n        data_prefix=dict(img='valid2017/'),\n        test_mode=True,\n        pipeline=test_pipeline,\n        backend_args=backend_args))\ntest_dataloader = val_dataloader\n\ntest_cfg=dict(\n        rpn=dict(\n            nms_pre=1000,\n            max_per_img=1000,\n            nms=dict(type='nms', iou_threshold=0.7),\n            min_bbox_size=0),\n        rcnn=dict(\n            score_thr=0.05,\n            nms=dict(type='soft_nms', iou_threshold=0.5),\n            max_per_img=100)\n        # soft-nms is also supported for rcnn testing\n        # e.g., nms=dict(type='soft_nms', iou_threshold=0.5, min_score=0.05)\n    )\n\nval_evaluator = dict(\nann_file=data_root + 'annotations_valid.json', metric=['bbox'])\nload_from='https://download.openmmlab.com/mmdetection/v2.0/cascade_rcnn/cascade_rcnn_x101_32x4d_fpn_20e_coco/cascade_rcnn_x101_32x4d_fpn_20e_coco_20200906_134608-9ae0a720.pth'\ntest_evaluator = val_evaluator\nresume_from = None","metadata":{"execution":{"iopub.status.busy":"2024-05-18T14:05:37.993172Z","iopub.execute_input":"2024-05-18T14:05:37.993700Z","iopub.status.idle":"2024-05-18T14:05:38.008635Z","shell.execute_reply.started":"2024-05-18T14:05:37.993647Z","shell.execute_reply":"2024-05-18T14:05:38.007547Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!python tools/train.py /kaggle/working/mmdetection/configs/wheat/custom_config.py","metadata":{"execution":{"iopub.status.busy":"2024-05-18T14:05:38.560767Z","iopub.execute_input":"2024-05-18T14:05:38.561495Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}