{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.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":31089,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"## 1. order libraries","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np \nimport os  \nimport re \nfrom PIL import Image \n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:01:46.873877Z","iopub.execute_input":"2025-10-03T18:01:46.874630Z","iopub.status.idle":"2025-10-03T18:01:46.879990Z","shell.execute_reply.started":"2025-10-03T18:01:46.874581Z","shell.execute_reply":"2025-10-03T18:01:46.879078Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_df = pd.read_csv('/kaggle/input/global-wheat-detection/train.csv')\ntrain_df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:01:46.906993Z","iopub.execute_input":"2025-10-03T18:01:46.907652Z","iopub.status.idle":"2025-10-03T18:01:47.100866Z","shell.execute_reply.started":"2025-10-03T18:01:46.907630Z","shell.execute_reply":"2025-10-03T18:01:47.100167Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_df.info()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:01:47.102082Z","iopub.execute_input":"2025-10-03T18:01:47.102285Z","iopub.status.idle":"2025-10-03T18:01:47.135656Z","shell.execute_reply.started":"2025-10-03T18:01:47.102270Z","shell.execute_reply":"2025-10-03T18:01:47.134926Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:01:47.136670Z","iopub.execute_input":"2025-10-03T18:01:47.136956Z","iopub.status.idle":"2025-10-03T18:01:47.146143Z","shell.execute_reply.started":"2025-10-03T18:01:47.136935Z","shell.execute_reply":"2025-10-03T18:01:47.145368Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_df['x'] = -1\ntrain_df['y'] = -1\ntrain_df['w'] = -1 \ntrain_df['h'] = -1","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:01:47.147597Z","iopub.execute_input":"2025-10-03T18:01:47.147842Z","iopub.status.idle":"2025-10-03T18:01:47.160035Z","shell.execute_reply.started":"2025-10-03T18:01:47.147825Z","shell.execute_reply":"2025-10-03T18:01:47.159302Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def expand_bbox(x):\n    r = np.array(re.findall('([0-9]+[.]?[0-9]*)',x)) \n    if len(r) == 0:        \n        r = [-1,-1,-1,-1] \n    return r\ntrain_df[['x','y','w','h']] = np.stack(train_df['bbox'].apply(lambda x:expand_bbox(x)))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:01:47.160990Z","iopub.execute_input":"2025-10-03T18:01:47.161604Z","iopub.status.idle":"2025-10-03T18:01:47.991568Z","shell.execute_reply.started":"2025-10-03T18:01:47.161580Z","shell.execute_reply":"2025-10-03T18:01:47.990713Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_df['x'] = train_df['x'].astype(np.float64) \ntrain_df['y'] = train_df['y'].astype(np.float64) \ntrain_df['w'] = train_df['w'].astype(np.float64)\ntrain_df['h'] = train_df['h'].astype(np.float64)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:01:47.992370Z","iopub.execute_input":"2025-10-03T18:01:47.992664Z","iopub.status.idle":"2025-10-03T18:01:48.065870Z","shell.execute_reply.started":"2025-10-03T18:01:47.992638Z","shell.execute_reply":"2025-10-03T18:01:48.065338Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_df = train_df.drop('bbox',axis = 1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:01:48.066854Z","iopub.execute_input":"2025-10-03T18:01:48.067124Z","iopub.status.idle":"2025-10-03T18:01:48.075286Z","shell.execute_reply.started":"2025-10-03T18:01:48.067101Z","shell.execute_reply":"2025-10-03T18:01:48.074515Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 2. model sklearn ","metadata":{}},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:01:48.076097Z","iopub.execute_input":"2025-10-03T18:01:48.076811Z","iopub.status.idle":"2025-10-03T18:01:48.081033Z","shell.execute_reply.started":"2025-10-03T18:01:48.076787Z","shell.execute_reply":"2025-10-03T18:01:48.080264Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_ids  , valid_ids = train_test_split(train_df , test_size  = 0.08,random_state = 42 , shuffle = True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:01:48.081847Z","iopub.execute_input":"2025-10-03T18:01:48.082257Z","iopub.status.idle":"2025-10-03T18:01:48.113009Z","shell.execute_reply.started":"2025-10-03T18:01:48.082239Z","shell.execute_reply":"2025-10-03T18:01:48.112268Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_ids.shape , valid_ids.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:01:48.115577Z","iopub.execute_input":"2025-10-03T18:01:48.115785Z","iopub.status.idle":"2025-10-03T18:01:48.120644Z","shell.execute_reply.started":"2025-10-03T18:01:48.115770Z","shell.execute_reply":"2025-10-03T18:01:48.120035Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from torch.utils.data import DataLoader , Dataset\nimport albumentations as A\n\nfrom albumentations.pytorch.transforms import ToTensorV2\nfrom albumentations.pytorch.transforms import ToTensorV2\nfrom torchvision.models.detection.faster_rcnn import FastRCNNPredictor\nfrom torchvision.models.detection import FasterRCNN\nfrom torchvision.models.detection.rpn import AnchorGenerator\nimport torchvision\nimport cv2\nimport torch","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:01:48.121394Z","iopub.execute_input":"2025-10-03T18:01:48.121885Z","iopub.status.idle":"2025-10-03T18:01:48.135632Z","shell.execute_reply.started":"2025-10-03T18:01:48.121860Z","shell.execute_reply":"2025-10-03T18:01:48.134944Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 3.torch dataset\n## this function for download with __init__ , len used to of check the number pictures, getitem ordering images and update ","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n\n\nclass sDataset(torch.utils.data.Dataset):\n    def __init__(self, dataframe, image_dir, transforms=None):\n        super().__init__()\n        \n        self.image_ids = dataframe['image_id'].unique()\n        self.df = dataframe\n        self.image_dir = image_dir\n        self.transforms = transforms\n\n#-------------------------------------------------------------------------\n    \n    def __len__(self):\n      \n        return self.image_ids.shape[0]\n\n#-------------------------------------------------------------------------\n    \n    def __getitem__(self, index: int):\n        \n        \n        image_id = self.image_ids[index]\n        records = self.df[self.df['image_id'] == image_id]\n        \n        # 2. قراءة الصورة\n        image_path = os.path.join(self.image_dir, f'{image_id}.jpg') \n        image = cv2.imread(image_path, cv2.IMREAD_COLOR)\n        \n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB).astype(np.float32) \n        image /= 255.0 \n\n       \n       \n        boxes = records[['x', 'y', 'w', 'h']].values \n        \n        \n        boxes[:, 2] = boxes[:, 0] + boxes[:, 2] # x_max = x + w\n        boxes[:, 3] = boxes[:, 1] + boxes[:, 3] # y_max = y + h\n        \n        \n        \n       \n        boxes = torch.as_tensor(boxes, dtype=torch.float32)\n        labels = torch.ones(len(records), dtype=torch.int64)\n        iscrowd = torch.zeros(len(records), dtype=torch.int64)\n        \n        # 5. تجميع بيانات Target\n        target = {}\n        target['boxes'] = boxes\n        target['labels'] = labels\n        target['image_id'] = torch.tensor([index]) \n        target['iscrowd'] = iscrowd\n       \n        if self.transforms:\n   \n             sample = {\n                'image': image,\n                'boxes': target['boxes'].tolist(),  \n                'labels': labels.tolist(),         \n                'shape': image.shape               \n        }\n    \n       \n    \n             sample = self.transforms(**sample) \n    \n    \n             image = sample['image']\n            \n            \n              \n            \n            \n       \n        return image, target, image_id","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:01:48.136404Z","iopub.execute_input":"2025-10-03T18:01:48.136623Z","iopub.status.idle":"2025-10-03T18:01:48.149983Z","shell.execute_reply.started":"2025-10-03T18:01:48.136599Z","shell.execute_reply":"2025-10-03T18:01:48.149253Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# ToTensorV2 is strengthening computer vision","metadata":{}},{"cell_type":"code","source":"def get_train():\n    return A.Compose([\n        A.HorizontalFlip(0.5),\n        ToTensorV2(p = 1.0)\n    ],bbox_params = {'format':'pascal_voc','label_fields':['labels']}) \ndef get_valid():\n    return A.Compose([\n        ToTensorV2(p =1.0)\n        \n    ],bbox_params={'format':'pascal_voc','label_fields':['labels']})","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:01:48.150718Z","iopub.execute_input":"2025-10-03T18:01:48.150910Z","iopub.status.idle":"2025-10-03T18:01:48.166945Z","shell.execute_reply.started":"2025-10-03T18:01:48.150895Z","shell.execute_reply":"2025-10-03T18:01:48.166248Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 4. download model","metadata":{}},{"cell_type":"code","source":"model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained  = True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:01:48.167676Z","iopub.execute_input":"2025-10-03T18:01:48.167884Z","iopub.status.idle":"2025-10-03T18:02:08.906566Z","shell.execute_reply.started":"2025-10-03T18:01:48.167861Z","shell.execute_reply":"2025-10-03T18:02:08.905983Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"num_classes = 2 \n\nin_features = model.roi_heads.box_predictor.cls_score.in_features\n\nmodel.roi_heads.box_predictor = FastRCNNPredictor(in_features , num_classes)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:02:08.907412Z","iopub.execute_input":"2025-10-03T18:02:08.908055Z","iopub.status.idle":"2025-10-03T18:02:08.912353Z","shell.execute_reply.started":"2025-10-03T18:02:08.908028Z","shell.execute_reply":"2025-10-03T18:02:08.911767Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## let's  mix the data on the dataset's function and target batch","metadata":{}},{"cell_type":"code","source":"\nDIR_TRAIN ='/kaggle/input/global-wheat-detection/train' \nDIR_TEST = '/kaggle/input/global-wheat-detection/test'\ntrain_dataset = sDataset(train_df, DIR_TRAIN, get_train())\nvalid_dataset = sDataset(valid_ids, DIR_TRAIN, get_valid())\n\n\n\ndef collate_fn(batch):\n    return tuple(zip(*batch))\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:02:08.913120Z","iopub.execute_input":"2025-10-03T18:02:08.913329Z","iopub.status.idle":"2025-10-03T18:02:08.940231Z","shell.execute_reply.started":"2025-10-03T18:02:08.913308Z","shell.execute_reply":"2025-10-03T18:02:08.939692Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 5. training targeting wheat and validating wheat. ","metadata":{}},{"cell_type":"code","source":"train_data_loader  = DataLoader(\n    train_dataset,\n    batch_size = 8,\n    shuffle = False,\n    num_workers =4,\n    collate_fn = collate_fn\n)\nvalid_data_loader = DataLoader(\n    valid_dataset,\n    batch_size = 16,\n    shuffle = False,\n    num_workers = 4,\n    collate_fn = collate_fn\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:02:08.940946Z","iopub.execute_input":"2025-10-03T18:02:08.941421Z","iopub.status.idle":"2025-10-03T18:02:08.946116Z","shell.execute_reply.started":"2025-10-03T18:02:08.941397Z","shell.execute_reply":"2025-10-03T18:02:08.945414Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 6. plot model wheat","metadata":{}},{"cell_type":"code","source":"device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:02:08.946885Z","iopub.execute_input":"2025-10-03T18:02:08.947122Z","iopub.status.idle":"2025-10-03T18:02:08.958338Z","shell.execute_reply.started":"2025-10-03T18:02:08.947106Z","shell.execute_reply":"2025-10-03T18:02:08.957694Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images ,image_ids  , target= next(iter(train_data_loader))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:02:08.959160Z","iopub.execute_input":"2025-10-03T18:02:08.959345Z","iopub.status.idle":"2025-10-03T18:02:10.221361Z","shell.execute_reply.started":"2025-10-03T18:02:08.959329Z","shell.execute_reply":"2025-10-03T18:02:10.220404Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images = list(image.to(device) for image in images)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:02:10.222762Z","iopub.execute_input":"2025-10-03T18:02:10.223888Z","iopub.status.idle":"2025-10-03T18:02:10.284626Z","shell.execute_reply.started":"2025-10-03T18:02:10.223846Z","shell.execute_reply":"2025-10-03T18:02:10.284075Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"targets = [{k: v.to(device) for k, v in t.items()} for t in image_ids]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:02:10.285376Z","iopub.execute_input":"2025-10-03T18:02:10.285609Z","iopub.status.idle":"2025-10-03T18:02:10.290404Z","shell.execute_reply.started":"2025-10-03T18:02:10.285592Z","shell.execute_reply":"2025-10-03T18:02:10.289875Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"boxes = targets[2]['boxes'].cpu().numpy().astype(np.int32)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:02:10.291040Z","iopub.execute_input":"2025-10-03T18:02:10.291217Z","iopub.status.idle":"2025-10-03T18:02:10.302372Z","shell.execute_reply.started":"2025-10-03T18:02:10.291203Z","shell.execute_reply":"2025-10-03T18:02:10.301836Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sample = images[2].permute(1,2,0).cpu().numpy()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:02:10.303064Z","iopub.execute_input":"2025-10-03T18:02:10.303307Z","iopub.status.idle":"2025-10-03T18:02:10.332452Z","shell.execute_reply.started":"2025-10-03T18:02:10.303282Z","shell.execute_reply":"2025-10-03T18:02:10.331883Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:02:10.333083Z","iopub.execute_input":"2025-10-03T18:02:10.333241Z","iopub.status.idle":"2025-10-03T18:02:10.336308Z","shell.execute_reply.started":"2025-10-03T18:02:10.333228Z","shell.execute_reply":"2025-10-03T18:02:10.335800Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"fig , ax=plt.subplots(1, 1, figsize=(16, 8))\n\nfor box in boxes:\n    cv2.rectangle(sample,\n                  (box[0], box[1]),\n                  (box[2], box[3]),\n                  (220, 0, 0), 3)\n    \n\nax.imshow(sample)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:02:10.336964Z","iopub.execute_input":"2025-10-03T18:02:10.337509Z","iopub.status.idle":"2025-10-03T18:02:11.025830Z","shell.execute_reply.started":"2025-10-03T18:02:10.337490Z","shell.execute_reply":"2025-10-03T18:02:11.024893Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 7. Build a model torch for the wheat model","metadata":{}},{"cell_type":"code","source":"model.to(device)\nparams = [p for p in model.parameters() if p.requires_grad]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:02:11.026703Z","iopub.execute_input":"2025-10-03T18:02:11.026935Z","iopub.status.idle":"2025-10-03T18:02:11.088482Z","shell.execute_reply.started":"2025-10-03T18:02:11.026917Z","shell.execute_reply":"2025-10-03T18:02:11.087909Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"optimizer = torch.optim.SGD(params , lr = 0.005 , momentum = 0.9 , weight_decay = 0.0005) \nlr_scheduler = None\nnum_epochs = 2","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:02:11.089461Z","iopub.execute_input":"2025-10-03T18:02:11.089720Z","iopub.status.idle":"2025-10-03T18:02:11.093804Z","shell.execute_reply.started":"2025-10-03T18:02:11.089691Z","shell.execute_reply":"2025-10-03T18:02:11.093049Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(images[0].size) \nprint(targets[0])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:02:11.097121Z","iopub.execute_input":"2025-10-03T18:02:11.097723Z","iopub.status.idle":"2025-10-03T18:02:11.122196Z","shell.execute_reply.started":"2025-10-03T18:02:11.097706Z","shell.execute_reply":"2025-10-03T18:02:11.121644Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# write the code that calculates the image loss and final loss score","metadata":{}},{"cell_type":"code","source":"class Averager:\n    def __init__(self):\n        self.current_total = 0.0\n        self.iterations = 0.0\n\n    def send(self, value):\n        self.current_total += value\n        self.iterations += 1\n\n    @property\n    def value(self):\n        if self.iterations == 0:\n            return 0\n        else:\n            return 1.0 * self.current_total / self.iterations\n\n    def reset(self):\n        self.current_total = 0.0\n        self.iterations = 0.0\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:02:11.122789Z","iopub.execute_input":"2025-10-03T18:02:11.122982Z","iopub.status.idle":"2025-10-03T18:02:11.127680Z","shell.execute_reply.started":"2025-10-03T18:02:11.122968Z","shell.execute_reply":"2025-10-03T18:02:11.126916Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# let's predict the model","metadata":{}},{"cell_type":"code","source":"loss_hist = Averager()\nitr = 1    \n\nfor epoch in range(num_epochs):\n    loss_hist.reset() \n\n    for images , targets , images_ids in train_data_loader:\n\n        \n        \n        images = list(image.to(device) for image in images)\n        targets = [{k: v.to(device) for k, v in t.items()} for t in targets]\n\n        loss_dict = model(images, targets)\n\n        losses = sum(loss for loss in loss_dict.values())\n        loss_value = losses.item()\n        loss_hist.send(loss_value) \n\n        optimizer.zero_grad() \n        losses.backward() \n        optimizer.step() \n        if itr % 50 == 0:\n            print(f'iteration #(itr) loss:{loss_value}') \n        itr += 1\n\n    if lr_scheduler is not None:\n        lr_scheduler.step()\n    print(f'ecpoch {epoch} loss {loss_hist.value}')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:10:23.207150Z","iopub.execute_input":"2025-10-03T18:10:23.207852Z","iopub.status.idle":"2025-10-03T18:22:24.228665Z","shell.execute_reply.started":"2025-10-03T18:10:23.207825Z","shell.execute_reply":"2025-10-03T18:22:24.227811Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images , targets , image_ids = next(iter(valid_data_loader))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:23:20.963510Z","iopub.execute_input":"2025-10-03T18:23:20.964374Z","iopub.status.idle":"2025-10-03T18:23:22.454013Z","shell.execute_reply.started":"2025-10-03T18:23:20.964339Z","shell.execute_reply":"2025-10-03T18:23:22.453151Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images = list(img.to(device) for img in images) \ntargets = [{k: v.to(device)for k , v in t.items()} for t in targets] \n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:24:38.040812Z","iopub.execute_input":"2025-10-03T18:24:38.041509Z","iopub.status.idle":"2025-10-03T18:24:38.161712Z","shell.execute_reply.started":"2025-10-03T18:24:38.041474Z","shell.execute_reply":"2025-10-03T18:24:38.161034Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"boxes = targets[1]['boxes'].cpu().numpy().astype(np.int32) \n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:25:26.259974Z","iopub.execute_input":"2025-10-03T18:25:26.260606Z","iopub.status.idle":"2025-10-03T18:25:26.264582Z","shell.execute_reply.started":"2025-10-03T18:25:26.260584Z","shell.execute_reply":"2025-10-03T18:25:26.263686Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sample = images[1].permute(1,2,0).cpu().numpy()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:25:52.854863Z","iopub.execute_input":"2025-10-03T18:25:52.855682Z","iopub.status.idle":"2025-10-03T18:25:52.868955Z","shell.execute_reply.started":"2025-10-03T18:25:52.855644Z","shell.execute_reply":"2025-10-03T18:25:52.868221Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"fig , ax = plt.subplots(1,1,figsize = (16,8)) \nfor box in boxes:\n    cv2.rectangle(sample,\n                 (box[0],box[1]),\n                  (box[2],box[3]),\n                  (50,0,0),5)\nax.imshow(sample)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:28:44.586052Z","iopub.execute_input":"2025-10-03T18:28:44.586917Z","iopub.status.idle":"2025-10-03T18:28:45.201874Z","shell.execute_reply.started":"2025-10-03T18:28:44.586888Z","shell.execute_reply":"2025-10-03T18:28:45.201086Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## finally, a  codes to test the model and retain.","metadata":{}},{"cell_type":"code","source":"model.eval() \ncpu_device = torch.device('cpu')\noutputs = model(images)\noutputs = [{k: v.to(cpu_device) for k , v in t.items()} for t in outputs]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:36:00.733145Z","iopub.execute_input":"2025-10-03T18:36:00.733439Z","iopub.status.idle":"2025-10-03T18:36:01.463590Z","shell.execute_reply.started":"2025-10-03T18:36:00.733418Z","shell.execute_reply":"2025-10-03T18:36:01.462883Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"torch.save(model.state_dict(), 'chacek_plants_for_Wheat.pth')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-03T18:36:40.864396Z","iopub.execute_input":"2025-10-03T18:36:40.864972Z","iopub.status.idle":"2025-10-03T18:36:41.148344Z","shell.execute_reply.started":"2025-10-03T18:36:40.864947Z","shell.execute_reply":"2025-10-03T18:36:41.147527Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}