Upload finetune_pcd.ipynb

#2
Files changed (1) hide show
  1. finetune_pcd.ipynb +292 -0
finetune_pcd.ipynb ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "06fcadf4",
6
+ "metadata": {},
7
+ "source": [
8
+ "# PCD (Plant Component Detector) fine-tuning — standalone Colab notebook\n",
9
+ "\n",
10
+ "Fine-tunes a YOLOv5 plant-component detector via the `yolov5` PyPI package (fcakyon/yolov5-pip). Fully standalone — no HerbaScan repo checkout needed, just this notebook plus your dataset.\n",
11
+ "\n",
12
+ "**Runtime**: Runtime menu -> Change runtime type -> GPU, before running anything below.\n",
13
+ "\n",
14
+ "**Your dataset** must already be in YOLO format on Google Drive:\n",
15
+ "```\n",
16
+ "<DATASET_ROOT>/\n",
17
+ " images/train/*.jpg labels/train/*.txt\n",
18
+ " images/val/*.jpg labels/val/*.txt\n",
19
+ " images/test/*.jpg labels/test/*.txt (optional)\n",
20
+ "```\n",
21
+ "each label `.txt` line: `<class_id> <x_center> <y_center> <width> <height>` (normalized 0-1)."
22
+ ]
23
+ },
24
+ {
25
+ "cell_type": "markdown",
26
+ "id": "fc9881eb",
27
+ "metadata": {},
28
+ "source": [
29
+ "## 1. Mount Drive + install\n",
30
+ "\n",
31
+ "Everything (dataset yaml, training runs, output weights) lives under Drive so it survives when the Colab runtime recycles."
32
+ ]
33
+ },
34
+ {
35
+ "cell_type": "code",
36
+ "execution_count": null,
37
+ "id": "3a1650eb",
38
+ "metadata": {},
39
+ "outputs": [],
40
+ "source": [
41
+ "from pathlib import Path\n",
42
+ "\n",
43
+ "from google.colab import drive\n",
44
+ "drive.mount(\"/content/drive\")\n",
45
+ "\n",
46
+ "WORKDIR = Path(\"/content/drive/MyDrive/pcd_training\")\n",
47
+ "WORKDIR.mkdir(parents=True, exist_ok=True)\n",
48
+ "\n",
49
+ "!pip install -q yolov5"
50
+ ]
51
+ },
52
+ {
53
+ "cell_type": "markdown",
54
+ "id": "f7d03223",
55
+ "metadata": {},
56
+ "source": [
57
+ "## 2. Config\n",
58
+ "\n",
59
+ "- `DATASET_ROOT`: Drive folder holding your `images/`+`labels/` splits (see layout above).\n",
60
+ "- `CLASS_NAMES`: edit to match your labels' class ids (index = id). Defaults to HerbaScan's 11 PCD classes.\n",
61
+ "- `WEIGHTS`: starting checkpoint. `\"yolov5s.pt\"` (or `m`/`l`/`x`) auto-downloads a COCO-pretrained YOLOv5 and fine-tunes from there. To continue fine-tuning an existing PCD checkpoint instead, upload it to Drive and point `WEIGHTS` at that `.pt` path."
62
+ ]
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "execution_count": null,
67
+ "id": "70d043a5",
68
+ "metadata": {},
69
+ "outputs": [],
70
+ "source": [
71
+ "DATASET_ROOT = WORKDIR / \"dataset\" # <- point at your own Drive dataset folder\n",
72
+ "\n",
73
+ "CLASS_NAMES = [\n",
74
+ " \"leaf_whole\", \"leaf_partial\", \"leaflet\",\n",
75
+ " \"seed_fruit_one\", \"seed_fruit_many\",\n",
76
+ " \"flower_one\", \"flower_many\",\n",
77
+ " \"bud\", \"specimen\", \"roots\", \"wood\",\n",
78
+ "]\n",
79
+ "\n",
80
+ "NAME = \"my_run\" # run name -> WORKDIR/runs/train/<name>/weights/best.pt\n",
81
+ "EPOCHS = 100\n",
82
+ "IMGSZ = 1280 # match whatever resolution you'll run inference at\n",
83
+ "DEVICE = \"0\" # Colab GPU; \"\" lets yolov5 auto-pick, \"cpu\" forces CPU\n",
84
+ "WEIGHTS = \"yolov5s.pt\" # or Path(\"/content/drive/MyDrive/.../best.pt\") to resume fine-tuning\n",
85
+ "CONVERT = False # also export the trained weight to ONNX\n",
86
+ "PASSTHROUGH: list[str] = [] # extra yolov5-train flags, e.g. [\"--batch-size\", \"32\"]"
87
+ ]
88
+ },
89
+ {
90
+ "cell_type": "markdown",
91
+ "id": "f32b07df",
92
+ "metadata": {},
93
+ "source": [
94
+ "## 3. Write the dataset yaml"
95
+ ]
96
+ },
97
+ {
98
+ "cell_type": "code",
99
+ "execution_count": null,
100
+ "id": "fb7dd092",
101
+ "metadata": {},
102
+ "outputs": [],
103
+ "source": [
104
+ "import yaml\n",
105
+ "\n",
106
+ "for split in (\"train\", \"val\"):\n",
107
+ " assert (DATASET_ROOT / \"images\" / split).is_dir(), (\n",
108
+ " f\"Missing {DATASET_ROOT / 'images' / split} — point DATASET_ROOT at a dataset \"\n",
109
+ " \"with images/train, labels/train, images/val, labels/val.\"\n",
110
+ " )\n",
111
+ "\n",
112
+ "DATA = WORKDIR / \"dataset.yaml\"\n",
113
+ "dataset_config = {\n",
114
+ " \"path\": str(DATASET_ROOT),\n",
115
+ " \"train\": \"images/train\",\n",
116
+ " \"val\": \"images/val\",\n",
117
+ " \"nc\": len(CLASS_NAMES),\n",
118
+ " \"names\": CLASS_NAMES,\n",
119
+ "}\n",
120
+ "if (DATASET_ROOT / \"images\" / \"test\").is_dir():\n",
121
+ " dataset_config[\"test\"] = \"images/test\"\n",
122
+ "\n",
123
+ "DATA.write_text(yaml.safe_dump(dataset_config, sort_keys=False))\n",
124
+ "print(DATA.read_text())"
125
+ ]
126
+ },
127
+ {
128
+ "cell_type": "markdown",
129
+ "id": "3d5e2402",
130
+ "metadata": {},
131
+ "source": [
132
+ "## 4. Train"
133
+ ]
134
+ },
135
+ {
136
+ "cell_type": "code",
137
+ "execution_count": null,
138
+ "id": "70380f28",
139
+ "metadata": {},
140
+ "outputs": [],
141
+ "source": [
142
+ "from __future__ import annotations\n",
143
+ "\n",
144
+ "import shutil\n",
145
+ "import subprocess\n",
146
+ "import sys\n",
147
+ "\n",
148
+ "\n",
149
+ "def yolov5_cli() -> Path:\n",
150
+ " \"\"\"Locate the `yolov5` console script installed next to the active interpreter.\"\"\"\n",
151
+ " exe_dir = Path(sys.executable).parent\n",
152
+ " for name in (\"yolov5.exe\", \"yolov5\"):\n",
153
+ " candidate = exe_dir / name\n",
154
+ " if candidate.exists():\n",
155
+ " return candidate\n",
156
+ " raise FileNotFoundError(\"yolov5 CLI not found — did step 1's pip install run?\")\n",
157
+ "\n",
158
+ "\n",
159
+ "CLI = yolov5_cli()\n",
160
+ "!nvidia-smi --query-gpu=name,memory.total --format=csv,noheader"
161
+ ]
162
+ },
163
+ {
164
+ "cell_type": "code",
165
+ "execution_count": null,
166
+ "id": "14edb428",
167
+ "metadata": {},
168
+ "outputs": [],
169
+ "source": [
170
+ "def run_training() -> Path:\n",
171
+ " cmd = [\n",
172
+ " str(CLI), \"train\",\n",
173
+ " \"--data\", str(DATA),\n",
174
+ " \"--weights\", str(WEIGHTS),\n",
175
+ " \"--imgsz\", str(IMGSZ),\n",
176
+ " \"--epochs\", str(EPOCHS),\n",
177
+ " \"--project\", str(WORKDIR / \"runs\" / \"train\"),\n",
178
+ " \"--name\", NAME,\n",
179
+ " \"--exist-ok\",\n",
180
+ " \"--device\", DEVICE,\n",
181
+ " *PASSTHROUGH,\n",
182
+ " ]\n",
183
+ " print(f\"[TRAIN] weights={WEIGHTS} data={DATA} imgsz={IMGSZ} epochs={EPOCHS} name={NAME}\")\n",
184
+ " proc = subprocess.run(cmd)\n",
185
+ " if proc.returncode != 0:\n",
186
+ " raise RuntimeError(\"yolov5 train returned non-zero exit code.\")\n",
187
+ "\n",
188
+ " best = WORKDIR / \"runs\" / \"train\" / NAME / \"weights\" / \"best.pt\"\n",
189
+ " if not best.exists():\n",
190
+ " raise FileNotFoundError(f\"Expected trained weights not found: {best}\")\n",
191
+ " return best\n",
192
+ "\n",
193
+ "\n",
194
+ "trained = run_training()\n",
195
+ "trained"
196
+ ]
197
+ },
198
+ {
199
+ "cell_type": "markdown",
200
+ "id": "7d2d669a",
201
+ "metadata": {},
202
+ "source": [
203
+ "## 5. Collect the output weight\n",
204
+ "\n",
205
+ "Copies the trained checkpoint to `WORKDIR/weights/<NAME>.pt`, a stable path independent of `runs/train/...`."
206
+ ]
207
+ },
208
+ {
209
+ "cell_type": "code",
210
+ "execution_count": null,
211
+ "id": "d7df2867",
212
+ "metadata": {},
213
+ "outputs": [],
214
+ "source": [
215
+ "OUT_WEIGHTS = WORKDIR / \"weights\"\n",
216
+ "OUT_WEIGHTS.mkdir(parents=True, exist_ok=True)\n",
217
+ "\n",
218
+ "dest = OUT_WEIGHTS / f\"{NAME}.pt\"\n",
219
+ "shutil.copy2(trained, dest)\n",
220
+ "print(f\"[SAVED] {dest}\")\n",
221
+ "dest"
222
+ ]
223
+ },
224
+ {
225
+ "cell_type": "markdown",
226
+ "id": "224c8864",
227
+ "metadata": {},
228
+ "source": [
229
+ "## 6. Optional: export to ONNX"
230
+ ]
231
+ },
232
+ {
233
+ "cell_type": "code",
234
+ "execution_count": null,
235
+ "id": "c7a40b45",
236
+ "metadata": {},
237
+ "outputs": [],
238
+ "source": [
239
+ "def convert_to_onnx(weights_pt: Path, imgsz: int) -> Path:\n",
240
+ " dst = weights_pt.with_suffix(\".onnx\")\n",
241
+ " cmd = [\n",
242
+ " str(CLI), \"export\",\n",
243
+ " \"--weights\", str(weights_pt),\n",
244
+ " \"--include\", \"onnx\",\n",
245
+ " \"--opset\", \"18\",\n",
246
+ " \"--imgsz\", str(imgsz),\n",
247
+ " \"--device\", \"cpu\",\n",
248
+ " ]\n",
249
+ " print(f\"[CONVERT] {' '.join(cmd)}\")\n",
250
+ " proc = subprocess.run(cmd)\n",
251
+ " if proc.returncode != 0:\n",
252
+ " raise RuntimeError(\"yolov5 export returned non-zero exit code.\")\n",
253
+ " if not dst.exists():\n",
254
+ " raise FileNotFoundError(f\"Expected ONNX output not found: {dst}\")\n",
255
+ " return dst\n",
256
+ "\n",
257
+ "\n",
258
+ "if CONVERT:\n",
259
+ " onnx_path = convert_to_onnx(dest, IMGSZ)\n",
260
+ " print(onnx_path)\n",
261
+ "else:\n",
262
+ " print(\"CONVERT=False, skipped ONNX export.\")"
263
+ ]
264
+ },
265
+ {
266
+ "cell_type": "markdown",
267
+ "id": "65f19199",
268
+ "metadata": {},
269
+ "source": [
270
+ "Done. Trained weight: `WORKDIR/weights/<NAME>.pt` (and `.onnx` if `CONVERT=True`), both on Drive."
271
+ ]
272
+ }
273
+ ],
274
+ "metadata": {
275
+ "accelerator": "GPU",
276
+ "colab": {
277
+ "gpuType": "T4",
278
+ "provenance": []
279
+ },
280
+ "kernelspec": {
281
+ "display_name": "Python 3",
282
+ "language": "python",
283
+ "name": "python3"
284
+ },
285
+ "language_info": {
286
+ "name": "python",
287
+ "version": "3.10"
288
+ }
289
+ },
290
+ "nbformat": 4,
291
+ "nbformat_minor": 5
292
+ }