Added Automation to Kaggle with Kaggle API
This commit is contained in:
1 parent
2baac9b5a7
commit
99f6f6265b
2 files changed
+679
-4
No files matched your search
@@ -59,6 +59,8 @@ project/
|
||||
├── 2_train_classifier.py ← train EfficientNet classifier
|
||||
├── 3_inference.py ← end-to-end detect + classify on new images
|
||||
├── api_server.py ← FastAPI polling server
|
||||
├── balance_and_augment.py ← balance classes + generate augmented images
|
||||
├── kaggle_train.py ← automate Kaggle upload + training + download
|
||||
└── train_classifier_kaggle.ipynb
|
||||
```
|
||||
|
||||
@@ -311,6 +313,75 @@ The splitter prints a table so you can spot imbalanced or thin classes before tr
|
||||
|
||||
---
|
||||
|
||||
### Step 3b — Balance & augment the dataset
|
||||
|
||||
> Optional but strongly recommended when classes have unequal image counts or any class has fewer than 50 training images.
|
||||
|
||||
Analyses the `train/` split, calculates how many images each class needs to reach a target count, then generates augmented copies using a three-tier albumentations pipeline until every class is balanced.
|
||||
|
||||
```bash
|
||||
python balance_and_augment.py --data_dir crops_dataset --split train --max_scale 2.0 --workers 8 --dry_run
|
||||
```
|
||||
|
||||
Remove `--dry_run` once you are happy with the plan.
|
||||
|
||||
| Argument | Default | Description |
|
||||
|---|---|---|
|
||||
| `--data_dir` | `crops_dataset` | Root with `train/` `val/` `test/` subfolders |
|
||||
| `--split` | `train` | Which split to augment |
|
||||
| `--target_count` | auto | Explicit target per class — omit to use auto |
|
||||
| `--max_scale` | `2.0` | Auto target = largest class × this factor |
|
||||
| `--min_count` | `0.95` | Skip classes already within 5 % of target |
|
||||
| `--workers` | cpu − 1 | Parallel workers |
|
||||
| `--dry_run` | off | Print the plan without writing files |
|
||||
| `--val_split` | `0.0` | Fraction of augmented images also copied to `val/` |
|
||||
| `--suffix` | `_aug` | Filename suffix added to augmented images |
|
||||
| `--quality` | `92` | JPEG save quality |
|
||||
|
||||
**Dry-run output example:**
|
||||
|
||||
```
|
||||
──────────────────────────────────────────────────────────
|
||||
Class Current Target To add Status
|
||||
──────────────────────────────────────────────────────────
|
||||
cola_can 72 200 128 + 128 ████████████
|
||||
lays_chips 18 200 182 + 182 ██
|
||||
pepsi_can 58 200 142 + 142 ██████
|
||||
siglo 204 200 0 ✓ ok ████████████████████
|
||||
──────────────────────────────────────────────────────────
|
||||
TOTAL 352 452
|
||||
──────────────────────────────────────────────────────────
|
||||
```
|
||||
|
||||
**Three-tier augmentation pipeline:**
|
||||
|
||||
| Tier | Transforms | Probability |
|
||||
|---|---|---|
|
||||
| **Light** (always) | HorizontalFlip, ShiftScaleRotate ±15°, BrightnessContrast ±30%, HueSaturation | 75–85% each |
|
||||
| **Medium** (random subset) | Perspective, GridDistortion, ElasticTransform, Blur/Sharpen, GaussNoise, CoarseDropout (occlusion), JPEG compression | 25–40% |
|
||||
| **Heavy** (rare) | RandomShadow, RandomSunFlare, RandomFog, ChannelShuffle, RGBShift | 8–15% |
|
||||
|
||||
Augmented files are written **beside the originals** in the same class folder. Originals are never modified or deleted.
|
||||
|
||||
> **When to use `--val_split`:** Pass `--val_split 0.10` to also copy 10% of the augmented images into `val/` if your val set is very small (< 5 images per class). For most cases, leave it at `0` — val should represent real unaugmented images.
|
||||
|
||||
---
|
||||
|
||||
### Step 3b — recommended workflow
|
||||
|
||||
```bash
|
||||
# 1. Preview the plan
|
||||
python balance_and_augment.py --data_dir crops_dataset --dry_run
|
||||
|
||||
# 2. Run with auto target (largest class × 2)
|
||||
python balance_and_augment.py --data_dir crops_dataset --workers 8
|
||||
|
||||
# 3. Or set an explicit target
|
||||
python balance_and_augment.py --data_dir crops_dataset --target_count 300
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Step 4 — Train the classifier
|
||||
|
||||
Trains an **EfficientNet-B0** (ImageNet pre-trained) on `crops_dataset/`. A `WeightedRandomSampler` is used automatically so class imbalance does not bias training.
|
||||
@@ -399,6 +470,72 @@ After training, download from `/kaggle/working/runs/classify/`:
|
||||
|
||||
These two files are all you need to run `3_inference.py` and `api_server.py`.
|
||||
|
||||
#### Option C — Fully automated via `kaggle_train.py`
|
||||
|
||||
Run the entire Kaggle pipeline — upload, train, download — from a single command with no browser needed:
|
||||
|
||||
```bash
|
||||
python kaggle_train.py \
|
||||
--dataset_dir crops_dataset \
|
||||
--notebook train_classifier_kaggle.ipynb \
|
||||
--dataset_name my-product-crops \
|
||||
--kernel_name product-classifier-train \
|
||||
--output_dir runs/classify
|
||||
```
|
||||
|
||||
**One-time setup:**
|
||||
|
||||
1. Go to [kaggle.com/settings/api](https://www.kaggle.com/settings/api) → **Create New Token** → downloads `kaggle.json`
|
||||
2. Move it to `~/.kaggle/kaggle.json`
|
||||
3. On Linux/Mac: `chmod 600 ~/.kaggle/kaggle.json`
|
||||
|
||||
Or use environment variables instead of the file:
|
||||
```bash
|
||||
export KAGGLE_USERNAME=your_username
|
||||
export KAGGLE_KEY=your_api_key
|
||||
```
|
||||
|
||||
**What the script does automatically:**
|
||||
|
||||
| Step | Action |
|
||||
|---|---|
|
||||
| 1 | Zips `crops_dataset/` and uploads (or updates) it as a Kaggle Dataset |
|
||||
| 2 | Patches `DATA_DIR` in the notebook to match the uploaded dataset path |
|
||||
| 3 | Pushes the notebook as a Kaggle Kernel and triggers a GPU run |
|
||||
| 4 | Polls kernel status every 30 s until `complete` or `failed` |
|
||||
| 5 | Downloads `best.pt`, `class_names.json`, and plot PNGs into `runs/classify/` |
|
||||
|
||||
**Arguments:**
|
||||
|
||||
| Argument | Default | Description |
|
||||
|---|---|---|
|
||||
| `--dataset_dir` | `crops_dataset` | Local dataset folder to upload |
|
||||
| `--notebook` | `train_classifier_kaggle.ipynb` | Notebook file to push |
|
||||
| `--dataset_name` | `product-crops` | Kaggle dataset slug (lowercase, hyphens) |
|
||||
| `--kernel_name` | `product-classifier` | Kaggle kernel slug |
|
||||
| `--output_dir` | `runs/classify` | Where to save downloaded weights |
|
||||
| `--poll_interval` | `30` | Seconds between status checks |
|
||||
| `--timeout` | `180` | Max minutes to wait before giving up |
|
||||
| `--skip_upload` | off | Skip zip+upload — reuse existing Kaggle dataset |
|
||||
| `--skip_push` | off | Skip kernel push — just poll and download last run |
|
||||
| `--no_gpu` | off | Run on CPU instead of T4 GPU |
|
||||
| `--public` | off | Make dataset and kernel public |
|
||||
|
||||
**Useful combinations:**
|
||||
|
||||
```bash
|
||||
# Re-run training on an already uploaded dataset (faster — skips the zip/upload)
|
||||
python kaggle_train.py --skip_upload --dataset_name my-product-crops --kernel_name product-classifier-train
|
||||
|
||||
# Just download the outputs of the last completed run (no upload, no push)
|
||||
python kaggle_train.py --skip_upload --skip_push --kernel_name product-classifier-train
|
||||
|
||||
# Full run but with a fresh public kernel
|
||||
python kaggle_train.py --dataset_name my-product-crops --kernel_name product-classifier-train --public
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### Diagnosing a stuck val loss
|
||||
|
||||
A val loss stuck above `ln(num_classes)` (e.g. > 3.13 for 23 classes) means the model is guessing randomly or confidently wrong. Common causes:
|
||||
@@ -452,10 +589,8 @@ The classifier automatically probes available VRAM at startup and picks the larg
|
||||
---
|
||||
|
||||
## 5. API Server
|
||||
|
||||
A REST API with a polling pattern for integration into other applications.
|
||||
<p align="center">
|
||||
<img src="assets/Polling Pattern.png" height=400 />
|
||||
</p>
|
||||
|
||||
```bash
|
||||
pip install fastapi uvicorn
|
||||
@@ -560,6 +695,8 @@ Progress stages:
|
||||
| `1_generate_crop_dataset.py` | Detect & crop (no classifier) | shelf images | `data/unknown/*.jpg` |
|
||||
| `auto_label.py` | Detect + auto-classify + browser review | shelf images + both models | `data/<class>/*.jpg` |
|
||||
| `1b_split_dataset.py` | Stratified train/val/test split | `data/` | `crops_dataset/` |
|
||||
| `balance_and_augment.py` | Balance classes + augment | `crops_dataset/train/` | augmented images in-place |
|
||||
| `kaggle_train.py` | Automate Kaggle upload + train + download | `crops_dataset/` + notebook | `runs/classify/best.pt` |
|
||||
| `2_train_classifier.py` | Train EfficientNet classifier | `crops_dataset/` | `runs/classify/best.pt` |
|
||||
| `3_inference.py` | End-to-end detect + classify | images / video / webcam | annotated images/video |
|
||||
| `api_server.py` | REST polling API | — | JSON + base64 annotated image |
|
||||
@@ -620,7 +757,9 @@ Review UI (confirm / fix / reject)
|
||||
↓
|
||||
1b_split_dataset.py (re-split the grown dataset)
|
||||
↓
|
||||
2_train_classifier.py (retrain from scratch or from last.pt)
|
||||
balance_and_augment.py (equalise class counts, generate augmented copies)
|
||||
↓
|
||||
2_train_classifier.py (local) OR kaggle_train.py (automated Kaggle)
|
||||
↓
|
||||
3_inference.py / api_server.py (deploy updated model)
|
||||
↓
|
||||
|
||||
Reference in new issue
Block a user