Datasets:
v8: rebalanced + sample_karst_score for per-pixel binary karst regression
Browse filesCombines all 3 AOIs (Central/East/West), adds sample_karst_score field (0=other, 1=karst) for per-pixel binary regression, soft-balanced to max/min class ratio 9.9, pre-sharded into 5 longitude-coherent regions under Studio 10K-record cap. Passes 7/7 OE audit criteria. See v8/DATASET_CARD_ADDENDUM.md.
- .gitattributes +2 -0
- v8/DATASET_CARD_ADDENDUM.md +102 -0
- v8/HF_UPLOAD_INSTRUCTIONS.md +94 -0
- v8/balanced_karst_v8.parquet +3 -0
- v8/build_balanced_karst_dataset.py +225 -0
- v8/evaluate_v8_vs_v6.py +321 -0
- v8/rebuild_summary.csv +11 -0
- v8/studio/import_full.geojson +3 -0
- v8/studio/import_full.json +3 -0
- v8/studio/shards/region_00_lon-78.67_to_-77.74.geojson +0 -0
- v8/studio/shards/region_00_lon-78.67_to_-77.74.json +0 -0
- v8/studio/shards/region_01_lon-77.74_to_-77.15.geojson +0 -0
- v8/studio/shards/region_01_lon-77.74_to_-77.15.json +0 -0
- v8/studio/shards/region_02_lon-77.15_to_-76.34.geojson +0 -0
- v8/studio/shards/region_02_lon-77.15_to_-76.34.json +0 -0
- v8/studio/shards/region_03_lon-76.34_to_-75.70.geojson +0 -0
- v8/studio/shards/region_03_lon-76.34_to_-75.70.json +0 -0
- v8/studio/shards/region_04_lon-75.70_to_-74.97.geojson +0 -0
- v8/studio/shards/region_04_lon-75.70_to_-74.97.json +0 -0
.gitattributes
CHANGED
|
@@ -67,3 +67,5 @@ annotations/annotation_features.geojson filter=lfs diff=lfs merge=lfs -text
|
|
| 67 |
annotation_features.geojson filter=lfs diff=lfs merge=lfs -text
|
| 68 |
studio/import.geojson filter=lfs diff=lfs merge=lfs -text
|
| 69 |
studio/import.json filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 67 |
annotation_features.geojson filter=lfs diff=lfs merge=lfs -text
|
| 68 |
studio/import.geojson filter=lfs diff=lfs merge=lfs -text
|
| 69 |
studio/import.json filter=lfs diff=lfs merge=lfs -text
|
| 70 |
+
v8/studio/import_full.geojson filter=lfs diff=lfs merge=lfs -text
|
| 71 |
+
v8/studio/import_full.json filter=lfs diff=lfs merge=lfs -text
|
v8/DATASET_CARD_ADDENDUM.md
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
# This is an addendum to be merged into the existing README.md on HF
|
| 3 |
+
# Dataset: BAIGroup/OlmoEarth-v1-FT-Karst-Groundwater-Base
|
| 4 |
+
# Version: v8 (rebalanced + sample_karst_score)
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
# v8 Rebalanced Edition (2026-05-23)
|
| 8 |
+
|
| 9 |
+
A new variant of the Karst fine-tuning dataset that:
|
| 10 |
+
|
| 11 |
+
1. **Combines all 3 AOI regions** (Central, East, West) into one mixed training set
|
| 12 |
+
2. **Adds `sample_karst_score`** — a binary regression target (0.0 = other / 1.0 = karst) that lets OlmoEarth Studio's per-pixel regression head actually learn karst vs non-karst, instead of regressing to the mean of `sample_number` (confidence)
|
| 13 |
+
3. **Passes the 7-criterion OE quality audit** (max/min class ratio reduced from 13.0 to 9.9; spatial spread verified; negative class present)
|
| 14 |
+
4. **Pre-sharded** into 5 longitude-sorted regions of ~8,200 features each, all under Studio's 10K-records / 1-hour upload cap (pitfall #7)
|
| 15 |
+
|
| 16 |
+
## What's new in this version
|
| 17 |
+
|
| 18 |
+
| Aspect | Original (v1) | v8 |
|
| 19 |
+
|---|---|---|
|
| 20 |
+
| Rows | 47,020 | **40,989** |
|
| 21 |
+
| Class distribution | other 53%, depression 35%, sinkhole 8%, mine 4% | other 46%, depression 40%, sinkhole 9%, mine 5% |
|
| 22 |
+
| Max/min class ratio | 13.0 (fails audit) | **9.9 (passes)** |
|
| 23 |
+
| Binary karst balance (positive : negative) | 47 : 53 | **54 : 46** |
|
| 24 |
+
| Per-AOI columns | implicit only | **explicit `task_name`** (pa_karst_central / east / west) |
|
| 25 |
+
| Per-pixel regression target | `confidence` (0.6–0.9 for all classes — degenerate) | **`sample_karst_score` (0 or 1 — discriminative)** |
|
| 26 |
+
| Studio shards | none — 47K records times out (pitfall #7) | **5 longitude-coherent shards, each ~8,200** |
|
| 27 |
+
|
| 28 |
+
## New field: `sample_karst_score`
|
| 29 |
+
|
| 30 |
+
A pre-computed binary regression target so per-pixel regression in Studio produces a real karst probability map instead of collapsing to the mean (the V6 failure).
|
| 31 |
+
|
| 32 |
+
| `sample_category` (existing) | `sample_karst_score` (new) |
|
| 33 |
+
|---|---|
|
| 34 |
+
| `other` | **0.0** |
|
| 35 |
+
| `sinkhole` | **1.0** |
|
| 36 |
+
| `surface_depression` | **1.0** |
|
| 37 |
+
| `surface_mine` | **1.0** |
|
| 38 |
+
|
| 39 |
+
All other existing fields (`sample_category`, `sample_number`, `sample_true_false`, etc.) are preserved unchanged, so window-level classification and point detection workflows remain available.
|
| 40 |
+
|
| 41 |
+
## New field: `task_name`
|
| 42 |
+
|
| 43 |
+
Spatial AOI assignment (was implicit in v1, now an explicit column):
|
| 44 |
+
|
| 45 |
+
| AOI | Longitude range | Row count |
|
| 46 |
+
|---|---|---:|
|
| 47 |
+
| `pa_karst_west` | lon < -78.5 | 557 |
|
| 48 |
+
| `pa_karst_central` | -78.5 ≤ lon < -76.5 | 21,517 |
|
| 49 |
+
| `pa_karst_east` | lon ≥ -76.5 | 18,915 |
|
| 50 |
+
|
| 51 |
+
## Why three V6/V7 training runs produced unusable outputs
|
| 52 |
+
|
| 53 |
+
| Run | What it did | Why it failed |
|
| 54 |
+
|---|---|---|
|
| 55 |
+
| **V6 run2** (per-pixel regression on `sample_number`) | Trained continuous regression on labeler confidence (0.6–0.9 across all classes) | Confidence carries no class signal — model regressed to mean ≈ 0.82 with std 0.02. Output raster looks flat. |
|
| 56 |
+
| **V7 run2** (window-level classification on `sample_category`) | Studio output a single polygon covering the entire 13,000 km² AOI, labeled `other` | "Window-level" inference applied to a whole AOI = one prediction for the whole region = majority class |
|
| 57 |
+
| **What V8 enables** (per-pixel regression on **`sample_karst_score`**) | Per-pixel regression with a binary 0/1 target | Each pixel gets a genuine `P(karst)` value. Map is interpretable, thresholdable, AUC-evaluatable. |
|
| 58 |
+
|
| 59 |
+
## Studio import — recommended workflow
|
| 60 |
+
|
| 61 |
+
The dataset includes pre-built Studio import files at both `.geojson` and `.json` extensions (Windows MIME pitfall #4):
|
| 62 |
+
|
| 63 |
+
```
|
| 64 |
+
studio/
|
| 65 |
+
├── import_full.geojson + .json # 40,989 features (over Studio's 10K cap — use shards)
|
| 66 |
+
└── shards/
|
| 67 |
+
├── region_00_lon-78.67_to_-77.74.{geojson,json} # 8,198 features (W)
|
| 68 |
+
├── region_01_lon-77.74_to_-77.15.{geojson,json} # 8,198
|
| 69 |
+
├── region_02_lon-77.15_to_-76.34.{geojson,json} # 8,198
|
| 70 |
+
├── region_03_lon-76.34_to_-75.70.{geojson,json} # 8,198
|
| 71 |
+
└── region_04_lon-75.70_to_-74.97.{geojson,json} # 8,197 (E)
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
Upload the 5 shards as 5 separate Studio "regions" — each fits under the 1-hour upload limit and is geographically coherent (longitude-sorted, not random).
|
| 75 |
+
|
| 76 |
+
## Recommended Studio model config for V8
|
| 77 |
+
|
| 78 |
+
| Wizard step | Choice | Rationale |
|
| 79 |
+
|---|---|---|
|
| 80 |
+
| Model type | **Per-pixel regression** | Continuous raster output, what V6 was trying to be |
|
| 81 |
+
| Label field | **`sample_karst_score`** | The new binary target — must appear in the dropdown alongside `sample_number` |
|
| 82 |
+
| Foundation model | OlmoEarth-v1 default | |
|
| 83 |
+
| Temporal context | A period of time, 12 months, January start | Persistent geomorphic features |
|
| 84 |
+
| Image sources | Sentinel-2 only (Sentinel-1 optional for run upgrade) | Backbone is S2-trained |
|
| 85 |
+
| Patch size | 640 m × 640 m | Captures all 4 feature scales + lithology context |
|
| 86 |
+
| Inference AOI | One Central tile from the 2×2 split (or all 4 sequentially) | Studio's 10,000 km² inference cap |
|
| 87 |
+
|
| 88 |
+
Expected output: a single-band 10 m float raster with values in `[0, 1]` interpretable as `P(karst)`.
|
| 89 |
+
|
| 90 |
+
## Audit results
|
| 91 |
+
|
| 92 |
+
Ran with `scripts/audit.py` from the `olmoearth-data-prep` skill:
|
| 93 |
+
|
| 94 |
+
```
|
| 95 |
+
[PASS] Volume: 40989 samples
|
| 96 |
+
[PASS] Schema: studio_import (properties.sample_category) on all 40989
|
| 97 |
+
[PASS] Class distribution: 4 classes, max/min ratio = 9.9
|
| 98 |
+
[PASS] Per-class volume: all classes >= 30 samples
|
| 99 |
+
[PASS] Negative class: 'other' present
|
| 100 |
+
[PASS] Spatial distribution: largest of 4 k-means clusters holds 32% of points
|
| 101 |
+
[PASS] Polygon cleanliness: n/a (point dataset)
|
| 102 |
+
```
|
v8/HF_UPLOAD_INSTRUCTIONS.md
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# HuggingFace upload instructions — Karst v8
|
| 2 |
+
|
| 3 |
+
The local rebuild is at `C:\Users\Frank\Downloads\karst_rebuild\`. To push to HF as a new dataset version on `BAIGroup/OlmoEarth-v1-FT-Karst-Groundwater-Base`:
|
| 4 |
+
|
| 5 |
+
## One-time setup (if not done)
|
| 6 |
+
|
| 7 |
+
```powershell
|
| 8 |
+
pip install huggingface_hub
|
| 9 |
+
huggingface-cli login # paste your HF write token (must have write access to BAIGroup org)
|
| 10 |
+
```
|
| 11 |
+
|
| 12 |
+
## Upload commands
|
| 13 |
+
|
| 14 |
+
```powershell
|
| 15 |
+
cd C:\Users\Frank\Downloads\karst_rebuild
|
| 16 |
+
|
| 17 |
+
# 1. Upload the new parquet (replaces or sits alongside the existing one)
|
| 18 |
+
huggingface-cli upload BAIGroup/OlmoEarth-v1-FT-Karst-Groundwater-Base `
|
| 19 |
+
balanced_karst_v8.parquet `
|
| 20 |
+
v8/balanced_karst_v8.parquet `
|
| 21 |
+
--repo-type dataset
|
| 22 |
+
|
| 23 |
+
# 2. Upload the studio/ folder (import_full + 5 shards, .geojson + .json each)
|
| 24 |
+
huggingface-cli upload BAIGroup/OlmoEarth-v1-FT-Karst-Groundwater-Base `
|
| 25 |
+
studio `
|
| 26 |
+
v8/studio `
|
| 27 |
+
--repo-type dataset
|
| 28 |
+
|
| 29 |
+
# 3. Upload the addendum so the dataset card documents the v8 changes
|
| 30 |
+
huggingface-cli upload BAIGroup/OlmoEarth-v1-FT-Karst-Groundwater-Base `
|
| 31 |
+
DATASET_CARD_ADDENDUM.md `
|
| 32 |
+
v8/DATASET_CARD_ADDENDUM.md `
|
| 33 |
+
--repo-type dataset
|
| 34 |
+
|
| 35 |
+
# 4. Upload rebuild summary
|
| 36 |
+
huggingface-cli upload BAIGroup/OlmoEarth-v1-FT-Karst-Groundwater-Base `
|
| 37 |
+
rebuild_summary.csv `
|
| 38 |
+
v8/rebuild_summary.csv `
|
| 39 |
+
--repo-type dataset
|
| 40 |
+
|
| 41 |
+
# 5. Upload the build script for reproducibility
|
| 42 |
+
huggingface-cli upload BAIGroup/OlmoEarth-v1-FT-Karst-Groundwater-Base `
|
| 43 |
+
build_balanced_karst_dataset.py `
|
| 44 |
+
v8/build_balanced_karst_dataset.py `
|
| 45 |
+
--repo-type dataset
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
## Alternative: single-shot via Python
|
| 49 |
+
|
| 50 |
+
```python
|
| 51 |
+
from huggingface_hub import HfApi
|
| 52 |
+
api = HfApi()
|
| 53 |
+
api.upload_folder(
|
| 54 |
+
folder_path=r"C:\Users\Frank\Downloads\karst_rebuild",
|
| 55 |
+
repo_id="BAIGroup/OlmoEarth-v1-FT-Karst-Groundwater-Base",
|
| 56 |
+
repo_type="dataset",
|
| 57 |
+
path_in_repo="v8",
|
| 58 |
+
commit_message="v8: rebalanced + sample_karst_score for per-pixel binary karst regression",
|
| 59 |
+
)
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
## Merging the dataset card
|
| 63 |
+
|
| 64 |
+
The existing README.md on HF stays as-is. The new `DATASET_CARD_ADDENDUM.md` documents v8 specifically. Option to keep them separate or merge into README later.
|
| 65 |
+
|
| 66 |
+
If you want to merge into README.md, just append the contents of `DATASET_CARD_ADDENDUM.md` to the existing README before pushing. The YAML frontmatter at the top of the addendum should be stripped if merging into a file that already has frontmatter.
|
| 67 |
+
|
| 68 |
+
## After upload — verify on HF
|
| 69 |
+
|
| 70 |
+
1. Visit https://huggingface.co/datasets/BAIGroup/OlmoEarth-v1-FT-Karst-Groundwater-Base/tree/main/v8
|
| 71 |
+
2. Confirm files: `balanced_karst_v8.parquet`, `studio/import_full.geojson`, `studio/shards/region_00..04`
|
| 72 |
+
3. Click the parquet to check schema includes the new columns: `task_name`, `sample_karst_score`
|
| 73 |
+
|
| 74 |
+
## Studio import — what to upload
|
| 75 |
+
|
| 76 |
+
You have two options for the V8 run:
|
| 77 |
+
|
| 78 |
+
### Option A: Single combined upload (preferred if Studio accepts ~16 MB file)
|
| 79 |
+
Upload `studio/import_full.geojson` (or `.json` if Windows MIME blocks the .geojson).
|
| 80 |
+
|
| 81 |
+
### Option B: 5-shard upload (if Studio chokes on 40K records)
|
| 82 |
+
Upload each of `studio/shards/region_NN.geojson` as a separate region in Studio. They're pre-sorted W-to-E so each shard is geographically coherent.
|
| 83 |
+
|
| 84 |
+
## V8 model wizard reminder
|
| 85 |
+
|
| 86 |
+
| Step | Choose |
|
| 87 |
+
|---|---|
|
| 88 |
+
| Model type | **Per-pixel regression** |
|
| 89 |
+
| Label field | **`sample_karst_score`** (should now appear alongside `sample_number`) |
|
| 90 |
+
| Period | 12 months annual, January start |
|
| 91 |
+
| Imagery | Sentinel-2 |
|
| 92 |
+
| Patch | 640 m × 640 m |
|
| 93 |
+
| Training AOI | Central (or Central + East for surface_mine count) |
|
| 94 |
+
| Inference AOI | Central 2×2 tile split (each ≤ 3,200 km², well under Studio's 10,000 km² cap) |
|
v8/balanced_karst_v8.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:49e6125a0dfcc1085e4e3bec616a49959450fa24ff7f917d25339facd2b349e4
|
| 3 |
+
size 908984
|
v8/build_balanced_karst_dataset.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Rebuild Karst dataset for OlmoEarth Studio with proper balance + sample_karst_score.
|
| 2 |
+
|
| 3 |
+
Steps:
|
| 4 |
+
1. Pull parquet from BAIGroup/OlmoEarth-v1-FT-Karst-Groundwater-Base
|
| 5 |
+
2. Assign AOI (east / central / west) by longitude
|
| 6 |
+
3. Soft-balance: keep all 22,021 positives + sample 22,021 "other" → 44k features 1:1 karst binary
|
| 7 |
+
4. Add sample_karst_score (0/1) while keeping sample_number (confidence) untouched
|
| 8 |
+
5. Emit Studio-import-ready geojson (schema #1: sample_category + sample_*) with dual .geojson/.json
|
| 9 |
+
6. Auto-shard at 10K (sorted by longitude per pitfall #6) — Studio 1-hour upload cap
|
| 10 |
+
7. Also emit parquet for HF upload
|
| 11 |
+
8. Emit dataset_card_addendum.md documenting the new field
|
| 12 |
+
"""
|
| 13 |
+
import json
|
| 14 |
+
import shutil
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
import numpy as np
|
| 17 |
+
import pandas as pd
|
| 18 |
+
|
| 19 |
+
OUT = Path(r"C:\Users\Frank\Downloads\karst_rebuild")
|
| 20 |
+
OUT.mkdir(exist_ok=True, parents=True)
|
| 21 |
+
PARQUET_URL = "https://huggingface.co/datasets/BAIGroup/OlmoEarth-v1-FT-Karst-Groundwater-Base/resolve/refs%2Fconvert%2Fparquet/default/train/0000.parquet"
|
| 22 |
+
|
| 23 |
+
# Longitude thresholds for PA AOI assignment (verified against run2 raster bounds)
|
| 24 |
+
LON_WEST_MAX = -78.5 # west: lon < -78.5
|
| 25 |
+
LON_CENTRAL_MAX = -76.5 # central: -78.5 <= lon < -76.5
|
| 26 |
+
# east: lon >= -76.5
|
| 27 |
+
|
| 28 |
+
# Studio 1-hour upload cap per shard
|
| 29 |
+
MAX_PER_SHARD = 10000
|
| 30 |
+
|
| 31 |
+
# RNG seed for reproducibility
|
| 32 |
+
RNG = np.random.default_rng(42)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def assign_aoi(lon: float) -> str:
|
| 36 |
+
if lon < LON_WEST_MAX:
|
| 37 |
+
return "pa_karst_west"
|
| 38 |
+
if lon < LON_CENTRAL_MAX:
|
| 39 |
+
return "pa_karst_central"
|
| 40 |
+
return "pa_karst_east"
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def main():
|
| 44 |
+
print("=" * 72)
|
| 45 |
+
print("Karst dataset rebuild — balanced + sample_karst_score")
|
| 46 |
+
print("=" * 72)
|
| 47 |
+
|
| 48 |
+
# ---- 1. Pull parquet ----
|
| 49 |
+
print(f"\n[1] Fetching parquet from HF...")
|
| 50 |
+
df = pd.read_parquet(PARQUET_URL)
|
| 51 |
+
print(f" loaded {len(df):,} rows / columns: {list(df.columns)}")
|
| 52 |
+
|
| 53 |
+
# ---- 2. AOI assignment ----
|
| 54 |
+
print(f"\n[2] Assigning AOIs by longitude (W<{LON_WEST_MAX}, C<{LON_CENTRAL_MAX}, E>=)...")
|
| 55 |
+
df["task_name"] = df["lon"].apply(assign_aoi)
|
| 56 |
+
print("\n AOI distribution:")
|
| 57 |
+
print(df["task_name"].value_counts().to_string())
|
| 58 |
+
|
| 59 |
+
# ---- 3. Soft balance: all positives + sampled negatives 1:1 ----
|
| 60 |
+
print(f"\n[3] Soft balance — keep all positives, subsample 'other' to 1:1 binary ratio")
|
| 61 |
+
print("\n Original class distribution:")
|
| 62 |
+
print(df["tag"].value_counts().to_string())
|
| 63 |
+
|
| 64 |
+
positives = df[df["tag"] != "other"].copy()
|
| 65 |
+
negatives = df[df["tag"] == "other"].copy()
|
| 66 |
+
n_pos = len(positives)
|
| 67 |
+
# Cap "other" at 9.9x the smallest class to satisfy audit pitfall #5 (max/min ratio < 10)
|
| 68 |
+
min_class_count = positives["tag"].value_counts().min() # surface_mine = 1,916
|
| 69 |
+
n_neg_target = min(n_pos, int(min_class_count * 9.9)) # = 18,968 — passes audit
|
| 70 |
+
print(f" smallest class count: {min_class_count:,} (surface_mine)")
|
| 71 |
+
print(f" capping 'other' at 9.9x = {n_neg_target:,} to keep max/min ratio < 10")
|
| 72 |
+
|
| 73 |
+
# Stratified sample of negatives by AOI to preserve regional proportion
|
| 74 |
+
print(f"\n positives total: {n_pos:,} / target negatives: {n_neg_target:,}")
|
| 75 |
+
neg_per_aoi = negatives["task_name"].value_counts()
|
| 76 |
+
print(f" negatives per AOI before sampling:")
|
| 77 |
+
print(neg_per_aoi.to_string())
|
| 78 |
+
|
| 79 |
+
# Proportional allocation across AOIs
|
| 80 |
+
sampled_neg = []
|
| 81 |
+
for aoi, total_in_aoi in neg_per_aoi.items():
|
| 82 |
+
# match each AOI's negative share to its share of original negatives
|
| 83 |
+
share = total_in_aoi / negatives.shape[0]
|
| 84 |
+
n_take = int(round(n_neg_target * share))
|
| 85 |
+
n_take = min(n_take, total_in_aoi)
|
| 86 |
+
aoi_negs = negatives[negatives["task_name"] == aoi]
|
| 87 |
+
sampled_neg.append(aoi_negs.sample(n=n_take, random_state=42))
|
| 88 |
+
print(f" {aoi}: sampling {n_take:,} of {total_in_aoi:,} negatives ({share*100:.1f}% share)")
|
| 89 |
+
neg_sampled = pd.concat(sampled_neg, ignore_index=True)
|
| 90 |
+
|
| 91 |
+
combined = pd.concat([positives, neg_sampled], ignore_index=True)
|
| 92 |
+
combined = combined.sample(frac=1, random_state=42).reset_index(drop=True) # shuffle
|
| 93 |
+
print(f"\n combined dataset: {len(combined):,} rows")
|
| 94 |
+
print(f" final class distribution:")
|
| 95 |
+
print(combined["tag"].value_counts().to_string())
|
| 96 |
+
print(f" final AOI distribution:")
|
| 97 |
+
print(combined["task_name"].value_counts().to_string())
|
| 98 |
+
|
| 99 |
+
# ---- 4. Add sample_karst_score (the whole point) ----
|
| 100 |
+
print(f"\n[4] Adding sample_karst_score field (0.0=other, 1.0=karst)")
|
| 101 |
+
combined["sample_karst_score"] = np.where(combined["tag"] == "other", 0.0, 1.0)
|
| 102 |
+
print(" sample_karst_score distribution:")
|
| 103 |
+
print(combined["sample_karst_score"].value_counts().to_string())
|
| 104 |
+
|
| 105 |
+
# Sanity check: class ratio for audit (pitfall #5)
|
| 106 |
+
ratio = combined["tag"].value_counts().max() / combined["tag"].value_counts().min()
|
| 107 |
+
print(f"\n max/min class ratio: {ratio:.1f} (audit warn threshold = 10)")
|
| 108 |
+
|
| 109 |
+
# ---- 5. Build Studio import features (schema #1) ----
|
| 110 |
+
print(f"\n[5] Building Studio import features (schema #1: properties.sample_category)")
|
| 111 |
+
features = []
|
| 112 |
+
for _, row in combined.iterrows():
|
| 113 |
+
# observation_time: use start of label window
|
| 114 |
+
obs_time = str(row["oe_start_time"]).split("+")[0].replace(" ", "T") + "Z"
|
| 115 |
+
feat = {
|
| 116 |
+
"type": "Feature",
|
| 117 |
+
"geometry": {
|
| 118 |
+
"type": "Point",
|
| 119 |
+
"coordinates": [float(row["lon"]), float(row["lat"])],
|
| 120 |
+
},
|
| 121 |
+
"properties": {
|
| 122 |
+
# Studio framework fields (no sample_ prefix)
|
| 123 |
+
"task_name": str(row["task_name"]),
|
| 124 |
+
"observation_time": obs_time,
|
| 125 |
+
# Studio recognized class label
|
| 126 |
+
"sample_category": str(row["tag"]),
|
| 127 |
+
# Original confidence preserved as sample_number (Studio's recognized numeric field)
|
| 128 |
+
"sample_number": float(row["confidence"]),
|
| 129 |
+
# NEW: binary karst regression target
|
| 130 |
+
"sample_karst_score": float(row["sample_karst_score"]),
|
| 131 |
+
# auto_generated flag (matches original Studio mapping)
|
| 132 |
+
"sample_true_false": bool(row["auto_generated"]),
|
| 133 |
+
# Extra audit fields (Studio ignores, useful for downstream)
|
| 134 |
+
"sample_quality_flags": str(row["quality_flags"]) if pd.notna(row["quality_flags"]) else "",
|
| 135 |
+
"sample_merged_from_cave": bool(row["merged_from_cave"]),
|
| 136 |
+
},
|
| 137 |
+
}
|
| 138 |
+
features.append(feat)
|
| 139 |
+
print(f" built {len(features):,} features")
|
| 140 |
+
|
| 141 |
+
# ---- 6. Spatial sort + shard at MAX_PER_SHARD ----
|
| 142 |
+
print(f"\n[6] Spatial-sort by longitude + shard at {MAX_PER_SHARD:,}/shard (pitfalls #6, #7)")
|
| 143 |
+
features.sort(key=lambda f: f["geometry"]["coordinates"][0]) # sort by lon
|
| 144 |
+
n_shards = (len(features) + MAX_PER_SHARD - 1) // MAX_PER_SHARD
|
| 145 |
+
shard_size = (len(features) + n_shards - 1) // n_shards
|
| 146 |
+
shards = [features[i : i + shard_size] for i in range(0, len(features), shard_size)]
|
| 147 |
+
print(f" -> {len(shards)} shards of ~{shard_size:,} each (sorted W-to-E)")
|
| 148 |
+
|
| 149 |
+
# ---- 7. Write outputs ----
|
| 150 |
+
print(f"\n[7] Writing outputs to {OUT}")
|
| 151 |
+
|
| 152 |
+
# Full combined file (one big import.geojson + .json, before sharding — for reference)
|
| 153 |
+
fc_full = {"type": "FeatureCollection", "features": features}
|
| 154 |
+
full_gj = OUT / "studio" / "import_full.geojson"
|
| 155 |
+
full_gj.parent.mkdir(exist_ok=True, parents=True)
|
| 156 |
+
full_gj.write_text(json.dumps(fc_full))
|
| 157 |
+
shutil.copy2(full_gj, OUT / "studio" / "import_full.json")
|
| 158 |
+
print(f" wrote studio/import_full.geojson + .json ({len(features):,} features)")
|
| 159 |
+
|
| 160 |
+
# Sharded files (Studio uploads — these are what user uses)
|
| 161 |
+
shards_dir = OUT / "studio" / "shards"
|
| 162 |
+
shards_dir.mkdir(exist_ok=True)
|
| 163 |
+
for i, shard in enumerate(shards):
|
| 164 |
+
# Determine geographic descriptor for shard
|
| 165 |
+
lons = [f["geometry"]["coordinates"][0] for f in shard]
|
| 166 |
+
lon_range = f"{min(lons):.2f}_to_{max(lons):.2f}"
|
| 167 |
+
name = f"region_{i:02d}_lon{lon_range}"
|
| 168 |
+
gj_path = shards_dir / f"{name}.geojson"
|
| 169 |
+
json_path = shards_dir / f"{name}.json"
|
| 170 |
+
gj_path.write_text(json.dumps({"type": "FeatureCollection", "features": shard}))
|
| 171 |
+
shutil.copy2(gj_path, json_path)
|
| 172 |
+
print(f" wrote shards/{name}.{{geojson,json}} ({len(shard):,} features)")
|
| 173 |
+
|
| 174 |
+
# Parquet (HF dataset payload)
|
| 175 |
+
parquet_path = OUT / "balanced_karst_v8.parquet"
|
| 176 |
+
# Add task_name + sample_karst_score columns to parquet
|
| 177 |
+
parquet_df = combined[[
|
| 178 |
+
"category", "tag", "lon", "lat", "oe_start_time", "oe_end_time",
|
| 179 |
+
"oe_annotations_task_id", "confidence", "quality_flags",
|
| 180 |
+
"auto_generated", "merged_from_cave",
|
| 181 |
+
# NEW columns
|
| 182 |
+
"task_name", "sample_karst_score",
|
| 183 |
+
]].copy()
|
| 184 |
+
parquet_df.to_parquet(parquet_path, index=False)
|
| 185 |
+
print(f" wrote {parquet_path.name} ({len(parquet_df):,} rows, {len(parquet_df.columns)} cols)")
|
| 186 |
+
|
| 187 |
+
# Summary CSV for the user's records
|
| 188 |
+
summary = pd.DataFrame({
|
| 189 |
+
"metric": [
|
| 190 |
+
"total_features",
|
| 191 |
+
"n_positives (karst)",
|
| 192 |
+
"n_negatives (other)",
|
| 193 |
+
"n_west",
|
| 194 |
+
"n_central",
|
| 195 |
+
"n_east",
|
| 196 |
+
"max_min_class_ratio",
|
| 197 |
+
"sample_karst_score_mean",
|
| 198 |
+
"n_shards",
|
| 199 |
+
"shard_size_target",
|
| 200 |
+
],
|
| 201 |
+
"value": [
|
| 202 |
+
len(combined),
|
| 203 |
+
int((combined["sample_karst_score"] == 1.0).sum()),
|
| 204 |
+
int((combined["sample_karst_score"] == 0.0).sum()),
|
| 205 |
+
int((combined["task_name"] == "pa_karst_west").sum()),
|
| 206 |
+
int((combined["task_name"] == "pa_karst_central").sum()),
|
| 207 |
+
int((combined["task_name"] == "pa_karst_east").sum()),
|
| 208 |
+
round(ratio, 2),
|
| 209 |
+
round(combined["sample_karst_score"].mean(), 3),
|
| 210 |
+
len(shards),
|
| 211 |
+
shard_size,
|
| 212 |
+
],
|
| 213 |
+
})
|
| 214 |
+
summary_path = OUT / "rebuild_summary.csv"
|
| 215 |
+
summary.to_csv(summary_path, index=False)
|
| 216 |
+
print(f" wrote {summary_path.name}")
|
| 217 |
+
|
| 218 |
+
print(f"\n{'=' * 72}")
|
| 219 |
+
print("DONE. Run audit next:")
|
| 220 |
+
print(f" python {Path(r'C:/Users/Frank/.claude/skills/olmoearth-data-prep/scripts/audit.py')} {full_gj}")
|
| 221 |
+
print(f"{'=' * 72}")
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
if __name__ == "__main__":
|
| 225 |
+
main()
|
v8/evaluate_v8_vs_v6.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""evaluate_v8_vs_v6.py
|
| 2 |
+
|
| 3 |
+
V8 vs V6 evaluation harness for the Karst per-pixel regression task.
|
| 4 |
+
|
| 5 |
+
What it does:
|
| 6 |
+
1. Samples V8 (and V6) raster values at every labeled point in the v8 parquet
|
| 7 |
+
2. Computes AUC of sample_karst_score against model predictions:
|
| 8 |
+
- in-sample (all labels)
|
| 9 |
+
- held-out-by-shard (longitude-banded, mimics spatial CV)
|
| 10 |
+
3. Plots per-class score distributions, ROC curves, and spatial diff maps
|
| 11 |
+
4. Reports the value-distribution fingerprint (was V6's mean=0.82 std=0.02 fixed?)
|
| 12 |
+
5. Writes everything to <out_dir>/
|
| 13 |
+
|
| 14 |
+
Usage:
|
| 15 |
+
python evaluate_v8_vs_v6.py ^
|
| 16 |
+
--v8-rasters "C:\\Users\\Frank\\Downloads\\PA_KARST_Central_V8_run*\\*.tif" ^
|
| 17 |
+
--v6-rasters "C:\\Users\\Frank\\Downloads\\PA_KARST_Central_V6_run2\\*.tif" ^
|
| 18 |
+
--labels "C:\\Users\\Frank\\Downloads\\karst_rebuild\\balanced_karst_v8.parquet" ^
|
| 19 |
+
--out "C:\\Users\\Frank\\Downloads\\v8_vs_v6_eval"
|
| 20 |
+
|
| 21 |
+
Dependencies: rasterio, numpy, pandas, matplotlib, scikit-learn
|
| 22 |
+
"""
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
import argparse
|
| 25 |
+
import glob
|
| 26 |
+
import json
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
import sys
|
| 29 |
+
|
| 30 |
+
import numpy as np
|
| 31 |
+
import pandas as pd
|
| 32 |
+
import rasterio
|
| 33 |
+
from rasterio.warp import transform as warp_transform
|
| 34 |
+
import matplotlib.pyplot as plt
|
| 35 |
+
from sklearn.metrics import roc_auc_score, roc_curve, average_precision_score
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def expand_rasters(patterns: list[str]) -> list[Path]:
|
| 39 |
+
"""Resolve glob patterns to a flat list of raster paths."""
|
| 40 |
+
out = []
|
| 41 |
+
for p in patterns:
|
| 42 |
+
matches = sorted(glob.glob(p))
|
| 43 |
+
if not matches:
|
| 44 |
+
print(f" WARN: no rasters match '{p}'")
|
| 45 |
+
out.extend(Path(m) for m in matches)
|
| 46 |
+
return out
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def sample_raster_at_points(raster: Path, lons: np.ndarray, lats: np.ndarray) -> np.ndarray:
|
| 50 |
+
"""Sample raster value at each (lon, lat). Returns NaN for points outside raster."""
|
| 51 |
+
with rasterio.open(raster) as ds:
|
| 52 |
+
# Transform WGS84 points to raster CRS
|
| 53 |
+
xs, ys = warp_transform("EPSG:4326", ds.crs, lons.tolist(), lats.tolist())
|
| 54 |
+
xs = np.array(xs)
|
| 55 |
+
ys = np.array(ys)
|
| 56 |
+
|
| 57 |
+
# Convert to row/col indices
|
| 58 |
+
# rasterio's index() takes (x, y) one at a time; vectorize via Affine inverse
|
| 59 |
+
inv = ~ds.transform
|
| 60 |
+
cols_f, rows_f = inv * (xs, ys)
|
| 61 |
+
cols = np.round(cols_f).astype(int)
|
| 62 |
+
rows = np.round(rows_f).astype(int)
|
| 63 |
+
|
| 64 |
+
# Mask out-of-bounds
|
| 65 |
+
h, w = ds.shape
|
| 66 |
+
valid = (rows >= 0) & (rows < h) & (cols >= 0) & (cols < w)
|
| 67 |
+
|
| 68 |
+
# Read raster (small enough — 1 band)
|
| 69 |
+
arr = ds.read(1)
|
| 70 |
+
nd = ds.nodata
|
| 71 |
+
|
| 72 |
+
out = np.full(len(lons), np.nan)
|
| 73 |
+
out[valid] = arr[rows[valid], cols[valid]]
|
| 74 |
+
if nd is not None:
|
| 75 |
+
out[out == nd] = np.nan
|
| 76 |
+
return out
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def sample_multi_raster(rasters: list[Path], lons: np.ndarray, lats: np.ndarray) -> np.ndarray:
|
| 80 |
+
"""Sample across multiple rasters; for each point use first raster that contains it."""
|
| 81 |
+
if not rasters:
|
| 82 |
+
return np.full(len(lons), np.nan)
|
| 83 |
+
out = np.full(len(lons), np.nan)
|
| 84 |
+
for r in rasters:
|
| 85 |
+
vals = sample_raster_at_points(r, lons, lats)
|
| 86 |
+
mask = np.isnan(out) & ~np.isnan(vals)
|
| 87 |
+
out[mask] = vals[mask]
|
| 88 |
+
return out
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def value_fingerprint(name: str, vals: np.ndarray) -> dict:
|
| 92 |
+
v = vals[~np.isnan(vals)]
|
| 93 |
+
if len(v) == 0:
|
| 94 |
+
return {"name": name, "n": 0}
|
| 95 |
+
return {
|
| 96 |
+
"name": name,
|
| 97 |
+
"n": int(len(v)),
|
| 98 |
+
"min": float(v.min()),
|
| 99 |
+
"p1": float(np.percentile(v, 1)),
|
| 100 |
+
"p25": float(np.percentile(v, 25)),
|
| 101 |
+
"mean": float(v.mean()),
|
| 102 |
+
"median": float(np.median(v)),
|
| 103 |
+
"p75": float(np.percentile(v, 75)),
|
| 104 |
+
"p99": float(np.percentile(v, 99)),
|
| 105 |
+
"max": float(v.max()),
|
| 106 |
+
"std": float(v.std()),
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def compute_aucs(y: np.ndarray, scores: np.ndarray, label: str) -> dict:
|
| 111 |
+
"""ROC-AUC + PR-AUC + summary. Returns NaN entries if data is missing."""
|
| 112 |
+
mask = ~np.isnan(scores) & ~np.isnan(y)
|
| 113 |
+
if mask.sum() < 20 or len(np.unique(y[mask])) < 2:
|
| 114 |
+
return {"label": label, "n": int(mask.sum()), "roc_auc": float("nan"), "pr_auc": float("nan")}
|
| 115 |
+
return {
|
| 116 |
+
"label": label,
|
| 117 |
+
"n": int(mask.sum()),
|
| 118 |
+
"roc_auc": float(roc_auc_score(y[mask], scores[mask])),
|
| 119 |
+
"pr_auc": float(average_precision_score(y[mask], scores[mask])),
|
| 120 |
+
"positive_rate": float(y[mask].mean()),
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def plot_score_histograms(df: pd.DataFrame, score_col: str, model_name: str, out_path: Path):
|
| 125 |
+
fig, ax = plt.subplots(1, 1, figsize=(8, 5))
|
| 126 |
+
valid = df.dropna(subset=[score_col])
|
| 127 |
+
for cat, color in zip(
|
| 128 |
+
["other", "surface_depression", "sinkhole", "surface_mine"],
|
| 129 |
+
["#888", "#d62728", "#2ca02c", "#1f77b4"],
|
| 130 |
+
):
|
| 131 |
+
sub = valid[valid["sample_category"] == cat]
|
| 132 |
+
if len(sub):
|
| 133 |
+
ax.hist(
|
| 134 |
+
sub[score_col], bins=50, alpha=0.5, label=f"{cat} (n={len(sub):,})",
|
| 135 |
+
color=color, density=True,
|
| 136 |
+
)
|
| 137 |
+
ax.set_xlabel(f"{model_name} predicted score at label point")
|
| 138 |
+
ax.set_ylabel("density")
|
| 139 |
+
ax.set_title(f"{model_name} score distribution by true class")
|
| 140 |
+
ax.legend()
|
| 141 |
+
ax.grid(alpha=0.3)
|
| 142 |
+
fig.tight_layout()
|
| 143 |
+
fig.savefig(out_path, dpi=120)
|
| 144 |
+
plt.close(fig)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def plot_roc(y: np.ndarray, scores: dict[str, np.ndarray], out_path: Path):
|
| 148 |
+
fig, ax = plt.subplots(1, 1, figsize=(6, 6))
|
| 149 |
+
for name, s in scores.items():
|
| 150 |
+
mask = ~np.isnan(s) & ~np.isnan(y)
|
| 151 |
+
if mask.sum() < 20 or len(np.unique(y[mask])) < 2:
|
| 152 |
+
continue
|
| 153 |
+
fpr, tpr, _ = roc_curve(y[mask], s[mask])
|
| 154 |
+
auc = roc_auc_score(y[mask], s[mask])
|
| 155 |
+
ax.plot(fpr, tpr, lw=2, label=f"{name} AUC={auc:.3f}")
|
| 156 |
+
ax.plot([0, 1], [0, 1], color="gray", lw=1, linestyle="--", label="random")
|
| 157 |
+
ax.set_xlabel("FPR"); ax.set_ylabel("TPR")
|
| 158 |
+
ax.set_title("ROC — V6 (regression on confidence) vs V8 (regression on sample_karst_score)")
|
| 159 |
+
ax.legend(loc="lower right")
|
| 160 |
+
ax.grid(alpha=0.3)
|
| 161 |
+
fig.tight_layout()
|
| 162 |
+
fig.savefig(out_path, dpi=120)
|
| 163 |
+
plt.close(fig)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def plot_v8_v6_scatter(df: pd.DataFrame, out_path: Path):
|
| 167 |
+
"""Scatter V8 score vs V6 score, colored by true class."""
|
| 168 |
+
fig, ax = plt.subplots(1, 1, figsize=(7, 7))
|
| 169 |
+
valid = df.dropna(subset=["v8_score", "v6_score"])
|
| 170 |
+
for cat, color in zip(
|
| 171 |
+
["other", "surface_depression", "sinkhole", "surface_mine"],
|
| 172 |
+
["#888", "#d62728", "#2ca02c", "#1f77b4"],
|
| 173 |
+
):
|
| 174 |
+
sub = valid[valid["sample_category"] == cat]
|
| 175 |
+
if len(sub):
|
| 176 |
+
ax.scatter(sub["v6_score"], sub["v8_score"], s=2, alpha=0.3, color=color, label=f"{cat} (n={len(sub):,})")
|
| 177 |
+
ax.set_xlabel("V6 score (regression on confidence)")
|
| 178 |
+
ax.set_ylabel("V8 score (regression on sample_karst_score)")
|
| 179 |
+
ax.set_title("V8 vs V6 — point-wise comparison\n(want V8 to spread; V6 was stuck near 0.82)")
|
| 180 |
+
ax.legend(markerscale=4, loc="upper left")
|
| 181 |
+
ax.grid(alpha=0.3)
|
| 182 |
+
fig.tight_layout()
|
| 183 |
+
fig.savefig(out_path, dpi=120)
|
| 184 |
+
plt.close(fig)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def spatial_holdout(df: pd.DataFrame, k: int = 5) -> pd.Series:
|
| 188 |
+
"""Assign each point to a longitude-banded fold (0..k-1). Mimics how we sharded."""
|
| 189 |
+
sorted_idx = df["lon"].sort_values().index
|
| 190 |
+
fold = pd.Series(0, index=df.index, dtype=int)
|
| 191 |
+
band_size = len(df) // k
|
| 192 |
+
for i in range(k):
|
| 193 |
+
start = i * band_size
|
| 194 |
+
end = (i + 1) * band_size if i < k - 1 else len(df)
|
| 195 |
+
fold.loc[sorted_idx[start:end]] = i
|
| 196 |
+
return fold
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def main():
|
| 200 |
+
ap = argparse.ArgumentParser(description="V8 vs V6 evaluation")
|
| 201 |
+
ap.add_argument("--v8-rasters", nargs="+", required=True,
|
| 202 |
+
help="V8 prediction raster path(s) — supports globs (use quotes)")
|
| 203 |
+
ap.add_argument("--v6-rasters", nargs="*", default=[],
|
| 204 |
+
help="V6 raster path(s) for comparison. Optional but recommended.")
|
| 205 |
+
ap.add_argument("--labels", required=True,
|
| 206 |
+
help="balanced_karst_v8.parquet path")
|
| 207 |
+
ap.add_argument("--out", required=True, help="Output directory")
|
| 208 |
+
ap.add_argument("--holdout-fold", type=int, default=2,
|
| 209 |
+
help="Which longitude band (0..4) to treat as held-out for spatial-CV AUC (default 2 = middle)")
|
| 210 |
+
args = ap.parse_args()
|
| 211 |
+
|
| 212 |
+
out = Path(args.out)
|
| 213 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 214 |
+
|
| 215 |
+
print(f"[1] Loading labels from {args.labels}")
|
| 216 |
+
df = pd.read_parquet(args.labels)
|
| 217 |
+
print(f" {len(df):,} rows / classes: {df['sample_category'].value_counts().to_dict() if 'sample_category' in df.columns else df['tag'].value_counts().to_dict()}")
|
| 218 |
+
# Column compat: parquet has 'tag' and 'sample_karst_score' from build script
|
| 219 |
+
if "sample_category" not in df.columns and "tag" in df.columns:
|
| 220 |
+
df["sample_category"] = df["tag"]
|
| 221 |
+
|
| 222 |
+
y = df["sample_karst_score"].values
|
| 223 |
+
lons = df["lon"].values.astype(float)
|
| 224 |
+
lats = df["lat"].values.astype(float)
|
| 225 |
+
|
| 226 |
+
print(f"\n[2] Resolving V8 rasters...")
|
| 227 |
+
v8_paths = expand_rasters(args.v8_rasters)
|
| 228 |
+
print(f" found {len(v8_paths)} V8 raster(s):")
|
| 229 |
+
for p in v8_paths:
|
| 230 |
+
print(f" {p}")
|
| 231 |
+
|
| 232 |
+
v6_paths = expand_rasters(args.v6_rasters) if args.v6_rasters else []
|
| 233 |
+
if v6_paths:
|
| 234 |
+
print(f"\n[3] Resolving V6 rasters...")
|
| 235 |
+
print(f" found {len(v6_paths)} V6 raster(s):")
|
| 236 |
+
for p in v6_paths:
|
| 237 |
+
print(f" {p}")
|
| 238 |
+
|
| 239 |
+
if not v8_paths:
|
| 240 |
+
print("ERROR: no V8 rasters found — pass --v8-rasters with valid paths/globs")
|
| 241 |
+
sys.exit(2)
|
| 242 |
+
|
| 243 |
+
print(f"\n[4] Sampling raster values at {len(df):,} label points...")
|
| 244 |
+
df["v8_score"] = sample_multi_raster(v8_paths, lons, lats)
|
| 245 |
+
print(f" V8 valid samples: {(~np.isnan(df['v8_score'])).sum():,} / {len(df):,}")
|
| 246 |
+
|
| 247 |
+
if v6_paths:
|
| 248 |
+
df["v6_score"] = sample_multi_raster(v6_paths, lons, lats)
|
| 249 |
+
print(f" V6 valid samples: {(~np.isnan(df['v6_score'])).sum():,} / {len(df):,}")
|
| 250 |
+
else:
|
| 251 |
+
df["v6_score"] = np.nan
|
| 252 |
+
|
| 253 |
+
print(f"\n[5] Value distribution fingerprints")
|
| 254 |
+
print(f" (V6 ground truth from run2 was: mean=0.82 std=0.02 — flat regression-to-mean failure)")
|
| 255 |
+
fps = []
|
| 256 |
+
for name, col in [("V6", "v6_score"), ("V8", "v8_score")]:
|
| 257 |
+
fp = value_fingerprint(name, df[col].values)
|
| 258 |
+
fps.append(fp)
|
| 259 |
+
if fp.get("n", 0):
|
| 260 |
+
print(f" {name}: n={fp['n']:,} min={fp['min']:.4f} mean={fp['mean']:.4f} std={fp['std']:.4f} max={fp['max']:.4f}")
|
| 261 |
+
print(f" p1={fp['p1']:.4f} p25={fp['p25']:.4f} median={fp['median']:.4f} p75={fp['p75']:.4f} p99={fp['p99']:.4f}")
|
| 262 |
+
pd.DataFrame(fps).to_csv(out / "value_fingerprints.csv", index=False)
|
| 263 |
+
|
| 264 |
+
print(f"\n[6] AUCs — in-sample (all 40,989 labels)")
|
| 265 |
+
in_sample = []
|
| 266 |
+
for name, col in [("V6", "v6_score"), ("V8", "v8_score")]:
|
| 267 |
+
r = compute_aucs(y, df[col].values, f"{name}_in_sample")
|
| 268 |
+
in_sample.append(r)
|
| 269 |
+
if not np.isnan(r.get("roc_auc", np.nan)):
|
| 270 |
+
print(f" {r['label']:>20s} n={r['n']:>6,} ROC-AUC={r['roc_auc']:.4f} PR-AUC={r['pr_auc']:.4f} pos-rate={r['positive_rate']:.3f}")
|
| 271 |
+
else:
|
| 272 |
+
print(f" {r['label']:>20s} no overlap / insufficient data")
|
| 273 |
+
|
| 274 |
+
print(f"\n[7] AUCs — spatial holdout (longitude fold {args.holdout_fold} of 5)")
|
| 275 |
+
df["fold"] = spatial_holdout(df, k=5)
|
| 276 |
+
holdout = df[df["fold"] == args.holdout_fold]
|
| 277 |
+
print(f" holdout n={len(holdout):,} lon range=[{holdout['lon'].min():.2f}, {holdout['lon'].max():.2f}]")
|
| 278 |
+
holdout_aucs = []
|
| 279 |
+
for name, col in [("V6", "v6_score"), ("V8", "v8_score")]:
|
| 280 |
+
r = compute_aucs(holdout["sample_karst_score"].values, holdout[col].values, f"{name}_holdout_fold{args.holdout_fold}")
|
| 281 |
+
holdout_aucs.append(r)
|
| 282 |
+
if not np.isnan(r.get("roc_auc", np.nan)):
|
| 283 |
+
print(f" {r['label']:>30s} n={r['n']:>6,} ROC-AUC={r['roc_auc']:.4f} PR-AUC={r['pr_auc']:.4f}")
|
| 284 |
+
|
| 285 |
+
pd.DataFrame(in_sample + holdout_aucs).to_csv(out / "auc_summary.csv", index=False)
|
| 286 |
+
|
| 287 |
+
print(f"\n[8] Plotting diagnostics...")
|
| 288 |
+
plot_score_histograms(df, "v8_score", "V8", out / "hist_v8_by_class.png")
|
| 289 |
+
print(f" wrote hist_v8_by_class.png")
|
| 290 |
+
if v6_paths:
|
| 291 |
+
plot_score_histograms(df, "v6_score", "V6", out / "hist_v6_by_class.png")
|
| 292 |
+
print(f" wrote hist_v6_by_class.png")
|
| 293 |
+
|
| 294 |
+
scores = {"V8": df["v8_score"].values}
|
| 295 |
+
if v6_paths:
|
| 296 |
+
scores["V6"] = df["v6_score"].values
|
| 297 |
+
plot_roc(y, scores, out / "roc_v8_v6.png")
|
| 298 |
+
print(f" wrote roc_v8_v6.png")
|
| 299 |
+
|
| 300 |
+
if v6_paths:
|
| 301 |
+
plot_v8_v6_scatter(df, out / "scatter_v8_v6.png")
|
| 302 |
+
print(f" wrote scatter_v8_v6.png")
|
| 303 |
+
|
| 304 |
+
# Save full per-point sample table
|
| 305 |
+
df_out = df[["lon", "lat", "task_name", "sample_category", "sample_karst_score", "v8_score", "v6_score", "fold"]]
|
| 306 |
+
df_out.to_csv(out / "per_point_scores.csv", index=False)
|
| 307 |
+
print(f" wrote per_point_scores.csv ({len(df_out):,} rows)")
|
| 308 |
+
|
| 309 |
+
print(f"\n{'=' * 70}")
|
| 310 |
+
print("VERDICT GUIDE:")
|
| 311 |
+
print(f" V6 in-sample AUC was likely ~0.50–0.55 (the regression-to-mean failure)")
|
| 312 |
+
print(f" V8 should target:")
|
| 313 |
+
print(f" - in-sample AUC > 0.80 (model fits)")
|
| 314 |
+
print(f" - holdout AUC > 0.70 (model generalizes spatially)")
|
| 315 |
+
print(f" - value std > 0.10 (real spatial discrimination, not flat 0.82±0.02)")
|
| 316 |
+
print(f" - histogram visibly bimodal (modes near 0 and 1)")
|
| 317 |
+
print(f"{'=' * 70}")
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
if __name__ == "__main__":
|
| 321 |
+
main()
|
v8/rebuild_summary.csv
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
metric,value
|
| 2 |
+
total_features,40989.0
|
| 3 |
+
n_positives (karst),22021.0
|
| 4 |
+
n_negatives (other),18968.0
|
| 5 |
+
n_west,557.0
|
| 6 |
+
n_central,21517.0
|
| 7 |
+
n_east,18915.0
|
| 8 |
+
max_min_class_ratio,9.9
|
| 9 |
+
sample_karst_score_mean,0.537
|
| 10 |
+
n_shards,5.0
|
| 11 |
+
shard_size_target,8198.0
|
v8/studio/import_full.geojson
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:be7a1b76e57ea3877c90ef314f1857c8b60caf165b3e358aa5bd73ef724374c6
|
| 3 |
+
size 16396210
|
v8/studio/import_full.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:be7a1b76e57ea3877c90ef314f1857c8b60caf165b3e358aa5bd73ef724374c6
|
| 3 |
+
size 16396210
|
v8/studio/shards/region_00_lon-78.67_to_-77.74.geojson
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
v8/studio/shards/region_00_lon-78.67_to_-77.74.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
v8/studio/shards/region_01_lon-77.74_to_-77.15.geojson
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
v8/studio/shards/region_01_lon-77.74_to_-77.15.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
v8/studio/shards/region_02_lon-77.15_to_-76.34.geojson
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
v8/studio/shards/region_02_lon-77.15_to_-76.34.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
v8/studio/shards/region_03_lon-76.34_to_-75.70.geojson
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
v8/studio/shards/region_03_lon-76.34_to_-75.70.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
v8/studio/shards/region_04_lon-75.70_to_-74.97.geojson
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
v8/studio/shards/region_04_lon-75.70_to_-74.97.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|