{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","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"}],"dockerImageVersionId":30699,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install torch torchvision","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2025-12-23T07:51:27.056832Z","iopub.execute_input":"2025-12-23T07:51:27.057159Z","iopub.status.idle":"2025-12-23T07:51:36.527739Z","shell.execute_reply.started":"2025-12-23T07:51:27.057122Z","shell.execute_reply":"2025-12-23T07:51:36.526688Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# important library:","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nimport os\nimport random\nfrom PIL import Image , ImageDraw \nfrom collections import Counter\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nimport torch\nimport torchvision\nfrom torchvision import transforms as T\n\nfrom torchvision.models.detection.faster_rcnn import FastRCNNPredictor\n\n","metadata":{"execution":{"iopub.status.busy":"2025-12-23T07:51:36.529573Z","iopub.execute_input":"2025-12-23T07:51:36.529889Z","iopub.status.idle":"2025-12-23T07:51:42.964271Z","shell.execute_reply.started":"2025-12-23T07:51:36.529863Z","shell.execute_reply":"2025-12-23T07:51:42.963561Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# load train data:","metadata":{}},{"cell_type":"code","source":"train = pd.read_csv(\"/kaggle/input/global-wheat-detection/train.csv\")\ntrain.head()","metadata":{"execution":{"iopub.status.busy":"2025-12-23T07:51:42.965208Z","iopub.execute_input":"2025-12-23T07:51:42.965538Z","iopub.status.idle":"2025-12-23T07:51:43.219179Z","shell.execute_reply.started":"2025-12-23T07:51:42.965519Z","shell.execute_reply":"2025-12-23T07:51:43.218320Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"- split the bbox column to x1,y1,w,h","metadata":{}},{"cell_type":"code","source":"coord = pd.DataFrame(list(train.bbox.apply(lambda x : x[1:-1].split(\",\")).values),columns=[\"x1\",\"y1\",\"w\",\"h\"])","metadata":{"execution":{"iopub.status.busy":"2025-12-23T07:51:43.221393Z","iopub.execute_input":"2025-12-23T07:51:43.221814Z","iopub.status.idle":"2025-12-23T07:51:43.546451Z","shell.execute_reply.started":"2025-12-23T07:51:43.221783Z","shell.execute_reply":"2025-12-23T07:51:43.545763Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df = pd.concat([train,coord],axis=1)","metadata":{"execution":{"iopub.status.busy":"2025-12-23T07:51:43.547332Z","iopub.execute_input":"2025-12-23T07:51:43.547571Z","iopub.status.idle":"2025-12-23T07:51:43.566832Z","shell.execute_reply.started":"2025-12-23T07:51:43.547551Z","shell.execute_reply":"2025-12-23T07:51:43.565970Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"- make the values of the columns numeric values:","metadata":{}},{"cell_type":"code","source":"df['x1']=pd.to_numeric(df['x1'])\ndf['y1']=pd.to_numeric(df['y1'])\ndf['w']=pd.to_numeric(df['w'])\ndf['h']=pd.to_numeric(df['h'])\n","metadata":{"execution":{"iopub.status.busy":"2025-12-23T07:51:43.567782Z","iopub.execute_input":"2025-12-23T07:51:43.568047Z","iopub.status.idle":"2025-12-23T07:51:43.780718Z","shell.execute_reply.started":"2025-12-23T07:51:43.568025Z","shell.execute_reply":"2025-12-23T07:51:43.780030Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"- calcualte the y2,x2 :","metadata":{}},{"cell_type":"code","source":"df['x2']=df['x1']+df['w']\ndf['y2']=df['y1']+df['h']","metadata":{"execution":{"iopub.status.busy":"2025-12-23T07:51:43.781863Z","iopub.execute_input":"2025-12-23T07:51:43.782444Z","iopub.status.idle":"2025-12-23T07:51:43.790061Z","shell.execute_reply.started":"2025-12-23T07:51:43.782412Z","shell.execute_reply":"2025-12-23T07:51:43.789400Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df","metadata":{"execution":{"iopub.status.busy":"2025-12-23T07:51:43.791055Z","iopub.execute_input":"2025-12-23T07:51:43.791280Z","iopub.status.idle":"2025-12-23T07:51:43.814868Z","shell.execute_reply.started":"2025-12-23T07:51:43.791261Z","shell.execute_reply":"2025-12-23T07:51:43.814075Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"- Drop unneeded column:","metadata":{}},{"cell_type":"code","source":"df.drop(['bbox','width','height','w','h','source'],axis=1,inplace=True)","metadata":{"execution":{"iopub.status.busy":"2025-12-23T07:51:43.815892Z","iopub.execute_input":"2025-12-23T07:51:43.816180Z","iopub.status.idle":"2025-12-23T07:51:43.832364Z","shell.execute_reply.started":"2025-12-23T07:51:43.816151Z","shell.execute_reply":"2025-12-23T07:51:43.831462Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.head()","metadata":{"execution":{"iopub.status.busy":"2025-12-23T07:51:43.834966Z","iopub.execute_input":"2025-12-23T07:51:43.835204Z","iopub.status.idle":"2025-12-23T07:51:43.844739Z","shell.execute_reply.started":"2025-12-23T07:51:43.835185Z","shell.execute_reply":"2025-12-23T07:51:43.843959Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"- Take the unique ids of the images:","metadata":{}},{"cell_type":"code","source":"unique_imgs=df.image_id.unique()\nunique_imgs","metadata":{"execution":{"iopub.status.busy":"2025-12-23T07:51:43.845733Z","iopub.execute_input":"2025-12-23T07:51:43.846053Z","iopub.status.idle":"2025-12-23T07:51:43.866267Z","shell.execute_reply.started":"2025-12-23T07:51:43.846024Z","shell.execute_reply":"2025-12-23T07:51:43.865417Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"- Make custom class for preparing the data:","metadata":{}},{"cell_type":"code","source":"class custDat(torch.utils.data.Dataset):\n    def __init__(self, df, unique_imgs, indices):\n        self.df = df\n        self.unique_imgs = unique_imgs\n        self.indices = indices\n    \n    def __len__(self):\n        return len(self.indices)\n    \n    def __getitem__(self, idx):\n        image_name = self.unique_imgs[self.indices[idx]]\n        boxes = self.df[self.df.image_id == image_name].values[:, 1:].astype(\"float\")\n        img = Image.open(\"../input/global-wheat-detection/train/\" + image_name + \".jpg\").convert('RGB')\n        labels = torch.ones(boxes.shape[0], dtype=torch.int64)\n        target = {}\n        target[\"boxes\"] = torch.tensor(boxes)\n        target[\"label\"] = labels\n        return T.ToTensor()(img), target\n","metadata":{"execution":{"iopub.status.busy":"2025-12-23T07:51:43.867207Z","iopub.execute_input":"2025-12-23T07:51:43.867399Z","iopub.status.idle":"2025-12-23T07:51:43.875823Z","shell.execute_reply.started":"2025-12-23T07:51:43.867383Z","shell.execute_reply":"2025-12-23T07:51:43.875138Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# spit the data int train and validation:","metadata":{}},{"cell_type":"code","source":"train_inds , val_inds =train_test_split(range(unique_imgs.shape[0]),test_size=0.1)","metadata":{"execution":{"iopub.status.busy":"2025-12-23T07:51:43.876690Z","iopub.execute_input":"2025-12-23T07:51:43.876891Z","iopub.status.idle":"2025-12-23T07:51:43.886935Z","shell.execute_reply.started":"2025-12-23T07:51:43.876874Z","shell.execute_reply":"2025-12-23T07:51:43.886330Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def custom_collate(data):\n    return data","metadata":{"execution":{"iopub.status.busy":"2025-12-23T07:51:43.887734Z","iopub.execute_input":"2025-12-23T07:51:43.887961Z","iopub.status.idle":"2025-12-23T07:51:43.895823Z","shell.execute_reply.started":"2025-12-23T07:51:43.887942Z","shell.execute_reply":"2025-12-23T07:51:43.895120Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Call the data loader to prepare it to the model:","metadata":{}},{"cell_type":"code","source":"train_dl = torch.utils.data.DataLoader(custDat(df,unique_imgs,train_inds),batch_size=16,shuffle=True,collate_fn=custom_collate,pin_memory=True if torch.cuda.is_available() else False)\nval_dl = torch.utils.data.DataLoader(custDat(df,unique_imgs,val_inds),batch_size=8,shuffle=True,collate_fn=custom_collate,pin_memory=True if torch.cuda.is_available() else False)\n","metadata":{"execution":{"iopub.status.busy":"2025-12-23T07:51:43.896667Z","iopub.execute_input":"2025-12-23T07:51:43.896908Z","iopub.status.idle":"2025-12-23T07:51:43.936894Z","shell.execute_reply.started":"2025-12-23T07:51:43.896890Z","shell.execute_reply":"2025-12-23T07:51:43.936012Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Modeling:","metadata":{}},{"cell_type":"code","source":"model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)\nnum_classes=2\nin_features=model.roi_heads.box_predictor.cls_score.in_features\nmodel.roi_heads.box_predictor =  FastRCNNPredictor(in_features,num_classes)","metadata":{"execution":{"iopub.status.busy":"2025-12-23T07:51:43.937858Z","iopub.execute_input":"2025-12-23T07:51:43.938103Z","iopub.status.idle":"2025-12-23T07:51:45.856117Z","shell.execute_reply.started":"2025-12-23T07:51:43.938083Z","shell.execute_reply":"2025-12-23T07:51:45.855361Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')","metadata":{"execution":{"iopub.status.busy":"2025-12-23T07:51:45.857330Z","iopub.execute_input":"2025-12-23T07:51:45.857738Z","iopub.status.idle":"2025-12-23T07:51:45.862187Z","shell.execute_reply.started":"2025-12-23T07:51:45.857693Z","shell.execute_reply":"2025-12-23T07:51:45.861410Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"device","metadata":{"execution":{"iopub.status.busy":"2025-12-23T07:51:45.863187Z","iopub.execute_input":"2025-12-23T07:51:45.863390Z","iopub.status.idle":"2025-12-23T07:51:45.875265Z","shell.execute_reply.started":"2025-12-23T07:51:45.863373Z","shell.execute_reply":"2025-12-23T07:51:45.874574Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"optimizer = torch.optim.SGD(model.parameters(),lr=0.001,momentum=0.9,weight_decay=0.005)\nnum_epochs=10","metadata":{"execution":{"iopub.status.busy":"2025-12-23T07:51:45.876239Z","iopub.execute_input":"2025-12-23T07:51:45.876498Z","iopub.status.idle":"2025-12-23T07:51:45.885055Z","shell.execute_reply.started":"2025-12-23T07:51:45.876478Z","shell.execute_reply":"2025-12-23T07:51:45.884311Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# train the model with 5 epochs and prin the loss:","metadata":{}},{"cell_type":"code","source":"model.to(device)\nfor epochs in range (num_epochs):\n    epoch_loss = 0\n    for data in tqdm(train_dl):\n        imgs=[]\n        targets = []\n        for d in data :\n            imgs.append(d[0].to(device))\n            targ = {}\n            targ['boxes']=d[1]['boxes'].to(device)\n            targ['labels']=d[1]['label'].to(device)\n            targets.append(targ)\n        loss_dict = model(imgs,targets)\n        loss= sum(v for v in loss_dict.values())\n        epoch_loss += loss.cpu().detach().numpy()\n        optimizer.zero_grad()\n        loss.backward()\n        optimizer.step()\n    print(epoch_loss) \n            \n            ","metadata":{"execution":{"iopub.status.busy":"2025-12-23T07:51:45.886143Z","iopub.execute_input":"2025-12-23T07:51:45.886390Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Evaluate the model","metadata":{}},{"cell_type":"code","source":"model.eval()\ndata = iter(val_dl).__next__()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"img= data[0][0]\nboxes=data[0][1]['boxes']\nlabels=data[0][1]['label']","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"output = model([img.to(device)])","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# output os the evaluation:","metadata":{}},{"cell_type":"code","source":"output","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"out_bbox=output[0]['boxes']\nout_scores=output[0]['scores']","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"keep = torchvision.ops.nms(out_bbox,out_scores,0.45)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"out_bbox.shape , keep.shape","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# prediction detection:","metadata":{}},{"cell_type":"code","source":"im = (img.permute(1,2,0).cpu().detach().numpy()*255).astype('uint8')\nim","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"vsample = Image.fromarray(im)\ndraw = ImageDraw.Draw(vsample)\nfor box in boxes :\n    draw.rectangle(list(box),fill=None,outline='red')\nvsample","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# if you like it please upvote....","metadata":{}},{"cell_type":"code","source":"# Save the model state\ntorch.save(model.state_dict(), 'modified_fasterrcnn_resnet50_fpn.pth')\n","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}