{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceType":"competition","sourceId":117876,"databundleVersionId":14198377}],"dockerImageVersionId":31329,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2026-03-21T09:46:13.477334Z","iopub.execute_input":"2026-03-21T09:46:13.477650Z","iopub.status.idle":"2026-03-21T09:46:16.242399Z","shell.execute_reply.started":"2026-03-21T09:46:13.477613Z","shell.execute_reply":"2026-03-21T09:46:16.241587Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\nfor root, dirs, files in os.walk('/kaggle/input'):\n    print(root)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-21T09:46:37.784824Z","iopub.execute_input":"2026-03-21T09:46:37.785383Z","iopub.status.idle":"2026-03-21T09:46:38.566309Z","shell.execute_reply.started":"2026-03-21T09:46:37.785351Z","shell.execute_reply":"2026-03-21T09:46:38.565592Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install ultralytics","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-21T09:46:45.005131Z","iopub.execute_input":"2026-03-21T09:46:45.005857Z","iopub.status.idle":"2026-03-21T09:46:50.482811Z","shell.execute_reply.started":"2026-03-21T09:46:45.005826Z","shell.execute_reply":"2026-03-21T09:46:50.481868Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data_yaml = \"\"\"\npath: /kaggle/input/competitions/the-3lc-cotton-weed-detection-challenge/cotton_weed_competition_dataset\ntrain: train/images\nval: val/images\n\nnc: 3\nnames: ['Carpetweed', 'MorningGlory', 'PalmerAmaranth']\n\"\"\"\n\nwith open(\"data.yaml\", \"w\") as f:\n    f.write(data_yaml)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-21T09:47:02.920615Z","iopub.execute_input":"2026-03-21T09:47:02.920921Z","iopub.status.idle":"2026-03-21T09:47:02.925237Z","shell.execute_reply.started":"2026-03-21T09:47:02.920895Z","shell.execute_reply":"2026-03-21T09:47:02.924709Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from ultralytics import YOLO\n\nmodel = YOLO(\"yolov8n.pt\")\n\nmodel.train(\n    data=\"data.yaml\",\n    epochs=30,\n    imgsz=640,\n    batch=16\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-21T09:47:27.961265Z","iopub.execute_input":"2026-03-21T09:47:27.961628Z","iopub.status.idle":"2026-03-21T10:14:31.892701Z","shell.execute_reply.started":"2026-03-21T09:47:27.961598Z","shell.execute_reply":"2026-03-21T10:14:31.891896Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!ls /kaggle/input/competitions/the-3lc-cotton-weed-detection-challenge/cotton_weed_competition_dataset/val","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-21T10:23:02.566220Z","iopub.execute_input":"2026-03-21T10:23:02.566596Z","iopub.status.idle":"2026-03-21T10:23:02.762731Z","shell.execute_reply.started":"2026-03-21T10:23:02.566531Z","shell.execute_reply":"2026-03-21T10:23:02.761982Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.val()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-21T10:23:27.198345Z","iopub.execute_input":"2026-03-21T10:23:27.198723Z","iopub.status.idle":"2026-03-21T10:23:45.141408Z","shell.execute_reply.started":"2026-03-21T10:23:27.198685Z","shell.execute_reply":"2026-03-21T10:23:45.140621Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"results = model.predict(\n    \"/kaggle/input/competitions/the-3lc-cotton-weed-detection-challenge/cotton_weed_competition_dataset/test/images\",\n    save=True,\n    save_txt=True\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-21T10:31:24.134106Z","iopub.execute_input":"2026-03-21T10:31:24.134699Z","iopub.status.idle":"2026-03-21T10:32:20.040121Z","shell.execute_reply.started":"2026-03-21T10:31:24.134666Z","shell.execute_reply":"2026-03-21T10:32:20.039545Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport pandas as pd\n\n# Path to predicted label files\npred_labels_path = \"/kaggle/working/runs/detect/predict/labels\"\n\nrows = []\n\n# Loop over all label files\nfor file in os.listdir(pred_labels_path):\n    if not file.endswith(\".txt\"):\n        continue\n\n    image_id = file.replace(\".txt\", \"\")\n    filepath = os.path.join(pred_labels_path, file)\n    \n    with open(filepath, \"r\") as f:\n        lines = f.readlines()\n    \n    if len(lines) == 0:\n        # No detections for this image\n        prediction_string = \"no box\"\n    else:\n        preds = []\n        for line in lines:\n            parts = list(map(float, line.strip().split()))\n            \n            # Handle lines with or without confidence\n            if len(parts) == 6:\n                cls, x, y, w, h, conf = parts\n            elif len(parts) == 5:\n                cls, x, y, w, h = parts\n                conf = 1.0  # default confidence if missing\n            else:\n                raise ValueError(f\"Unexpected number of values in {file}: {parts}\")\n            \n            # Reorder for Kaggle submission\n            preds.extend([int(cls), float(conf), float(x), float(y), float(w), float(h)])\n        \n        prediction_string = \" \".join(map(str, preds))\n    \n    rows.append([image_id, prediction_string])\n\n# Create DataFrame and save CSV\ndf = pd.DataFrame(rows, columns=[\"image_id\", \"prediction_string\"])\ndf.to_csv(\"submission.csv\", index=False)\n\n# Preview\ndf.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-21T10:38:57.029753Z","iopub.execute_input":"2026-03-21T10:38:57.030599Z","iopub.status.idle":"2026-03-21T10:38:57.127234Z","shell.execute_reply.started":"2026-03-21T10:38:57.030535Z","shell.execute_reply":"2026-03-21T10:38:57.126652Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!ls /kaggle/working/runs/detect/predict/labels\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-03-21T10:34:11.109598Z","iopub.execute_input":"2026-03-21T10:34:11.110459Z","iopub.status.idle":"2026-03-21T10:34:11.386742Z","shell.execute_reply.started":"2026-03-21T10:34:11.110421Z","shell.execute_reply":"2026-03-21T10:34:11.385986Z"}},"outputs":[],"execution_count":null}]}