{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","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":410288,"sourceType":"modelInstanceVersion","isSourceIdPinned":true,"modelInstanceId":335039,"modelId":356057}],"dockerImageVersionId":31041,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport re\nimport numpy as np\nimport pandas as pd\nimport cv2\nimport matplotlib.pyplot as plt\nfrom sklearn import model_selection\nfrom sklearn.model_selection import train_test_split\nfrom tqdm import tqdm\nimport shutil","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-05-25T22:47:30.073686Z","iopub.execute_input":"2025-05-25T22:47:30.073949Z","iopub.status.idle":"2025-05-25T22:47:33.182474Z","shell.execute_reply.started":"2025-05-25T22:47:30.073924Z","shell.execute_reply":"2025-05-25T22:47:33.181730Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"output_dir = '/kaggle/working/'  \ndata_path = '/kaggle/input/global-wheat-detection/train'  \n\nos.makedirs(os.path.join(output_dir, 'labels/train'), exist_ok=True)\nos.makedirs(os.path.join(output_dir, 'labels/valid'), exist_ok=True)\nos.makedirs(os.path.join(output_dir, 'images/train'), exist_ok=True)\nos.makedirs(os.path.join(output_dir, 'images/valid'), exist_ok=True)\n\ndef process_data(data, data_type='train'):\n    for _, row in tqdm(data.iterrows(), total=len(data)):\n        image_name = row['image_id']\n        bounding_boxes = row['bboxes']\n        yolo_data = []\n        \n        for bbox in bounding_boxes:\n            x, y, w, h = bbox \n            x_center = (x + w / 2) / 1024.0  # Normalize x_center\n            y_center = (y + h / 2) / 1024.0  # Normalize y_center\n            w_norm = w / 1024.0  # Normalize width\n            h_norm = h / 1024.0  # Normalize height\n            yolo_data.append([0, x_center, y_center, w_norm, h_norm]) \n            \n        yolo_data = np.array(yolo_data)  \n    \n        np.savetxt(\n            os.path.join(output_dir, f'labels/{data_type}/{image_name}.txt'),\n            yolo_data,\n            fmt='%d %.6f %.6f %.6f %.6f',  # Format: class_id x_center y_center width height\n            delimiter=' '\n        )\n        shutil.copyfile(\n            os.path.join(data_path, f'{image_name}.jpg'),\n            os.path.join(output_dir, f'images/{data_type}/{image_name}.jpg')\n        )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-25T22:47:33.183190Z","iopub.execute_input":"2025-05-25T22:47:33.183473Z","iopub.status.idle":"2025-05-25T22:47:33.191821Z","shell.execute_reply.started":"2025-05-25T22:47:33.183457Z","shell.execute_reply":"2025-05-25T22:47:33.191071Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df = pd.read_csv(\"/kaggle/input/global-wheat-detection/train.csv\")\ndf.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-25T22:47:33.193541Z","iopub.execute_input":"2025-05-25T22:47:33.193745Z","iopub.status.idle":"2025-05-25T22:47:33.537908Z","shell.execute_reply.started":"2025-05-25T22:47:33.193729Z","shell.execute_reply":"2025-05-25T22:47:33.537069Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_show = []\ncolumns = df . columns \nfor i in columns : \n    types = df[i] . dtypes\n    unique_data = df[i] . nunique()\n    NAN_value=df[i].isnull().sum()\n    duplicated= df.duplicated().sum()  \n    \n    df_show . append ([i , types , unique_data , NAN_value,duplicated])\n        \ndf_info = pd . DataFrame (df_show)\ndf_info . columns =['name of column' , 'types' ,'unique_data' , 'NAN value',\"duplicated\"]\n\n\n\n\ndf_info.style.highlight_max(color = 'pink', axis = 0)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-25T22:47:33.538781Z","iopub.execute_input":"2025-05-25T22:47:33.539381Z","iopub.status.idle":"2025-05-25T22:47:34.010839Z","shell.execute_reply.started":"2025-05-25T22:47:33.539362Z","shell.execute_reply":"2025-05-25T22:47:34.009847Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def expand_bbox(x):\n    r = np.array(re.findall(\"[0-9]+[.]?[0-9]*\", x)).astype(np.float32)\n    if len(r) != 4:\n        print(\"WARNING! Bbox dimension not equal to 4\")\n    return r\n\ndf.bbox=df.bbox.apply(expand_bbox)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-25T22:47:34.011623Z","iopub.execute_input":"2025-05-25T22:47:34.012055Z","iopub.status.idle":"2025-05-25T22:47:34.880985Z","shell.execute_reply.started":"2025-05-25T22:47:34.012034Z","shell.execute_reply":"2025-05-25T22:47:34.880280Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.bbox","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-25T22:47:34.881833Z","iopub.execute_input":"2025-05-25T22:47:34.882104Z","iopub.status.idle":"2025-05-25T22:47:34.890816Z","shell.execute_reply.started":"2025-05-25T22:47:34.882080Z","shell.execute_reply":"2025-05-25T22:47:34.890123Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df = df.groupby('image_id')['bbox'].apply(list).reset_index(name='bboxes')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-25T22:47:34.891394Z","iopub.execute_input":"2025-05-25T22:47:34.891661Z","iopub.status.idle":"2025-05-25T22:47:34.995496Z","shell.execute_reply.started":"2025-05-25T22:47:34.891637Z","shell.execute_reply":"2025-05-25T22:47:34.994582Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-25T22:47:34.996237Z","iopub.execute_input":"2025-05-25T22:47:34.996426Z","iopub.status.idle":"2025-05-25T22:47:35.072025Z","shell.execute_reply.started":"2025-05-25T22:47:34.996410Z","shell.execute_reply":"2025-05-25T22:47:35.071218Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_train, df_vaild = train_test_split(df, test_size=0.1, random_state=42, shuffle=True)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-25T22:47:35.074644Z","iopub.execute_input":"2025-05-25T22:47:35.074919Z","iopub.status.idle":"2025-05-25T22:47:35.080842Z","shell.execute_reply.started":"2025-05-25T22:47:35.074901Z","shell.execute_reply":"2025-05-25T22:47:35.080006Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_train = df_train.reset_index(drop=True)\ndf_vaild = df_vaild.reset_index(drop=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-25T22:47:35.081827Z","iopub.execute_input":"2025-05-25T22:47:35.082184Z","iopub.status.idle":"2025-05-25T22:47:35.097314Z","shell.execute_reply.started":"2025-05-25T22:47:35.082111Z","shell.execute_reply":"2025-05-25T22:47:35.096529Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"process_data(df_train, data_type='train')\nprocess_data(df_vaild, data_type='valid')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-25T22:47:35.098024Z","iopub.execute_input":"2025-05-25T22:47:35.098284Z","iopub.status.idle":"2025-05-25T22:48:07.718261Z","shell.execute_reply.started":"2025-05-25T22:47:35.098260Z","shell.execute_reply":"2025-05-25T22:48:07.717471Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data_yaml_content=f\"\"\"\ntrain: {os.path.join(output_dir,'images/train')}\nval: {os.path.join(output_dir,'images/valid')}\nnc: 1\nnames: ['wheat']\n\"\"\"\n\ndata_yaml_path= os.path.join(output_dir, 'data.yaml')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-25T22:48:07.719143Z","iopub.execute_input":"2025-05-25T22:48:07.720034Z","iopub.status.idle":"2025-05-25T22:48:07.723893Z","shell.execute_reply.started":"2025-05-25T22:48:07.720015Z","shell.execute_reply":"2025-05-25T22:48:07.723093Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"with open(data_yaml_path, 'w') as file:\n    file.write(data_yaml_content)\nprint(f\"data.yaml file saved at: {data_yaml_path}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-25T22:48:07.724765Z","iopub.execute_input":"2025-05-25T22:48:07.725081Z","iopub.status.idle":"2025-05-25T22:48:07.747392Z","shell.execute_reply.started":"2025-05-25T22:48:07.725061Z","shell.execute_reply":"2025-05-25T22:48:07.746593Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"with open(data_yaml_path,'r') as file:\n    print(file.read())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-25T22:48:07.748306Z","iopub.execute_input":"2025-05-25T22:48:07.748591Z","iopub.status.idle":"2025-05-25T22:48:07.761726Z","shell.execute_reply.started":"2025-05-25T22:48:07.748570Z","shell.execute_reply":"2025-05-25T22:48:07.760965Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install ultralytics\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-25T22:48:07.762590Z","iopub.execute_input":"2025-05-25T22:48:07.762912Z","iopub.status.idle":"2025-05-25T22:49:16.770736Z","shell.execute_reply.started":"2025-05-25T22:48:07.762888Z","shell.execute_reply":"2025-05-25T22:49:16.769800Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from ultralytics import YOLO\n\nmodel = YOLO('/kaggle/input/yolo11n/pytorch/default/1/yolo11n.pt')  \nresults = model.train(\n    data=data_yaml_path,  \n    epochs=2,                         \n    imgsz=1024,                        \n    batch=16,                          \n    patience=10,                                                 \n    cos_lr=True,                       \n    warmup_epochs=3,                  \n    augment=True,                     \n    weight_decay=0.0005,               \n    momentum=0.937,                    \n    dropout=0.2                        \n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-25T22:55:00.284246Z","iopub.execute_input":"2025-05-25T22:55:00.285014Z","iopub.status.idle":"2025-05-25T23:38:33.809425Z","shell.execute_reply.started":"2025-05-25T22:55:00.284972Z","shell.execute_reply":"2025-05-25T23:38:33.807921Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"metrics = model.val(data='/kaggle/working/data.yaml', split='val')\n\nmAP50 = metrics.box.map50  \nmAP50_95 = metrics.box.map  \nprecision = metrics.box.p  \nrecall = metrics.box.r  \n\n# Print metrics\nprint(f\"mAP50: {mAP50:.4f}\")\nprint(f\"mAP50-95: {mAP50_95:.4f}\")\nprint(f\"Precision: {np.mean(precision):.4f}\")  \nprint(f\"Recall: {np.mean(recall):.4f}\") ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-25T23:38:40.804708Z","iopub.execute_input":"2025-05-25T23:38:40.805044Z","iopub.status.idle":"2025-05-25T23:38:53.659542Z","shell.execute_reply.started":"2025-05-25T23:38:40.805022Z","shell.execute_reply":"2025-05-25T23:38:53.658622Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sample_image_path = os.path.join(output_dir, 'images/valid', df_vaild.iloc[89]['image_id'] + '.jpg')\nimage = cv2.imread(sample_image_path)\nimage = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) \n\nresults = model.predict(source=sample_image_path, conf=0.5)  \n\nfor result in results:\n    boxes = result.boxes.xyxy.cpu().numpy()  \n    for box in boxes:\n        x1, y1, x2, y2 = box\n        cv2.rectangle(image, (int(x1), int(y1)), (int(x2), int(y2)), (255, 0, 0), 2)  \n\nplt.figure(figsize=(6, 4))\nplt.imshow(image)\nplt.axis('off')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-25T23:38:58.963421Z","iopub.execute_input":"2025-05-25T23:38:58.963741Z","iopub.status.idle":"2025-05-25T23:38:59.222535Z","shell.execute_reply.started":"2025-05-25T23:38:58.963715Z","shell.execute_reply":"2025-05-25T23:38:59.221746Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save('custom_yolo.pt')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-25T23:39:01.075001Z","iopub.execute_input":"2025-05-25T23:39:01.075290Z","iopub.status.idle":"2025-05-25T23:39:01.155126Z","shell.execute_reply.started":"2025-05-25T23:39:01.075270Z","shell.execute_reply":"2025-05-25T23:39:01.154268Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}