Winner models, code, notebooks, data and results
Browse filesFiles changed (34)
- .gitattributes+2
- README.mdAdded+296
- data/processed/amsterdam_features.parquetAdded+3
- data/processed/madrid_features.parquetAdded+3
- models/amsterdam_robustz_stats.npzAdded+3
- models/meta.jsonAdded+430
- models/retrained_example_shot_indices.jsonAdded+1
- models/retrained_n200_rep0_lgbm.txtAdded
- models/retrained_n25_rep0_lgbm.txtAdded
- models/zero_shot_lgbm.txtAdded+3
- notebooks/01_build_features.ipynbAdded+437
- notebooks/03_gbdt_models.ipynbAdded+747
- notebooks/src/01_build_features.pyAdded+290
- notebooks/src/03_gbdt_models.pyAdded+574
- notebooks/src/winners_demo.pyAdded+171
- notebooks/winners_demo.ipynbAdded
- results/f1_vs_n_full_city.pngAdded
- results/full_score_prototype.jsonAdded+1884
- results/full_score_upweighted.jsonAdded+834
- results/llm_protocol_results_colab.mdAdded+74
- results/logs/01_build_features.logAdded+129
- results/logs/03_gbdt_models.logAdded+305
- results/logs/03_gbdt_models_fullscore_run.logAdded+192
- results/logs/full_score_prototype.logAdded+74
- results/logs/full_score_upweighted.logAdded+37
- results/protocol_results.csvAdded+31
- results/shift_harness.csvAdded+11
- src/config.pyAdded+111
- src/evaluation.pyAdded+519
- src/features.pyAdded+634
- src/gbdt.pyAdded+776
- src/retrieval.pyAdded+420
- tools/full_score.pyAdded+159
- winners.pyAdded+277
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines333435363732 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textmodels/zero_shot_lgbm.txt filter=lfs diff=lfs merge=lfs -textresults/f1_vs_n_full_city.png filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296---tags:- tabular-classification- lightgbm- remote-sensing- landsat- domain-adaptation- few-shotlibrary_name: lightgbm---
# Building age from Landsat: Madrid → Amsterdam (Hack4Dev 2026)
This repo holds the two winning models from our Iraq Hackathon 2026 / Hack4Deventry "Building Age Classification from Satellite Imagery", together withthe code, data and notebooks needed to reproduce them or compare against them.
**The task.** Predict a building-age class (1–4) for each 30 m Landsat pixel.Train on Madrid and transfer to Amsterdam. Scoring is macro F1 on Amsterdamafter you are given **n = 5, 25, 50, 100 or 200 labelled Amsterdam pixels perclass** (the few-shot protocol).
| class | Amsterdam | Madrid ||---|---|---|| 1 | before 1945 | before 1960 || 2 | 1945–1984 | 1960–1984 || 3 | 1984–2004 | 1984–2004 || 4 | 2004–2024 | 2004–2024 |
## The two winners
| | **Zero-shot LightGBM** | **Retrained LightGBM** ||---|---|---|| What it is | LightGBM trained on Madrid only. It never sees an Amsterdam label. | A fresh LightGBM trained on all of Madrid plus the n labelled Amsterdam pixels per class, with those pixels weighted 30×. || When to use it | You may not use any Amsterdam labels | You are given a few labelled target pixels, which is the official protocol || Amsterdam macro F1 | **0.590–0.593** at every n (it ignores the labels; it drifts only because each draw's labelled pixels leave the scored set) | **0.656** average over n, **0.720** at n=200 || Saved model | `models/zero_shot_lgbm.txt` | Refit for every draw, so there is no single model. `models/retrained_n{25,200}_rep0_lgbm.txt` are two example draws. || Training cost | A few minutes on a 12-thread CPU | ~1–4 min per draw (84 s mean on a 12-thread CPU) |
Both models use the same 393 features and the same decision rule. All numbersare on **all of Amsterdam** (25,992 pixels), minus the labelled pixels of eachdraw.
### Results on all of Amsterdam
| model | n=5 | n=25 | n=50 | n=100 | n=200 | average | peak ||---|---|---|---|---|---|---|---|| **Retrained LightGBM** (5 draws per n) | 0.5658 ± 0.0108 | 0.6284 ± 0.0120 | 0.6697 ± 0.0087 | 0.6973 ± 0.0038 | **0.7204 ± 0.0060** | **0.6563** | **0.7204** || Prototype, within-class Mahalanobis (12 draws) | 0.5040 ± 0.0402 | **0.6361 ± 0.0170** | 0.6733 ± 0.0135 | 0.7023 ± 0.0067 | 0.7141 ± 0.0031 | 0.6460 | 0.7141 || **Zero-shot LightGBM** (20 draws) | **0.5928** | 0.5925 | 0.5922 | 0.5918 | 0.5903 | 0.5919 | 0.5928 || Organisers' prototype method, re-run by us on our 393 features (20 draws) | 0.5066 | 0.5821 | 0.5965 | 0.6034 | 0.5972 | 0.5772 | 0.6034 || *Organisers' prototype, as reported in their `4-Modelling.ipynb` (their 60 features, their draws)* | *0.5437* | *0.5986* | *0.6079* | *0.6129* | *0.6150* | *0.5956* | *0.6150* || *Organisers' reported zero-shot Random Forest (60 features)* | *0.3427* | | | | | | |
Mean ± std over draws. Each draw is a fresh random sample of labelled pixels,so the ± is the spread you get from which pixels you happen to be handed.
The two italic rows are the organisers' own figures, copied from theirnotebook. Their draws and evaluation set are not ours, so compare themloosely. Their prototype scores higher on their 60 features than on our 393.Both of our winners still beat it at every n.
**Best by prize category:**- **Average:** retrained LightGBM, 0.6563.- **Peak:** retrained LightGBM at n=200, 0.7204.- **n=25:** the prototype, 0.6361. It is implemented in `src/gbdt.py` (`mc_prototype(metric="within")`) but not packaged as a model here.- **n=5:** zero-shot LightGBM, 0.5928.

### The fine-tuned LLM we also tried, for comparison
We also fine-tuned Qwen3-4B-Base with LoRA on text prompts that describe eachMadrid pixel. It took about 2 h on an A100: 1,513 steps at ~0.2 it/s.- **Held-out Madrid areas:** it went from 0.305 untrained to 0.537 macro F1. These come from the fine-tuning notebook's validation output, which is not in this repo.- **Amsterdam:** 0.554 with no labels, on a 6,000-pixel random subset. 0.622 at best (n=200), on a fixed 2,000-pixel subset with 6 draws. These are not full-city numbers like the table above.
It does not beat the zero-shot LightGBM below n=200, so it is not one of thewinners. Details are in `results/llm_protocol_results_colab.md`.
## Quick start
```bashpip install numpy pandas pyarrow scikit-learn lightgbm matplotlibpython winners.py zero-shot # ~15-40 spython winners.py retrained --n 25 --rep 0 # ~2-4 min```
Expected output, from the verification run on our machine:
```zero-shot, all 25,992 Amsterdam pixels: macro F1 0.5928retrained, n=25 rep=0: macro F1 0.6303```
To re-run the whole protocol: `python winners.py protocol --model retrained--reps 5` (25 refits: ~35 min on our machine, up to ~1.5 h on a slowerone). Or open **`notebooks/winners_demo.ipynb`**, which isalready executed, for a walk-through of both models with outputs and thechart.
LightGBM is multi-threaded, so on a different machine the numbers can differin the 4th decimal.
## What we did, exactly
### 1. Features (`notebooks/01_build_features.ipynb`, `src/features.py`)
We started from the organisers' raw per-pixel Landsat time series and builtone row per pixel with 393 usable features:
| group | count | what ||---|---|---|| official | 59 | The organisers' 60 features, reproduced exactly. One has zero variance in a city and was dropped. || reflectance | 276 | Surface reflectance per band; correct spectral indices; tasseled cap; chromaticity; per-decade and early/late-period means || events | 15 | Construction-event detection: when and how sharply the pixel's spectrum stepped || neighbourhood | 15 | The same signals averaged over surrounding pixels || other | 28 | Disturbance spikes and post-construction trends (12), Landsat sensor shares (9), observation coverage (4), position in the city: radial distance and distance to water (3) |
Two features with zero variance in one city were dropped, leaving 393 of 395.The pixel coordinates and the label are never features. The resulting tablesare in `data/processed/` (Madrid 76,263 pixels, Amsterdam 25,992). Notebook 1needs the raw hackathon data, which is not in this repo; the processed tablesare.
### 2. Model selection, on Madrid only (`notebooks/03_gbdt_models.ipynb`)
The rule we followed was that **Amsterdam labels are used only to draw thepermitted n-per-class sample and to score**. Every design choice was made onMadrid.
**Spatial cross-validation.** Madrid was split into 25 geographic blocks, with5-fold cross-validation over whole blocks. Random-pixel folds leak, becauseneighbouring pixels share a construction era. That is why the published 0.618Madrid baseline looks better than it transfers.
| model | 59 official | 393 all features ||---|---|---|| LightGBM, class-balanced | 0.556 | **0.570** || LightGBM, unweighted | 0.550 | 0.569 || LightGBM, ordinal | 0.546 | 0.562 || CatBoost, class-balanced | 0.545 | 0.562 * |
This comparison used cheap settings (400 rounds, learning rate 0.06) androbust-z scaling per block. We were reading the ranking here, not the finalscores. The normalisation test below then dropped the scaling.\* From an earlier run of the same notebook(`results/logs/03_gbdt_models_fullscore_run.log`).
**Per-city normalisation, decided on Madrid.** Each held-out block was scaledwith its own statistics, the same way a new city would be.- No normalisation: **0.599**.- Robust z (median/IQR): 0.569.
So the zero-shot model uses raw features. This went against our startingintuition, and Amsterdam agreed: robust z scored 0.527 there against 0.593with no normalisation.
**Decision rule.** Plain argmax maximises accuracy, not macro F1. A simulatedshift harness makes held-out Madrid blocks look like a new city, by resamplingthe class mix and mapping the features onto Amsterdam's unlabelleddistribution. In it, the most robust rule was:
1. Divide the probabilities by the Madrid class prior raised to 0.5 (tau-logit adjustment).2. Apply the macro-F1 plug-in rule (Ramaswamy et al.).
It never lost to argmax in any simulated regime: +0.012 on average. EM-basedprior estimation was the worst option tested (−0.099) and is not used.
### 3. The two winners
**Zero-shot LightGBM** (`winners.train_zero_shot`)- 1,200 rounds, learning rate 0.03, 31 leaves, `min_child_samples` 80, subsample 0.8, `colsample_bytree` 0.6, L1 0.5, L2 5.0, seed 42.- Class-balanced weights, raw features.- Prediction is the decision rule above, applied to all of Amsterdam's probabilities at once. The rule uses the batch's predicted class shares, never its labels.
**Retrained LightGBM** (`winners.train_retrained`). This follows theorganisers' `modelCreate` spec. The deck`Building-Age-from-Space-A-Transferable-Classifier.pptx` is in their`hackathon.zip` download, and its slide 4 says:
> "We are NOT building a classifier. We are building a METHOD that creates> classifiers."
Slide 5 says that `modelCreate` takes N labelled pixels per class from the newcity and outputs "a fully functional classifier for that city". There is oneliberty beyond the tightest reading of slides 5 and 7, which give`modelCreate` only the labelled sample: step 1 below also reads Amsterdam's**unlabelled** feature table to compute scaling statistics (see Caveats). Foreach draw of n labelled Amsterdam pixels per class:1. Robust-z scale Madrid with Madrid's median/IQR. Scale Amsterdam with Amsterdam's median/IQR, computed from its whole unlabelled feature table.2. Stack the 76,263 Madrid rows and the 4n Amsterdam rows. The Amsterdam rows get weight 30, then everything is multiplied by class-balanced weights.3. Fit LightGBM with the same parameters as the zero-shot model, but 400 rounds at learning rate 0.06. This is the cheaper setting the protocol was run with, because it refits on every draw.4. Predict every other Amsterdam pixel and apply the same decision rule.
### 4. The protocol, i.e. how every number was measured
- **Labelled sample:** for each n and each repeat r, n pixels per class are drawn with `numpy.random.default_rng(42 + 1000·n + r)`. Use `winners.shots_for(y_ams, n, r)` to get the identical pixels.- **Scoring:** those pixels are removed and macro F1 is computed on every remaining Amsterdam pixel.- **Repeats:** 5 for the retrained model, since each draw is a full refit. 12 for the prototype, 20 for the zero-shot and the organisers' baseline.- **Exploration subsample:** notebook 3 explored 14 variants on a fixed 8,000-pixel subsample.- **Full-city re-scoring:** `tools/full_score.py` re-scored the retrained LightGBM and the within-class prototype on all of Amsterdam. In the same run it re-scored the 8,000-pixel subsample, and that reproduced notebook 3's table to the 4th decimal, so the full-city numbers come from identical models. The full city reads 0.002–0.006 higher per n, and 0.003–0.004 on the average.- **The other full-city rows:** the zero-shot and organisers' baseline rows come from an earlier full-city run of notebook 3 (`results/logs/03_gbdt_models_fullscore_run.log`, 20 draws).
### 5. The other 12 Amsterdam variants (8,000-pixel subsample, average over n)
| variant | average ||---|---|| refit leaf values, tree structure frozen † | 0.612 || prototype, total-covariance Mahalanobis | 0.612 || prototype, rank + Euclidean | 0.591 || pure k-NN on the labelled pixels only | 0.589 || zero-shot, no normalisation (the zero-shot winner, before full-city scoring) | 0.586 || organisers' Euclidean prototype (re-run on our 393 features) | 0.575 || zero-shot, per-city rank / robust z / robust z + CORAL | 0.553 / 0.524 / 0.537 || recalibrated LightGBM / CatBoost | 0.544 / 0.550 || prototype, robust z + Euclidean | 0.401 |
† Measured with a normalisation bug: it applied robust z when its label saysnone.
The models that actually learn from the labelled Amsterdam pixels win. Theones that only rescale or recalibrate Madrid's output score below theorganisers' baseline (0.524–0.553 against 0.575). The exception is the plainzero-shot model with no scaling at all.
## Caveats
- **Transductive scaling.** The retrained model scales Amsterdam with the median/IQR of Amsterdam's whole unlabelled feature table. That uses features only, never labels, and the protocol passes the table in. The organisers' baseline does **not** do this: it scales Amsterdam with Madrid's scaler. On a strict reading, where `modelCreate` gets only the labelled sample, you would compute those statistics from the shots alone. On a new test set, compute them on that set's features. The zero-shot model is unaffected, because it uses no scaling.- **Batch-level decision rule.** The rule looks at the predicted class shares of the batch it labels. With plain argmax the zero-shot model scores 0.5680 on all of Amsterdam instead of 0.5928.- **Few repeats.** The retrained model's ± comes from 5 draws per n.- **Hidden test sets.** The organisers score on held-out Amsterdam and Madrid sets we never saw. Expect those numbers to be lower.
## Repo layout
```winners.py self-contained: both models, the decision rule, the protocolmodels/ zero_shot_lgbm.txt the zero-shot model (LightGBM text format) retrained_n25_rep0_lgbm.txt example retrained models, draw rep 0 retrained_n200_rep0_lgbm.txt amsterdam_robustz_stats.npz Amsterdam median/IQR the retrained models expect retrained_example_shot_indices.json which Amsterdam rows they were trained on meta.json feature order, Madrid prior, verification resultsdata/processed/ madrid_features.parquet, amsterdam_features.parquetnotebooks/ winners_demo.ipynb executed walk-through of both winners (start here) 03_gbdt_models.ipynb full model study: CV, normalisation, decision rule, all 14 variants 01_build_features.ipynb raw data -> features (needs the hackathon raw data) src/ the same notebooks as plain .pysrc/ project code the notebooks import (gbdt.py, evaluation.py, ...)tools/full_score.py full-city re-scoring of the two winnersresults/ per-draw JSON, logs of every run, the LLM results```
`models/meta.json` → `verification` records the checks run when these fileswere exported:- the ported code in `winners.py` gives the same probabilities as the project code (max abs diff 0);- the saved models reload identically;- the two example draws reproduce the reported per-draw scores exactly.123version https://git-lfs.github.com/spec/v1oid sha256:3d5a8953b2560b30fe2453363b07408cd870f293d0bb2d0c93e24803f32e0262size 56157092123version https://git-lfs.github.com/spec/v1oid sha256:0dd77b81c5314bb4380160442edeced09b7e9c3eec94dfd13d720366eba43161size 165478500123version https://git-lfs.github.com/spec/v1oid sha256:035cfe85473152b23f9bb5076adb78a2f8106b547bb18f8226d84612d990f931size 6792123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430{
"feature_names": [
"Blue_mean",
"Green_mean",
"Red_mean",
"NIR_mean",
"SWIR1_mean",
"SWIR2_mean",
"Blue_std",
"Green_std",
"Red_std",
"NIR_std",
"SWIR1_std",
"SWIR2_std",
"NDVI_mean",
"NDBI_mean",
"UI_mean",
"MNDWI_mean",
"BSI_mean",
"NDVI_std",
"NDBI_std",
"UI_std",
"MNDWI_std",
"BSI_std",
"Blue_early_mean",
"Green_early_mean",
"Red_early_mean",
"NIR_early_mean",
"SWIR1_early_mean",
"SWIR2_early_mean",
"Blue_early_std",
"Green_early_std",
"Red_early_std",
"NIR_early_std",
"SWIR1_early_std",
"SWIR2_early_std",
"Blue_late_mean",
"Green_late_mean",
"Red_late_mean",
"NIR_late_mean",
"SWIR1_late_mean",
"SWIR2_late_mean",
"Blue_late_std",
"Green_late_std",
"Red_late_std",
"NIR_late_std",
"SWIR1_late_std",
"SWIR2_late_std",
"d_Blue_mean",
"d_Green_mean",
"d_Red_mean",
"d_NIR_mean",
"d_SWIR1_mean",
"d_SWIR2_mean",
"d_Blue_std",
"d_Green_std",
"d_Red_std",
"d_NIR_std",
"d_SWIR1_std",
"d_SWIR2_std",
"has_late_data",
"sr_brightness_mean",
"sr_brightness_std",
"sr_brightness_early_mean",
"sr_brightness_late_mean",
"sr_brightness_late_minus_early",
"sr_brightness_cv",
"sr_brightness_early_std",
"sr_brightness_late_std",
"sr_brightness_slope_decade",
"sr_brightness_min",
"sr_brightness_max",
"sr_brightness_tm_mean",
"sr_brightness_oli_mean",
"sr_brightness_oli_minus_tm",
"sr_brightness_dec84_93_mean",
"sr_brightness_dec94_03_mean",
"sr_brightness_dec04_13_mean",
"sr_brightness_dec14_24_mean",
"sr_Blue_mean",
"sr_Blue_std",
"sr_Blue_early_mean",
"sr_Blue_late_mean",
"sr_Blue_late_minus_early",
"sr_Blue_cv",
"sr_Blue_early_std",
"sr_Blue_late_std",
"sr_Blue_slope_decade",
"sr_Blue_min",
"sr_Blue_max",
"sr_Blue_tm_mean",
"sr_Blue_oli_mean",
"sr_Blue_oli_minus_tm",
"sr_Blue_dec84_93_mean",
"sr_Blue_dec94_03_mean",
"sr_Blue_dec04_13_mean",
"sr_Blue_dec14_24_mean",
"sr_Green_mean",
"sr_Green_std",
"sr_Green_early_mean",
"sr_Green_late_mean",
"sr_Green_late_minus_early",
"sr_Green_cv",
"sr_Green_early_std",
"sr_Green_late_std",
"sr_Green_slope_decade",
"sr_Green_min",
"sr_Green_max",
"sr_Green_tm_mean",
"sr_Green_oli_mean",
"sr_Green_oli_minus_tm",
"sr_Green_dec84_93_mean",
"sr_Green_dec94_03_mean",
"sr_Green_dec04_13_mean",
"sr_Green_dec14_24_mean",
"sr_Red_mean",
"sr_Red_std",
"sr_Red_early_mean",
"sr_Red_late_mean",
"sr_Red_late_minus_early",
"sr_Red_cv",
"sr_Red_early_std",
"sr_Red_late_std",
"sr_Red_slope_decade",
"sr_Red_min",
"sr_Red_max",
"sr_Red_tm_mean",
"sr_Red_oli_mean",
"sr_Red_oli_minus_tm",
"sr_Red_dec84_93_mean",
"sr_Red_dec94_03_mean",
"sr_Red_dec04_13_mean",
"sr_Red_dec14_24_mean",
"sr_NIR_mean",
"sr_NIR_std",
"sr_NIR_early_mean",
"sr_NIR_late_mean",
"sr_NIR_late_minus_early",
"sr_NIR_cv",
"sr_NIR_early_std",
"sr_NIR_late_std",
"sr_NIR_slope_decade",
"sr_NIR_min",
"sr_NIR_max",
"sr_NIR_tm_mean",
"sr_NIR_oli_mean",
"sr_NIR_oli_minus_tm",
"sr_NIR_dec84_93_mean",
"sr_NIR_dec94_03_mean",
"sr_NIR_dec04_13_mean",
"sr_NIR_dec14_24_mean",
"sr_SWIR1_mean",
"sr_SWIR1_std",
"sr_SWIR1_early_mean",
"sr_SWIR1_late_mean",
"sr_SWIR1_late_minus_early",
"sr_SWIR1_cv",
"sr_SWIR1_early_std",
"sr_SWIR1_late_std",
"sr_SWIR1_slope_decade",
"sr_SWIR1_min",
"sr_SWIR1_max",
"sr_SWIR1_tm_mean",
"sr_SWIR1_oli_mean",
"sr_SWIR1_oli_minus_tm",
"sr_SWIR1_dec84_93_mean",
"sr_SWIR1_dec94_03_mean",
"sr_SWIR1_dec04_13_mean",
"sr_SWIR1_dec14_24_mean",
"sr_SWIR2_mean",
"sr_SWIR2_std",
"sr_SWIR2_early_mean",
"sr_SWIR2_late_mean",
"sr_SWIR2_late_minus_early",
"sr_SWIR2_cv",
"sr_SWIR2_early_std",
"sr_SWIR2_late_std",
"sr_SWIR2_slope_decade",
"sr_SWIR2_min",
"sr_SWIR2_max",
"sr_SWIR2_tm_mean",
"sr_SWIR2_oli_mean",
"sr_SWIR2_oli_minus_tm",
"sr_SWIR2_dec84_93_mean",
"sr_SWIR2_dec94_03_mean",
"sr_SWIR2_dec04_13_mean",
"sr_SWIR2_dec14_24_mean",
"sr_NDVI_mean",
"sr_NDVI_std",
"sr_NDVI_early_mean",
"sr_NDVI_late_mean",
"sr_NDVI_late_minus_early",
"sr_NDVI_cv",
"sr_NDVI_early_std",
"sr_NDVI_late_std",
"sr_NDVI_slope_decade",
"sr_NDVI_min",
"sr_NDVI_max",
"sr_NDVI_tm_mean",
"sr_NDVI_oli_mean",
"sr_NDVI_oli_minus_tm",
"sr_NDVI_dec84_93_mean",
"sr_NDVI_dec94_03_mean",
"sr_NDVI_dec04_13_mean",
"sr_NDVI_dec14_24_mean",
"sr_NDBI_mean",
"sr_NDBI_std",
"sr_NDBI_early_mean",
"sr_NDBI_late_mean",
"sr_NDBI_late_minus_early",
"sr_NDBI_cv",
"sr_NDBI_early_std",
"sr_NDBI_late_std",
"sr_NDBI_slope_decade",
"sr_NDBI_min",
"sr_NDBI_max",
"sr_NDBI_tm_mean",
"sr_NDBI_oli_mean",
"sr_NDBI_oli_minus_tm",
"sr_NDBI_dec84_93_mean",
"sr_NDBI_dec94_03_mean",
"sr_NDBI_dec04_13_mean",
"sr_NDBI_dec14_24_mean",
"sr_UI_mean",
"sr_UI_std",
"sr_UI_early_mean",
"sr_UI_late_mean",
"sr_UI_late_minus_early",
"sr_UI_cv",
"sr_UI_early_std",
"sr_UI_late_std",
"sr_UI_slope_decade",
"sr_UI_min",
"sr_UI_max",
"sr_UI_tm_mean",
"sr_UI_oli_mean",
"sr_UI_oli_minus_tm",
"sr_UI_dec84_93_mean",
"sr_UI_dec94_03_mean",
"sr_UI_dec04_13_mean",
"sr_UI_dec14_24_mean",
"sr_MNDWI_mean",
"sr_MNDWI_std",
"sr_MNDWI_early_mean",
"sr_MNDWI_late_mean",
"sr_MNDWI_late_minus_early",
"sr_MNDWI_cv",
"sr_MNDWI_early_std",
"sr_MNDWI_late_std",
"sr_MNDWI_slope_decade",
"sr_MNDWI_min",
"sr_MNDWI_max",
"sr_MNDWI_tm_mean",
"sr_MNDWI_oli_mean",
"sr_MNDWI_oli_minus_tm",
"sr_MNDWI_dec84_93_mean",
"sr_MNDWI_dec94_03_mean",
"sr_MNDWI_dec04_13_mean",
"sr_MNDWI_dec14_24_mean",
"sr_BSI_mean",
"sr_BSI_std",
"sr_BSI_early_mean",
"sr_BSI_late_mean",
"sr_BSI_late_minus_early",
"sr_BSI_cv",
"sr_BSI_early_std",
"sr_BSI_late_std",
"sr_BSI_slope_decade",
"sr_BSI_min",
"sr_BSI_max",
"sr_BSI_tm_mean",
"sr_BSI_oli_mean",
"sr_BSI_oli_minus_tm",
"sr_BSI_dec84_93_mean",
"sr_BSI_dec94_03_mean",
"sr_BSI_dec04_13_mean",
"sr_BSI_dec14_24_mean",
"sr_NBR_mean",
"sr_NBR_std",
"sr_NBR_early_mean",
"sr_NBR_late_mean",
"sr_NBR_late_minus_early",
"sr_NBR_cv",
"sr_TCB_mean",
"sr_TCB_std",
"sr_TCB_early_mean",
"sr_TCB_late_mean",
"sr_TCB_late_minus_early",
"sr_TCB_cv",
"sr_TCG_mean",
"sr_TCG_std",
"sr_TCG_early_mean",
"sr_TCG_late_mean",
"sr_TCG_late_minus_early",
"sr_TCG_cv",
"sr_TCW_mean",
"sr_TCW_std",
"sr_TCW_early_mean",
"sr_TCW_late_mean",
"sr_TCW_late_minus_early",
"sr_TCW_cv",
"sr_chromBlue_mean",
"sr_chromBlue_std",
"sr_chromBlue_early_mean",
"sr_chromBlue_late_mean",
"sr_chromBlue_late_minus_early",
"sr_chromBlue_cv",
"sr_chromGreen_mean",
"sr_chromGreen_std",
"sr_chromGreen_early_mean",
"sr_chromGreen_late_mean",
"sr_chromGreen_late_minus_early",
"sr_chromGreen_cv",
"sr_chromRed_mean",
"sr_chromRed_std",
"sr_chromRed_early_mean",
"sr_chromRed_late_mean",
"sr_chromRed_late_minus_early",
"sr_chromRed_cv",
"sr_chromNIR_mean",
"sr_chromNIR_std",
"sr_chromNIR_early_mean",
"sr_chromNIR_late_mean",
"sr_chromNIR_late_minus_early",
"sr_chromNIR_cv",
"sr_chromSWIR1_mean",
"sr_chromSWIR1_std",
"sr_chromSWIR1_early_mean",
"sr_chromSWIR1_late_mean",
"sr_chromSWIR1_late_minus_early",
"sr_chromSWIR1_cv",
"sr_chromSWIR2_mean",
"sr_chromSWIR2_std",
"sr_chromSWIR2_early_mean",
"sr_chromSWIR2_late_mean",
"sr_chromSWIR2_late_minus_early",
"sr_chromSWIR2_cv",
"step_brightness_year",
"step_brightness_mag",
"step_brightness_njumps",
"step_brightness_t",
"step_brightness_snr",
"step_SWIR1_year",
"step_SWIR1_mag",
"step_SWIR1_njumps",
"step_SWIR1_t",
"step_SWIR1_snr",
"step_NDVI_year",
"step_NDVI_mag",
"step_NDVI_njumps",
"step_NDVI_t",
"step_NDVI_snr",
"spike_BSI_year",
"spike_BSI_z",
"spike_BSI_returns",
"spike_SWIR1_year",
"spike_SWIR1_z",
"spike_SWIR1_returns",
"spike_brightness_year",
"spike_brightness_z",
"spike_brightness_returns",
"post_step_NDVI_slope_decade",
"years_since_step",
"pre_state",
"sat_share_tm",
"sat_share_tm_early",
"sat_share_tm_late",
"sat_share_etm",
"sat_share_etm_early",
"sat_share_etm_late",
"sat_share_oli",
"sat_share_oli_late",
"sat_switches",
"n_observed_years",
"first_observed_year",
"last_observed_year",
"coverage",
"radial_px",
"radial_frac",
"dist_to_water_px",
"nbr_sr_brightness_mean",
"nbr_sr_brightness_mean_diff",
"nbr_sr_NDVI_mean",
"nbr_sr_NDVI_mean_diff",
"nbr_sr_SWIR1_mean",
"nbr_sr_SWIR1_mean_diff",
"nbr_sr_brightness_late_minus_early",
"nbr_sr_brightness_late_minus_early_diff",
"nbr_step_brightness_year",
"nbr_step_brightness_year_diff",
"nbr_step_brightness_mag",
"nbr_step_brightness_mag_diff",
"nbr_sr_brightness_std",
"nbr_sr_brightness_std_diff",
"nbr_n_within_radius"
],
"dropped_dead_features": [
"has_early_data",
"sat_share_oli_early"
],
"classes": [
1,
2,
3,
4
],
"seed": 42,
"madrid_prior": [
0.18087408048463868,
0.35603110289393286,
0.244836945832186,
0.2182578707892425
],
"verification": {
"zero_shot_port_max_abs_diff": 0.0,
"zero_shot_reload_max_abs_diff": 0.0,
"decision_rule_port_identical": true,
"zero_shot_all_pixels": 0.592839846672412,
"zero_shot_n5_rep0": 0.592823816444138,
"zero_shot_all_pixels_plain_argmax": 0.5679842811565695,
"retrained_n25_port_max_abs_diff": 0.0,
"retrained_n25_reload_max_abs_diff": 0.0,
"retrained_n25_rep0": 0.6302737351779462,
"retrained_n25_rep0_reported": 0.6302737351779462,
"retrained_n200_port_max_abs_diff": 0.0,
"retrained_n200_reload_max_abs_diff": 0.0,
"retrained_n200_rep0": 0.7264520284114167,
"retrained_n200_rep0_reported": 0.7264520284114167
}
}1{"note": "Row indices into amsterdam_features.parquet of the labelled pixels each example model was trained on (draw rep 0).", "n25_rep0": [18209, 14793, 13081, 16589, 12889, 8381, 24399, 17181, 8471, 8515, 21652, 13638, 10185, 20225, 16664, 9001, 12752, 21310, 15707, 16958, 18041, 10554, 10847, 17240, 10859, 6669, 19686, 5601, 5623, 24595, 6035, 20979, 18754, 10980, 24335, 8212, 19981, 7277, 19086, 8830, 5902, 23524, 22079, 4517, 24030, 2259, 18522, 23554, 20420, 22163, 3346, 2215, 24890, 25644, 12506, 1931, 21353, 19457, 5595, 16020, 2685, 1390, 23123, 20915, 1603, 16994, 25794, 14681, 4879, 22097, 1574, 4700, 19263, 380, 20591, 15820, 25444, 20409, 2552, 19403, 2896, 3170, 6392, 15664, 6626, 22649, 8717, 15469, 25184, 25752, 1609, 203, 11321, 8911, 106, 851, 3206, 2821, 11818, 2823], "n200_rep0": [20654, 20967, 11154, 15646, 15977, 13403, 17039, 16593, 12370, 17313, 17984, 12118, 21891, 13184, 16304, 8086, 8067, 11131, 11704, 9913, 11579, 16044, 10758, 11957, 11988, 11464, 8811, 15911, 3389, 8363, 11027, 13754, 14215, 12225, 15645, 17666, 9020, 13148, 19873, 9224, 8676, 20079, 20758, 13620, 19097, 16442, 13763, 11616, 7858, 12522, 8171, 16562, 8796, 19447, 16275, 9336, 16260, 19687, 17233, 11175, 11444, 13228, 13577, 12539, 16172, 3300, 8823, 20700, 13990, 15500, 10045, 12519, 10335, 15305, 17747, 17282, 20831, 15850, 20167, 10270, 14653, 13760, 25756, 13152, 11256, 13076, 18640, 15876, 9448, 22074, 8113, 10362, 13113, 12192, 22773, 17441, 8740, 8426, 10553, 17135, 11016, 2352, 9426, 9093, 17847, 9596, 16776, 11069, 20815, 14459, 8364, 14606, 21497, 11426, 15315, 8872, 15400, 18130, 14526, 7266, 10382, 9350, 11534, 16035, 12045, 15504, 9543, 9187, 8897, 16242, 8068, 16796, 8070, 16130, 10907, 9819, 16966, 20706, 10621, 12196, 7634, 18552, 14149, 12149, 15863, 12062, 19763, 19126, 7983, 7981, 13770, 8304, 13334, 20785, 19342, 9532, 11784, 13396, 11173, 21238, 10778, 10859, 8423, 15870, 9605, 9871, 13623, 21631, 11537, 13144, 18301, 11989, 8669, 16602, 10189, 19069, 18700, 14953, 8675, 9274, 9973, 3998, 11440, 21736, 20582, 9610, 25596, 17099, 20500, 14723, 17363, 12133, 9225, 16732, 17094, 10606, 12633, 16102, 23531, 16126, 24788, 1207, 2411, 5724, 15590, 15291, 1011, 12725, 5769, 5405, 5192, 4450, 23979, 22540, 6712, 3995, 6061, 18941, 19122, 7081, 20440, 2239, 20097, 6928, 23056, 14025, 18895, 7117, 20115, 24627, 12551, 19265, 1583, 25014, 25893, 1749, 2634, 24388, 8156, 12419, 4877, 13434, 18125, 21958, 14268, 23363, 13544, 19470, 17795, 11412, 7946, 24246, 24809, 25850, 6244, 18527, 14263, 15900, 9397, 17058, 641, 1912, 20017, 10742, 11224, 13890, 13666, 20246, 23776, 24969, 18383, 5358, 15616, 21477, 17722, 20897, 24241, 16318, 5302, 5493, 15601, 7038, 5509, 21162, 2424, 25020, 18307, 19187, 12413, 18016, 1595, 12847, 12346, 11930, 5456, 18717, 6275, 5744, 2747, 18493, 1453, 18136, 2528, 23318, 18005, 24122, 24344, 23171, 18173, 2159, 23934, 2990, 18542, 23788, 20003, 24083, 15318, 20751, 25108, 6101, 10597, 15347, 6136, 18075, 20980, 5310, 7958, 13918, 23700, 11063, 25212, 21247, 5891, 9627, 7265, 23576, 24205, 11272, 16980, 6797, 22920, 6781, 13832, 20890, 10815, 23258, 24375, 13791, 10138, 10439, 13484, 1208, 12324, 11008, 22322, 8469, 22967, 23655, 23618, 3947, 22860, 6617, 21457, 12906, 2886, 2234, 18842, 6373, 5754, 3865, 15427, 19464, 23600, 21779, 20649, 13903, 22966, 12169, 5263, 15665, 1598, 21545, 23996, 9106, 23443, 5127, 4954, 4045, 23981, 3198, 18573, 23720, 6594, 5408, 5586, 24736, 5402, 24064, 20601, 5231, 1961, 22298, 2451, 1115, 22553, 5090, 24684, 25206, 7407, 7037, 3440, 1644, 12508, 833, 25302, 4499, 7834, 20431, 6992, 22832, 9177, 16153, 18968, 21896, 17037, 10339, 17449, 3966, 2008, 7413, 957, 2379, 20993, 376, 6428, 537, 2224, 8858, 3128, 25257, 3286, 5941, 5470, 23307, 4928, 6228, 25279, 14232, 12076, 553, 3770, 2146, 22589, 9315, 6058, 16757, 11387, 4751, 25385, 22437, 14439, 14926, 8229, 13204, 22375, 24149, 5545, 22142, 7104, 444, 25454, 2592, 1180, 23159, 24671, 16847, 1611, 10541, 12082, 3197, 6890, 18805, 3559, 24115, 852, 3716, 17893, 1503, 8349, 3089, 6640, 2230, 22596, 6408, 1842, 21486, 19990, 19159, 23764, 1023, 16626, 3548, 8552, 11376, 16767, 5800, 1835, 23148, 12921, 25008, 20029, 450, 18421, 17057, 354, 4168, 1432, 24898, 13253, 6779, 20028, 3914, 14636, 3289, 21334, 9969, 4371, 8083, 18980, 23420, 22574, 5596, 23965, 6316, 3343, 13530, 1449, 274, 1296, 4179, 5570, 4551, 7962, 25076, 18733, 23563, 15449, 4005, 1374, 19663, 19942, 22548, 6639, 24589, 2012, 23377, 7225, 3963, 7033, 14702, 4661, 419, 12577, 24437, 1120, 1247, 395, 19727, 15127, 13847, 12858, 22361, 22690, 1058, 15234, 1744, 12965, 19730, 15139, 960, 490, 3809, 2742, 1361, 2269, 24556, 20973, 2192, 24402, 954, 3898, 24590, 3451, 18692, 22414, 4395, 19605, 1091, 20620, 20012, 1567, 629, 22536, 11902, 3313, 9923, 660, 898, 14584, 11584, 2983, 21780, 10727, 25618, 24391, 23543, 25616, 11400, 11662, 156, 10219, 19787, 12487, 17250, 19753, 1697, 25687, 7156, 43, 10721, 15649, 22923, 651, 24544, 6500, 25253, 15584, 3169, 25532, 15605, 65, 17682, 25382, 630, 24382, 6798, 23007, 4145, 1548, 2831, 22231, 9801, 4584, 14985, 23076, 24485, 10649, 23674, 195, 25309, 2466, 2407, 22121, 801, 24742, 19594, 25503, 3252, 24907, 24364, 2898, 20349, 23714, 23270, 208, 935, 25667, 15946, 22, 25119, 17423, 7186, 3532, 22649, 6576, 17112, 11656, 25524, 23198, 160, 2252, 3231, 22389, 10, 24361, 209, 15652, 15738, 1504, 22529, 920, 24506, 24717, 22388, 6876, 15736, 1366, 116, 25505, 18364, 589, 2895, 18392, 18529, 187, 2335, 17863, 23187, 25449, 10895, 47, 2333, 16473, 2584, 6542, 1256, 23312, 6598, 2900, 1383, 19883, 1650, 11495, 6184, 22946, 3971, 25273, 23176, 16313, 950, 2667, 23993, 25635, 2, 19934, 25556, 11128, 148, 17457, 13345, 7441, 1892, 22199, 25979, 25627, 10000, 17555, 12246, 23036, 25397, 22470, 6586, 7233, 3016, 15467, 1204, 94, 7323, 25713, 3303, 3321, 15819, 6610, 3105, 2304, 19845, 2934, 130, 140, 6455, 169, 25363, 2127, 8712, 24833, 18926, 22959, 1307, 21381, 2695, 1151, 18766, 63, 25159, 2313, 25247, 9626, 16979, 2699, 9641]}123version https://git-lfs.github.com/spec/v1oid sha256:02f51d07177c68c0c8fbb6b5753195737b664498d2b875138188749d634374c6size 17080833123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 1 - Features: from 40 years of Landsat to one row per building pixel\n",
"\n",
"This notebook turns the two raw parquet files into two feature tables.\n",
"\n",
"It does **two** things at once:\n",
"\n",
"1. **Reproduces the organisers' 60 features exactly** (Notebook 3), so every\n",
" number we report stays comparable with the published Random-Forest\n",
" baseline of 0.618 +- 0.004 macro F1 on Madrid.\n",
"2. **Adds an extended set** on top: proper surface reflectance instead of raw\n",
" digital numbers, correct spectral indices, construction-event detection,\n",
" per-decade means, trends, and label-free neighbourhood context.\n",
"\n",
"Nothing here touches `y_amsterdam`. Amsterdam's *features* are used (for\n",
"per-city statistics), its *labels* are not.\n",
"\n",
"Runs on CPU in a few minutes - no GPU needed. Do this once, locally, and the\n",
"GPU notebooks just load the parquet files it writes."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"import sys\n",
"from pathlib import Path\n",
"\n",
"# Make src/ importable whether we are local, on Kaggle, or on Colab.\n",
"for cand in [Path.cwd() / \"src\", Path.cwd().parent / \"src\",\n",
" Path(\"/kaggle/working/src\"), Path(\"/content/hack4dev/src\")]:\n",
" if cand.exists():\n",
" sys.path.insert(0, str(cand))\n",
" break\n",
"\n",
"import numpy as np\n",
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"\n",
"import config as C\n",
"import features as F\n",
"import retrieval as R\n",
"\n",
"pd.set_option(\"display.width\", 200)\n",
"pd.set_option(\"display.max_columns\", 60)\n",
"print(\"platform:\", C.PLATFORM)\n",
"print(\"looking for raw parquet under:\", C.RAW_DIR)"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1.1 Find the raw files\n",
"\n",
"Expected: `madrid_train.parquet` (about 3.17 M rows) and\n",
"`amsterdam_data.parquet` (about 1.06 M rows). On Kaggle they will be inside\n",
"`/kaggle/input/<dataset-name>/`; the search below handles that."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"def find_parquet(pattern: str) -> Path:\n",
" roots = [C.RAW_DIR, C.DATA_DIR, C.PROJECT_ROOT, Path(\"/kaggle/input\")]\n",
" for root in roots:\n",
" if not root.exists():\n",
" continue\n",
" hits = sorted(root.rglob(pattern))\n",
" if hits:\n",
" return hits[0]\n",
" raise FileNotFoundError(\n",
" f\"{pattern} not found. Put the two parquet files in {C.RAW_DIR} \"\n",
" \"(local) or attach them as a Kaggle dataset.\")\n",
"\n",
"MADRID_PARQUET = find_parquet(\"madrid_train.parquet\")\n",
"AMS_PARQUET = find_parquet(\"amsterdam_data.parquet\")\n",
"print(\"Madrid :\", MADRID_PARQUET)\n",
"print(\"Amsterdam:\", AMS_PARQUET)"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1.2 What is actually in the raw file\n",
"\n",
"One row per *(pixel, year)*. Up to three summer observations per year are\n",
"stored side by side as `Blue_1/Blue_2/Blue_3`, each with a `qa_valid_N`\n",
"cloud flag. Band values are raw Landsat Collection-2 integers:\n",
"\n",
"$$\\text{surface reflectance} = \\text{DN} \\times 2.75\\times10^{-5} - 0.2$$"
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"peek = pd.read_parquet(MADRID_PARQUET)\n",
"print(f\"{len(peek):,} rows x {peek.shape[1]} columns\")\n",
"print(\"\\ncolumns:\")\n",
"print(list(peek.columns))\n",
"print(\"\\nyears:\", peek[\"year\"].min(), \"-\", peek[\"year\"].max(),\n",
" f\"({peek['year'].nunique()} distinct)\")\n",
"print(\"unique pixels:\", f\"{peek.groupby(C.PID).ngroups:,}\")\n",
"print(\"\\nfirst row:\")\n",
"print(peek.iloc[0].to_string())"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": [
"# Reflectance sanity check on one band, and the QA-flag hit rate.\n",
"dn = peek[\"Red_1\"].dropna()\n",
"sr = dn * C.SR_SCALE + C.SR_OFFSET\n",
"print(\"Red_1 digital numbers :\", dn.quantile([0, .01, .5, .99, 1]).round(0).to_dict())\n",
"print(\"Red_1 as reflectance :\", sr.quantile([0, .01, .5, .99, 1]).round(3).to_dict())\n",
"for s in (1, 2, 3):\n",
" col = f\"qa_valid_{s}\"\n",
" if col in peek.columns:\n",
" print(f\"{col}: {peek[col].mean():.1%} valid\")\n",
"del peek"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1.3 Build both feature sets\n",
"\n",
"The heavy lifting lives in `src/features.py`. Per city it:\n",
"\n",
"* picks the first QA-valid observation per band per year, drops haze\n",
" (`Blue > 15000`);\n",
"* records `has_early_data` / `has_late_data` on the *observed* years;\n",
"* fills the annual series (linear inside, nearest at the edges);\n",
"* pivots to one `(pixels x years)` matrix per band, then computes every\n",
" statistic with numpy - a whole city in about a minute."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"madrid = F.build_city(MADRID_PARQUET, city_hint=\"Madrid\")"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": [
"amsterdam = F.build_city(AMS_PARQUET, city_hint=\"Amsterdam\")"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1.4 Does this match the organisers' own output?\n",
"\n",
"If `preprocessed_data.pkl` from the organisers' Notebook 3 is around, compare\n",
"the 60 official features against it. Their arrays are standardised with\n",
"Madrid's `StandardScaler`, so we compare **correlation per feature**, which is\n",
"invariant to that. Anything below 0.999 means our pipeline has drifted."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"pkl = None\n",
"for root in [C.DATA_DIR, C.PROJECT_ROOT, Path(\"/kaggle/input\")]:\n",
" if root.exists():\n",
" hits = sorted(root.rglob(\"preprocessed_data.pkl\"))\n",
" if hits:\n",
" pkl = hits[0]\n",
" break\n",
"\n",
"if pkl is None:\n",
" print(\"preprocessed_data.pkl not found - skipping the cross-check.\")\n",
"else:\n",
" import pickle\n",
" with open(pkl, \"rb\") as fh:\n",
" ref = pickle.load(fh)\n",
" print(\"reference file:\", pkl)\n",
" ours = madrid.set_index([\"px_key\", \"py_key\"])\n",
" ref_ids = pd.MultiIndex.from_arrays(\n",
" [ref[\"pixel_ids_madrid\"][:, 0], ref[\"pixel_ids_madrid\"][:, 1]],\n",
" names=[\"px_key\", \"py_key\"])\n",
" common = ref_ids.intersection(ours.index)\n",
" print(f\"pixels: ours {len(ours):,}, theirs {len(ref_ids):,}, \"\n",
" f\"in common {len(common):,}\")\n",
" ref_df = pd.DataFrame(ref[\"X_madrid\"], index=ref_ids,\n",
" columns=ref[\"feature_names\"]).loc[common]\n",
" our_df = ours.loc[common, ref[\"feature_names\"]]\n",
" corr = {c: float(np.corrcoef(ref_df[c], our_df[c])[0, 1])\n",
" for c in ref[\"feature_names\"]\n",
" if ref_df[c].std() > 0 and our_df[c].std() > 0}\n",
" bad = {k: v for k, v in corr.items() if v < 0.999}\n",
" print(f\"features compared: {len(corr)} | min correlation: \"\n",
" f\"{min(corr.values()):.5f}\")\n",
" print(\"dead features in their file (zero variance):\",\n",
" [c for c in ref[\"feature_names\"] if ref_df[c].std() == 0])\n",
" print(\"features below 0.999:\", bad if bad else \"none - pipeline matches\")\n",
" # Labels must agree exactly.\n",
" y_ref = pd.Series(ref[\"y_madrid\"], index=ref_ids).loc[common]\n",
" print(\"label agreement:\",\n",
" f\"{(y_ref.to_numpy() == our_df.index.map(ours['age_class']).to_numpy()).mean():.4%}\")"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1.5 Class balance, and the domain gap\n",
"\n",
"Two facts drive every later design decision:\n",
"\n",
"* the classes are unbalanced, differently in each city;\n",
"* the same feature has a different *level* in each city, by much more than\n",
" the gap between classes - which is why a Madrid model collapses to ~0.34 on\n",
" Amsterdam."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"for name, df in [(\"Madrid\", madrid), (\"Amsterdam\", amsterdam)]:\n",
" n = len(df)\n",
" counts = df[\"age_class\"].value_counts().sort_index()\n",
" print(f\"\\n{name}: {n:,} labelled pixels\")\n",
" for c in C.CLASS_LABELS[name]:\n",
" k = int(counts.get(c, 0))\n",
" print(f\" class {c} ({C.CLASS_LABELS[name][c]:>11}): {k:6,} {k / n:6.1%}\")"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": [
"# How far apart are the two cities, feature by feature?\n",
"# Expressed in Madrid standard deviations, so it is directly comparable.\n",
"key = [\"sr_brightness_mean\", \"sr_Red_mean\", \"sr_NIR_mean\", \"sr_SWIR1_mean\",\n",
" \"sr_NDVI_mean\", \"sr_NDBI_mean\", \"sr_UI_mean\", \"sr_MNDWI_mean\",\n",
" \"sr_BSI_mean\", \"sr_brightness_std\", \"sr_brightness_late_minus_early\",\n",
" \"step_brightness_mag\", \"step_brightness_njumps\", \"coverage\"]\n",
"key = [k for k in key if k in madrid.columns and k in amsterdam.columns]\n",
"gap = pd.DataFrame({\n",
" \"madrid_mean\": [madrid[k].mean() for k in key],\n",
" \"amsterdam_mean\": [amsterdam[k].mean() for k in key],\n",
"}, index=key)\n",
"gap[\"madrid_sd\"] = [madrid[k].std() for k in key]\n",
"gap[\"gap_in_madrid_sd\"] = (gap.amsterdam_mean - gap.madrid_mean) / gap.madrid_sd\n",
"print(gap.round(3).sort_values(\"gap_in_madrid_sd\").to_string())"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A feature whose `gap_in_madrid_sd` is near zero is one a Madrid-trained model\n",
"can still read in Amsterdam. A feature at +/-2 is telling the model which\n",
"*city* it is looking at, not how old the building is."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"# Within-class spread versus between-city gap, for the top offenders.\n",
"fig, axes = plt.subplots(2, 4, figsize=(18, 7))\n",
"for ax, k in zip(axes.ravel(), key[:8]):\n",
" for name, df, col in [(\"Madrid\", madrid, \"tab:red\"),\n",
" (\"Amsterdam\", amsterdam, \"tab:blue\")]:\n",
" ax.hist(df[k], bins=60, density=True, alpha=0.45, label=name, color=col)\n",
" ax.set_title(k, fontsize=9)\n",
" ax.tick_params(labelsize=7)\n",
"axes.ravel()[0].legend(fontsize=8)\n",
"plt.suptitle(\"The same feature in the two cities\", fontweight=\"bold\")\n",
"plt.tight_layout()\n",
"plt.show()"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1.6 Does the construction-event detector actually work?\n",
"\n",
"A genuine test of the extended features. For classes 3 and 4 the building went\n",
"up *during* the satellite record, so `step_brightness_year` should land near\n",
"`weighted_mean_year`. For classes 1 and 2 it was already standing in 1984, so\n",
"the detector should find nothing meaningful. If that pattern does not show up,\n",
"the detector is noise and should be dropped."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"for name, df in [(\"Madrid\", madrid), (\"Amsterdam\", amsterdam)]:\n",
" print(f\"\\n{name}\")\n",
" for sig in (\"brightness\", \"SWIR1\", \"NDVI\"):\n",
" sub = df[df.age_class.isin([3, 4])]\n",
" err = (sub[f\"step_{sig}_year\"] - sub[\"weighted_mean_year\"]).abs()\n",
" r = np.corrcoef(sub[f\"step_{sig}_year\"], sub[\"weighted_mean_year\"])[0, 1]\n",
" print(f\" step_{sig}_year vs true year (classes 3+4): r={r:+.3f} \"\n",
" f\"median |error| = {err.median():.1f} years \"\n",
" f\"within 5 y: {(err <= 5).mean():.1%}\")\n",
" print(\" mean |step magnitude| by class:\",\n",
" df.groupby(\"age_class\")[\"step_brightness_mag\"].apply(\n",
" lambda s: round(float(s.abs().mean()), 4)).to_dict())"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": [
"fig, axes = plt.subplots(1, 2, figsize=(13, 4.5))\n",
"for ax, (name, df) in zip(axes, [(\"Madrid\", madrid), (\"Amsterdam\", amsterdam)]):\n",
" sub = df[df.age_class.isin([3, 4])].sample(min(4000, len(df)), random_state=0)\n",
" ax.scatter(sub[\"weighted_mean_year\"], sub[\"step_brightness_year\"], s=3,\n",
" alpha=0.25)\n",
" lims = [1984, 2024]\n",
" ax.plot(lims, lims, \"r--\", lw=1)\n",
" ax.set(xlabel=\"true construction year\", ylabel=\"detected brightness step year\",\n",
" title=f\"{name}: classes 3 and 4\", xlim=lims, ylim=lims)\n",
"plt.tight_layout()\n",
"plt.show()"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1.7 Neighbourhood context - free information, no labels\n",
"\n",
"Buildings go up a street at a time, so a pixel's neighbours carry real signal\n",
"about its era. These features average a few key quantities over the 8 nearest\n",
"pixels (within 10 pixel units = 300 m) and also store the *difference* between\n",
"the pixel and its surroundings. No labels are involved, so this is available\n",
"in Amsterdam at n = 0."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"madrid = R.add_neighbourhood_features(madrid)\n",
"amsterdam = R.add_neighbourhood_features(amsterdam)\n",
"nbr_cols = [c for c in madrid.columns if c.startswith(\"nbr_\")]\n",
"print(f\"added {len(nbr_cols)} neighbourhood features\")\n",
"print(madrid[[\"age_class\"] + nbr_cols[:6]].groupby(\"age_class\").mean().round(4).to_string())"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1.8 Save\n",
"\n",
"One parquet per city. Every later notebook starts from these."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"C.PROC_DIR.mkdir(parents=True, exist_ok=True)\n",
"madrid.to_parquet(C.PROC_DIR / \"madrid_features.parquet\", index=False)\n",
"amsterdam.to_parquet(C.PROC_DIR / \"amsterdam_features.parquet\", index=False)\n",
"for n, df in [(\"madrid\", madrid), (\"amsterdam\", amsterdam)]:\n",
" p = C.PROC_DIR / f\"{n}_features.parquet\"\n",
" print(f\"{p} {p.stat().st_size / 1e6:.1f} MB {df.shape}\")\n",
"print(\"\\nfeature groups:\",\n",
" f\"{len(C.FEATURE_COLS_60)} official,\",\n",
" f\"{sum(1 for c in madrid.columns if c.startswith('sr_'))} reflectance-based,\",\n",
" f\"{sum(1 for c in madrid.columns if c.startswith('step_'))} change-event,\",\n",
" f\"{len(nbr_cols)} neighbourhood\")"
],
"execution_count": null,
"outputs": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"name": "python",
"version": "3.11"
},
"accelerator": "GPU",
"colab": {
"provenance": [],
"gpuType": "L4"
}
},
"nbformat": 4,
"nbformat_minor": 5
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 3 - LightGBM and CatBoost: the two classical models\n",
"\n",
"The organisers ask for at least two models, chosen on Madrid. These are them.\n",
"They are also the honest yardstick the fine-tuned LLM has to beat, and the\n",
"source of the probabilities we later ensemble with it.\n",
"\n",
"Running order:\n",
"\n",
"1. **Spatial** cross-validation on Madrid - random folds are dishonest here,\n",
" because neighbouring pixels share a construction era.\n",
"2. **Adversarial validation** - find the features that only say \"this is\n",
" Madrid\" and drop them.\n",
"3. **Per-city normalisation** - the single biggest transfer win, and it needs\n",
" no labels.\n",
"4. **LightGBM vs CatBoost vs ordinal LightGBM**, all judged on Madrid only.\n",
"5. **The official few-shot protocol** at n = 5, 25, 50, 100, 200.\n",
"\n",
"Runs on CPU. About 20 minutes on a laptop."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"import sys\n",
"from pathlib import Path\n",
"\n",
"for cand in [Path.cwd() / \"src\", Path.cwd().parent / \"src\",\n",
" Path(\"/kaggle/working/src\"), Path(\"/content/hack4dev/src\")]:\n",
" if cand.exists():\n",
" sys.path.insert(0, str(cand))\n",
" break\n",
"\n",
"import numpy as np\n",
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"\n",
"import config as C\n",
"import evaluation as E\n",
"import gbdt as G\n",
"import retrieval as R\n",
"\n",
"RNG = np.random.default_rng(C.RANDOM_SEED)\n",
"\n",
"# Prefer the full feature tables from notebook 1. Fall back to the organisers'\n",
"# preprocessed_data.pkl, which carries the official 60 features and the pixel\n",
"# coordinates - enough for everything in THIS notebook, and only ~50 MB, so it\n",
"# is the right thing to grab first if the raw parquet is hard to get hold of.\n",
"import features as F\n",
"\n",
"if (C.PROC_DIR / \"madrid_features.parquet\").exists():\n",
" madrid = pd.read_parquet(C.PROC_DIR / \"madrid_features.parquet\")\n",
" amsterdam = pd.read_parquet(C.PROC_DIR / \"amsterdam_features.parquet\")\n",
" SOURCE = \"notebook 1 (official 60 + extended)\"\n",
"else:\n",
" pkl = None\n",
" for root in [C.DATA_DIR, C.PROJECT_ROOT, Path(\"/kaggle/input\")]:\n",
" if root.exists():\n",
" hits = sorted(root.rglob(\"preprocessed_data.pkl\"))\n",
" if hits:\n",
" pkl = hits[0]\n",
" break\n",
" if pkl is None:\n",
" raise FileNotFoundError(\n",
" \"Neither data/processed/madrid_features.parquet (run notebook 1) \"\n",
" \"nor preprocessed_data.pkl were found.\")\n",
" madrid, amsterdam = F.from_official_pkl(pkl)\n",
" SOURCE = \"organisers' preprocessed_data.pkl (official 60 only)\"\n",
"\n",
"print(f\"\\nfeature source: {SOURCE}\")\n",
"print(madrid.shape, amsterdam.shape)"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": [
"# Feature sets we will compare. Keeping them explicit makes the ablation table\n",
"# in the report trivial to produce.\n",
"DROP = {\"px_key\", \"py_key\", \"age_class\", \"weighted_mean_year\", \"city\"}\n",
"ALL_FEATS = [c for c in madrid.columns\n",
" if c not in DROP and madrid[c].dtype.kind in \"fiu\"]\n",
"DEAD = [c for c in ALL_FEATS if madrid[c].std() == 0 or amsterdam[c].std() == 0]\n",
"ALL_FEATS = [c for c in ALL_FEATS if c not in DEAD]\n",
"\n",
"FEATURE_SETS = {\n",
" \"official60\": [c for c in C.FEATURE_COLS_60 if c in ALL_FEATS],\n",
" \"reflectance\": [c for c in ALL_FEATS if c.startswith(\"sr_\")],\n",
" \"events\": [c for c in ALL_FEATS if c.startswith(\"step_\")],\n",
" \"neighbourhood\": [c for c in ALL_FEATS if c.startswith(\"nbr_\")],\n",
" \"everything\": ALL_FEATS,\n",
"}\n",
"print(\"dead (zero variance in at least one city):\", DEAD)\n",
"for k, v in FEATURE_SETS.items():\n",
" print(f\" {k:<14} {len(v)} features\")\n",
"\n",
"y_mad = madrid[\"age_class\"].to_numpy()\n",
"y_ams = amsterdam[\"age_class\"].to_numpy() # opened only for scoring\n",
"coords_mad = madrid[C.PID].to_numpy(float)\n",
"coords_ams = amsterdam[C.PID].to_numpy(float)"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3.1 An honest validation split\n",
"\n",
"`RepeatedStratifiedKFold` on pixels puts a pixel's own neighbours in the\n",
"training fold. Neighbours share an era, so the model can almost look up the\n",
"answer, and Madrid CV comes out flattering - part of why 0.63 on Madrid turns\n",
"into 0.34 on Amsterdam.\n",
"\n",
"Instead: cut Madrid into geographic blocks and hold out whole blocks. That is\n",
"our stand-in for \"a city the model has never seen\", and it is the only thing\n",
"we are allowed to choose models on."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"blocks_mad = R.spatial_blocks(coords_mad, n_blocks=25)\n",
"print(\"block sizes:\", np.bincount(blocks_mad))\n",
"\n",
"fig, ax = plt.subplots(figsize=(7, 5))\n",
"ax.scatter(coords_mad[:, 0], coords_mad[:, 1], c=blocks_mad, s=1, cmap=\"tab20\")\n",
"ax.set(title=\"Madrid split into spatial blocks\", xlabel=\"px_key\", ylabel=\"py_key\")\n",
"plt.tight_layout()\n",
"plt.show()\n",
"\n",
"\n",
"def block_cv(X, y, blocks, fit_fn, n_folds=5, normalise=\"robustz\", seed=0):\n",
" \"\"\"Hold out whole geographic blocks, score macro F1 on each.\"\"\"\n",
" uniq = np.unique(blocks)\n",
" rng = np.random.default_rng(seed)\n",
" order = rng.permutation(uniq)\n",
" folds = np.array_split(order, n_folds)\n",
" scores, oof = [], np.zeros((len(y), 4))\n",
" for f in folds:\n",
" te = np.isin(blocks, f)\n",
" tr = ~te\n",
" nrm = G.CityNormaliser(normalise).fit(X[tr]) if normalise else None\n",
" Xtr = nrm.transform(X[tr]) if nrm else X[tr]\n",
" # The held-out block plays the part of a new city: it gets normalised\n",
" # with its OWN statistics, exactly as Amsterdam will be.\n",
" nte = G.CityNormaliser(normalise).fit(X[te]) if normalise else None\n",
" Xte = nte.transform(X[te]) if nte else X[te]\n",
" m = fit_fn(Xtr, y[tr])\n",
" p = m.predict_proba(Xte)\n",
" oof[te] = p\n",
" scores.append(E.macro_f1(y[te], E.CLASSES[np.argmax(p, 1)]))\n",
" return np.array(scores), oof"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3.2 Which features betray the city?\n",
"\n",
"Train a classifier to separate Madrid pixels from Amsterdam pixels. If it\n",
"succeeds easily, the features carry a strong city signature. The most\n",
"important features in *that* task are the ones most likely to mislead the age\n",
"model, and are candidates for removal."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"auc, imp = G.adversarial_validation(madrid[ALL_FEATS], amsterdam[ALL_FEATS], ALL_FEATS)\n",
"print(f\"city-vs-city AUC: {auc:.4f} (1.0 = the two cities are trivially told apart)\")\n",
"print(imp.head(20).to_string(index=False))"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The joint model tells us the cities are separable; it does not tell us which\n",
"feature is to blame, because importance is shared among correlated features.\n",
"A single-feature AUC does, and the before/after table is the most convincing\n",
"figure in the write-up: 0.5 means a feature is domain-invariant, 1.0 means it\n",
"is a pure city marker and any Madrid split on it is meaningless in Amsterdam."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"Xm_all = madrid[ALL_FEATS].to_numpy(float)\n",
"Xa_all = amsterdam[ALL_FEATS].to_numpy(float)\n",
"sf_raw = G.single_feature_domain_auc(Xm_all, Xa_all, ALL_FEATS)\n",
"\n",
"# The rankable mask is a STRUCTURAL decision about the features, so it is\n",
"# computed once on Madrid - the design city - and shared. Fitting it per city\n",
"# lets a column be ranked in one and z-scored in the other, which puts them on\n",
"# different scales and reports a domain AUC of 1.000 for a feature that is\n",
"# actually domain-invariant. `n_observed_years` did exactly that.\n",
"RANKABLE = G.rankable_mask(Xm_all)\n",
"print(f\"rank-transformable on Madrid: {RANKABLE.sum()} of {len(ALL_FEATS)}; \"\n",
" f\"too heavily tied to rank: {[ALL_FEATS[j] for j in np.flatnonzero(~RANKABLE)]}\")\n",
"nm_ = G.CityNormaliser(\"rank\", rankable=RANKABLE).fit(Xm_all).transform(Xm_all)\n",
"na_ = G.CityNormaliser(\"rank\", rankable=RANKABLE).fit(Xa_all).transform(Xa_all)\n",
"sf_rank = G.single_feature_domain_auc(nm_, na_, ALL_FEATS)\n",
"screen = (sf_raw.rename(columns={\"domain_auc\": \"auc_raw\"})\n",
" .merge(sf_rank.rename(columns={\"domain_auc\": \"auc_after_rank\"}), on=\"feature\")\n",
" .sort_values(\"auc_raw\", ascending=False))\n",
"print(\"worst offenders, raw vs after per-city rank normalisation:\")\n",
"print(screen.head(25).round(3).to_string(index=False))\n",
"print(f\"\\nmedian domain AUC: raw {screen.auc_raw.median():.3f} -> \"\n",
" f\"after rank {screen.auc_after_rank.median():.3f}\")\n",
"print(f\"features still above 0.90 after normalisation: \"\n",
" f\"{(screen.auc_after_rank > 0.90).sum()} of {len(screen)}\")\n",
"screen.to_csv(C.REPORT_DIR / \"domain_auc_screen.csv\", index=False)\n",
"\n",
"fig, ax = plt.subplots(figsize=(7, 5))\n",
"ax.scatter(screen.auc_raw, screen.auc_after_rank, s=8, alpha=0.5)\n",
"ax.plot([0.5, 1], [0.5, 1], \"k--\", lw=1)\n",
"ax.set(xlabel=\"domain AUC, raw\", ylabel=\"domain AUC, after per-city rank\",\n",
" title=\"Per-city ranking removes the city signature (points below the line)\")\n",
"plt.tight_layout()\n",
"plt.show()"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": [
"# Repeat after per-city normalisation: a good normaliser should make the cities\n",
"# harder to tell apart without destroying the age signal.\n",
"nm = G.CityNormaliser(\"robustz\").fit(Xm_all).transform(Xm_all)\n",
"na = G.CityNormaliser(\"robustz\").fit(Xa_all).transform(Xa_all)\n",
"auc_z, imp_z = G.adversarial_validation(nm, na, ALL_FEATS)\n",
"auc_r, imp_r = G.adversarial_validation(nm_, na_, ALL_FEATS) # shared mask\n",
"print(f\"AUC raw {auc:.4f} | robust-z {auc_z:.4f} | rank {auc_r:.4f}\")\n",
"print(\"\\nstill city-specific after rank normalisation:\")\n",
"print(imp_r.head(12).to_string(index=False))"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Read the two screens together, because they say different things and the\n",
"difference is the point.\n",
"\n",
"Per-city **rank** normalisation forces every feature's marginal distribution\n",
"to be uniform in both cities, so the *single-feature* domain AUC becomes\n",
"exactly 0.5 by construction. That is not evidence that the domain gap is\n",
"gone. If the *joint* adversarial AUC above is still near 1.0 after ranking,\n",
"the city signature has simply moved into the **correlations between**\n",
"features, where a marginal transform cannot reach it.\n",
"\n",
"That is precisely what CORAL addresses - it matches second-order statistics\n",
"rather than marginals. So the honest conclusion from these two cells is:\n",
"ranking is necessary and cheap, and it is not sufficient. Whether CORAL on\n",
"top actually helps is an empirical question answered in section 3.5, not a\n",
"foregone conclusion: in synthetic testing CORAL slightly *hurt* when the\n",
"shift was close to diagonal."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### The drop rule, and why it must be conservative\n",
"\n",
"The tempting rule is \"drop the top features by adversarial importance\". It is\n",
"wrong. With 59 features the average importance share is 1/59 = 0.017, so any\n",
"threshold near that drops whatever happens to be slightly above average -\n",
"and once normalisation has pushed the joint AUC down to ~0.5, those\n",
"importances are *noise*. In an earlier run this rule dropped three features\n",
"whose single-feature domain AUC was exactly 0.500, i.e. perfectly\n",
"domain-invariant ones.\n",
"\n",
"The principled rule needs two conditions, both of them absolute rather than\n",
"relative: a feature is dropped only if it is **still** strongly\n",
"city-discriminative on its own after normalisation, **and** it is not\n",
"carrying much of the age signal on Madrid. Usually that drops nothing, which\n",
"is the correct answer."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"AUC_CUT = 0.90 # still a city marker after normalisation\n",
"IMP_CUT = 0.005 # and contributes little to the Madrid model\n",
"\n",
"X_all = madrid[ALL_FEATS].to_numpy(float)\n",
"probe = G.fit_lgbm(G.CityNormaliser(\"rank\").fit_transform(X_all), y_mad,\n",
" params=dict(n_estimators=300))\n",
"age_imp = pd.DataFrame({\n",
" \"feature\": ALL_FEATS,\n",
" \"age_importance\": probe.feature_importances_ / max(probe.feature_importances_.sum(), 1)\n",
"})\n",
"drop_tbl = screen.merge(age_imp, on=\"feature\")\n",
"leaky = drop_tbl[(drop_tbl.auc_after_rank > AUC_CUT)\n",
" & (drop_tbl.age_importance < IMP_CUT)].feature.tolist()\n",
"FEATURE_SETS[\"pruned\"] = [c for c in ALL_FEATS if c not in leaky]\n",
"print(f\"features still above AUC {AUC_CUT} after normalisation: \"\n",
" f\"{(drop_tbl.auc_after_rank > AUC_CUT).sum()}\")\n",
"print(f\"dropping {len(leaky)}: {leaky if leaky else 'nothing - as expected'}\")\n",
"print(f\"pruned set: {len(FEATURE_SETS['pruned'])} features\")\n",
"print(\"\\nmost city-specific features that we KEPT because they carry age signal:\")\n",
"print(drop_tbl.sort_values(\"auc_after_rank\", ascending=False)\n",
" .head(8).round(4).to_string(index=False))"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3.3 Model and feature-set comparison, on Madrid only\n",
"\n",
"Every row of this table is decided with Madrid block-CV. Amsterdam is not\n",
"consulted. This is the table that justifies the final model choice."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"# The comparison runs 4 models x 3 feature sets x 5 blocked folds = 60 fits.\n",
"# At full strength (1200 LightGBM rounds, 2000 CatBoost iterations) that is\n",
"# tens of minutes on 76k rows, and it buys nothing: we are reading the\n",
"# ORDERING of configurations here, not their final scores. So compare cheaply,\n",
"# then refit the winner at full strength in section 3.7.\n",
"CHEAP_LGB = dict(n_estimators=400, learning_rate=0.06)\n",
"CHEAP_CAT = dict(iterations=500, learning_rate=0.06)\n",
"\n",
"\n",
"def lgbm_balanced(X, y):\n",
" return G.fit_lgbm(X, y, params=CHEAP_LGB,\n",
" class_weight=dict(zip(range(4), G.balanced_class_weights(y))))\n",
"\n",
"def lgbm_plain(X, y):\n",
" return G.fit_lgbm(X, y, params=CHEAP_LGB)\n",
"\n",
"def cat_balanced(X, y):\n",
" return G.fit_catboost(X, y, params=CHEAP_CAT,\n",
" class_weights=G.balanced_class_weights(y))\n",
"\n",
"def ordinal_lgbm(X, y):\n",
" return G.OrdinalGBDT(params=CHEAP_LGB).fit(X, y)\n",
"\n",
"import time\n",
"\n",
"FEATURE_SETS_TO_TRY = [k for k in (\"official60\", \"everything\", \"pruned\")\n",
" if len(FEATURE_SETS.get(k, []))]\n",
"# Drop a duplicate: with the pkl-only fallback, \"everything\" == \"official60\".\n",
"seen, uniq = set(), []\n",
"for k in FEATURE_SETS_TO_TRY:\n",
" sig = tuple(FEATURE_SETS[k])\n",
" if sig not in seen:\n",
" seen.add(sig)\n",
" uniq.append(k)\n",
" else:\n",
" print(f\" (skipping '{k}' - identical to an earlier set)\")\n",
"FEATURE_SETS_TO_TRY = uniq\n",
"\n",
"rows = []\n",
"for fs_name in FEATURE_SETS_TO_TRY:\n",
" X = madrid[FEATURE_SETS[fs_name]].to_numpy(float)\n",
" models = [(\"lgbm\", lgbm_balanced), (\"lgbm_unweighted\", lgbm_plain),\n",
" (\"lgbm_ordinal\", ordinal_lgbm)]\n",
" if fs_name == FEATURE_SETS_TO_TRY[0]:\n",
" # CatBoost costs 35 min per feature set against LightGBM's 10 and came\n",
" # in about 0.008 behind on every set, so it runs on one set only. It\n",
" # still ships as the second required model.\n",
" models.append((\"catboost\", cat_balanced))\n",
" for mdl_name, fn in models:\n",
" t0 = time.time()\n",
" s, oof = block_cv(X, y_mad, blocks_mad, fn)\n",
" rows.append(dict(features=fs_name, model=mdl_name, n_feat=X.shape[1],\n",
" macro_f1=s.mean(), std=s.std(ddof=1),\n",
" minutes=(time.time() - t0) / 60))\n",
" print(f\" {fs_name:<12} {mdl_name:<16} {s.mean():.4f} +- \"\n",
" f\"{s.std(ddof=1):.4f} ({rows[-1]['minutes']:.1f} min)\")\n",
"table = pd.DataFrame(rows).sort_values(\"macro_f1\", ascending=False)\n",
"print(\"\\n\" + table.round(4).to_string(index=False))"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Does per-city normalisation actually help? Decide it on Madrid.\n",
"\n",
"This has to be settled here and not on the Amsterdam score, because the\n",
"Amsterdam score is not ours to choose on. `block_cv` is the right instrument:\n",
"it normalises the held-out block with the block's OWN statistics, exactly as\n",
"Amsterdam will be normalised, so each fold is a miniature transfer problem.\n",
"\n",
"Worth doing carefully, because the intuition (\"absolute reflectance does not\n",
"transfer, so normalise it away\") is strong and may still be wrong. Per-city\n",
"normalisation also destroys genuine between-city differences in LEVEL, and if\n",
"a city's overall darkness happens to correlate with its class mix, removing\n",
"the level removes a real cue along with the nuisance."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"norm_rows = []\n",
"X_best = madrid[FEATURE_SETS[table.iloc[0].features]].to_numpy(float)\n",
"for norm in (None, \"robustz\", \"rank\"):\n",
" s, _ = block_cv(X_best, y_mad, blocks_mad, lgbm_plain, normalise=norm)\n",
" norm_rows.append(dict(normalise=str(norm), macro_f1=s.mean(),\n",
" std=s.std(ddof=1)))\n",
" print(f\" normalise={str(norm):8} {s.mean():.4f} +- {s.std(ddof=1):.4f}\")\n",
"norm_table = pd.DataFrame(norm_rows).sort_values(\"macro_f1\", ascending=False)\n",
"print(\"\\n\" + norm_table.round(4).to_string(index=False))\n",
"BEST_NORM = None if norm_table.iloc[0].normalise == \"None\" else norm_table.iloc[0].normalise\n",
"print(f\"\\nnormalisation chosen on Madrid: {BEST_NORM}\")\n",
"print(\"Whatever Amsterdam says later, this is the choice the rules allow us to\")\n",
"print(\"make. If Amsterdam disagrees, that is a finding to report, not a reason\")\n",
"print(\"to switch.\")"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3.4 The decision rule matters as much as the model\n",
"\n",
"Macro F1 is not maximised by `argmax`. Three cheap post-processing steps,\n",
"each measured separately on Madrid block-CV:\n",
"\n",
"* **class weights** tuned by coordinate ascent on out-of-fold probabilities;\n",
"* **prior correction** towards the class prior EM estimates from *unlabelled*\n",
" target features;\n",
"* **spatial smoothing** of the probabilities over neighbouring pixels."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"BEST_FS = table.iloc[0].features\n",
"X_mad = madrid[FEATURE_SETS[BEST_FS]].to_numpy(float)\n",
"X_ams = amsterdam[FEATURE_SETS[BEST_FS]].to_numpy(float)\n",
"scores, oof = block_cv(X_mad, y_mad, blocks_mad, lgbm_balanced)\n",
"print(f\"baseline argmax, Madrid block-CV: {E.macro_f1(y_mad, E.CLASSES[np.argmax(oof, 1)]):.4f}\")\n",
"\n",
"w = E.tune_class_weights(oof, y_mad)\n",
"print(\"tuned class weights:\", np.round(w, 3))\n",
"print(\"after weighting: \",\n",
" f\"{E.macro_f1(y_mad, E.predict_weighted(oof, w)):.4f}\")\n",
"\n",
"for radius in (2.0, 4.0, 8.0):\n",
" sm = E.spatial_smooth(oof, coords_mad, radius=radius, alpha=0.5)\n",
" print(f\"spatial smoothing r={radius:>4}: \"\n",
" f\"{E.macro_f1(y_mad, E.predict_weighted(sm, w)):.4f}\")"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": [
"print(pd.DataFrame(E.confusion_proportions(y_mad, E.predict_weighted(oof, w)),\n",
" index=[f\"true {c}\" for c in E.CLASSES],\n",
" columns=[f\"pred {c}\" for c in E.CLASSES]).round(3).to_string())"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3.5 The simulated-shift harness - choosing the decision rule on Madrid\n",
"\n",
"This is the most important cell in the notebook, and the thing I would most\n",
"want the team to copy.\n",
"\n",
"None of the adaptation tricks above can be chosen honestly without a way to\n",
"*simulate* Amsterdam from Madrid. So: hold out a spatial block, and build four\n",
"versions of it.\n",
"\n",
"* `clean` - as-is;\n",
"* `label` - resampled to a random Dirichlet class prior (pure label shift);\n",
"* `covariate` - every feature quantile-mapped onto Amsterdam's own marginal\n",
" (pure covariate shift, using `X_amsterdam` only, no labels);\n",
"* `both`.\n",
"\n",
"Then score every candidate decision rule on all four. A rule that helps under\n",
"label shift can lose badly under covariate shift, and without this there is no\n",
"way to tell which regime you are actually in. **Ship only rules that are\n",
"non-negative in the worst case.**\n",
"\n",
"In synthetic testing this harness caught a trap: free SLD-EM prior estimation\n",
"looked excellent under label shift and lost 0.19 macro F1 on average (0.35 at\n",
"worst) under covariate shift, because EM assumes label shift only. The\n",
"macro-F1 plug-in rule driven by the *source* prior was the robust winner."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"# Note the UNWEIGHTED model here. The whole point of this cell is to choose the\n",
"# operating point, so the probabilities going into it must be an honest estimate\n",
"# of the Madrid posterior. class_weight='balanced' bakes a decision into the fit,\n",
"# where no decision rule can undo it.\n",
"harness_df, harness_table = E.shift_harness(\n",
" lgbm_plain, X_mad, y_mad, blocks_mad, X_ams,\n",
" E.DEFAULT_STRATEGIES, n_folds=5, n_rep=4, seed=C.RANDOM_SEED)\n",
"harness_table.to_csv(C.REPORT_DIR / \"shift_harness.csv\")"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": [
"# The criterion is the PER-REGIME worst case: for each rule, its deficit\n",
"# against argmax in whichever regime it handles worst. An earlier version used\n",
"# a column that compared each rule's worst cell anywhere against argmax's worst\n",
"# cell anywhere - two different regimes and two different folds - so a rule\n",
"# could look safe merely because its bad regime was also argmax's bad regime.\n",
"WORST = \"delta_vs_argmax_worst_regime\"\n",
"safe = harness_table[harness_table.get(WORST, 0) >= 0]\n",
"print(\"rules that never lose to plain argmax in ANY regime:\")\n",
"print(safe.round(4).to_string() if len(safe) else \" none - keep plain argmax\")\n",
"print(\"\\nrules to avoid:\")\n",
"risky = harness_table[harness_table.get(WORST, 0) < -0.01]\n",
"print(risky.round(4).to_string() if len(risky) else \" none\")\n",
"\n",
"CHOSEN_RULE = (harness_table[WORST].idxmax()\n",
" if WORST in harness_table else \"argmax\")\n",
"print(f\"\\nrule chosen on Madrid alone: {CHOSEN_RULE}\")\n",
"DECISION = E.DEFAULT_STRATEGIES[CHOSEN_RULE]"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3.6 The official few-shot protocol\n",
"\n",
"`y_amsterdam` enters here and only here: to draw the n labelled pixels per\n",
"class that the rules allow, and to score the remainder. Nothing above was\n",
"tuned on it."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"N_LIST = (5, 25, 50, 100, 200)\n",
"N_REPEATS = 12\n",
"# Score a fixed random 8,000-pixel sample of Amsterdam rather than all 25,992.\n",
"# Full scoring cost 19 s per draw - 32 minutes for one variant and hours for the\n",
"# table - and bought nothing: the variants that ignore the labelled sample have\n",
"# a standard deviation of 0.0001 across draws. The subsample is fixed, so every\n",
"# row of the table is compared on identical pixels. Re-run the winner on all\n",
"# 25,992 once, at the end, for the number that goes in the report.\n",
"EVAL_SUBSAMPLE = 8000\n",
"src_prior = np.array([(y_mad == c).mean() for c in E.CLASSES])\n",
"print('Madrid class prior:', np.round(src_prior, 3))\n",
"\n",
"# Cost control. Most variants cache the Madrid-trained model across repeats, so\n",
"# 20 draws are cheap. `upweighted shots, retrained` refits from scratch on every\n",
"# draw - 100 full fits on 76k rows - so it gets cheap params and fewer draws,\n",
"# and its std is correspondingly noisier. That is noted in the table.\n",
"REPEATS = {\"upweighted shots, retrained\": 5}\n",
"\n",
"variants = {\n",
" # the two baselines everything must beat\n",
" \"organisers' prototype (Euclidean, Madrid scaler)\": G.mc_prototype_official(),\n",
" \"pure retrieval k-NN (no source model)\": G.mc_knn(),\n",
" # zero-shot: does normalisation alone carry us?\n",
" \"zero-shot, no normalisation\": G.mc_zero_shot(normalise=None),\n",
" \"zero-shot, robust z\": G.mc_zero_shot(normalise=\"robustz\"),\n",
" \"zero-shot, rank\": G.mc_zero_shot(normalise=\"rank\"),\n",
" \"zero-shot, robust z + CORAL\": G.mc_zero_shot(normalise=\"robustz\", use_coral=True),\n",
" # the prototype metric ablation. On synthetic anisotropic data the pooled\n",
" # WITHIN-class Mahalanobis metric beat the organisers' Euclidean prototype\n",
" # by +0.11 macro F1 at n=25 - the largest single gain of anything tried.\n",
" # The total-covariance version is worse because the target city's total\n",
" # covariance is dominated by BETWEEN-class spread, so it shrinks exactly the\n",
" # directions that separate the classes. Confirm the ordering here on the\n",
" # real features before believing it.\n",
" \"prototype, robust z + euclidean\": G.mc_prototype(metric=\"euclidean\"),\n",
" \"prototype, rank + euclidean\": G.mc_prototype(normalise=\"rank\", metric=\"euclidean\"),\n",
" \"prototype, robust z + total-cov Mahalanobis\": G.mc_prototype(metric=\"total\"),\n",
" \"prototype, robust z + within-class Mahalanobis\": G.mc_prototype(metric=\"within\"),\n",
" # using the labelled sample with the source model\n",
" \"recalibrated (stratification-corrected)\": G.mc_recalibrated(normalise=\"robustz\"),\n",
" \"refit leaf values (structure frozen)\": G.mc_refit(),\n",
" \"upweighted shots, retrained\": G.mc_shot_weighted(\n",
" normalise=\"robustz\", fit=lambda X, y, **kw: G.fit_lgbm(X, y, params=CHEAP_LGB, **kw)),\n",
" \"catboost recalibrated\": G.mc_recalibrated(fit=G.fit_catboost, normalise=\"robustz\"),\n",
"}\n",
"\n",
"protocol = {}\n",
"for name, mc in variants.items():\n",
" print(f\"\\n{name}\")\n",
" reps = REPEATS.get(name, N_REPEATS)\n",
" t0 = time.time()\n",
" protocol[name] = E.evaluate_protocol(\n",
" mc, X_mad, y_mad, X_ams, y_ams, n_list=N_LIST, n_repeats=reps,\n",
" decision=lambda p: DECISION(p, src_prior),\n",
" eval_subsample=EVAL_SUBSAMPLE)\n",
" print(f\" ({reps} draws per n, {(time.time() - t0) / 60:.1f} min)\")"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": [
"summary = pd.DataFrame({name: {n: r[\"mean\"] for n, r in res.items()}\n",
" for name, res in protocol.items()}).T\n",
"summary[\"average\"] = summary.mean(axis=1)\n",
"summary[\"peak\"] = summary[list(N_LIST)].max(axis=1)\n",
"print(summary.round(4).sort_values(\"average\", ascending=False).to_string())"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": [
"fig, ax = plt.subplots(figsize=(8, 5))\n",
"for name, res in protocol.items():\n",
" m = [res[n][\"mean\"] for n in N_LIST]\n",
" s = [res[n][\"std\"] for n in N_LIST]\n",
" ax.errorbar(np.log2(N_LIST), m, yerr=s, marker=\"o\", capsize=3, label=name)\n",
"ax.axhline(0.618, ls=\"--\", c=\"k\", lw=1, label=\"published Madrid baseline 0.618\")\n",
"ax.set(xlabel=\"log2(labelled Amsterdam pixels per class)\", ylabel=\"macro F1 on Amsterdam\",\n",
" title=\"Macro F1 against labelling budget\")\n",
"ax.legend(fontsize=7)\n",
"plt.tight_layout()\n",
"plt.show()"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3.7 Save the probabilities for the ensemble\n",
"\n",
"The LLM notebook loads these and blends them with its own predictions."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"import pickle\n",
"\n",
"best_name = summary.sort_values(\"average\", ascending=False).index[0]\n",
"print(\"best classical variant on the protocol:\", best_name)\n",
"\n",
"nrm_m = G.CityNormaliser(\"robustz\").fit(X_mad)\n",
"nrm_a = G.CityNormaliser(\"robustz\").fit(X_ams)\n",
"final = G.fit_lgbm(nrm_m.transform(X_mad), y_mad,\n",
" class_weight=dict(zip(range(4), G.balanced_class_weights(y_mad))))\n",
"final_cat = G.fit_catboost(nrm_m.transform(X_mad), y_mad,\n",
" class_weights=G.balanced_class_weights(y_mad))\n",
"\n",
"out = {\n",
" \"feature_set\": BEST_FS,\n",
" \"feature_names\": FEATURE_SETS[BEST_FS],\n",
" \"madrid_oof_proba\": oof,\n",
" \"madrid_blocks\": blocks_mad,\n",
" \"class_weights\": w,\n",
" \"amsterdam_proba_lgbm\": final.predict_proba(nrm_a.transform(X_ams)),\n",
" \"amsterdam_proba_catboost\": final_cat.predict_proba(nrm_a.transform(X_ams)),\n",
" \"protocol\": {k: {n: dict(mean=r[\"mean\"], std=r[\"std\"],\n",
" per_class=r[\"per_class\"].tolist())\n",
" for n, r in v.items()} for k, v in protocol.items()},\n",
" # Plain lists, not a DataFrame: this file is read on Colab, whose pandas\n",
" # 2.x cannot unpickle a pandas 3 DataFrame with string columns\n",
" # (\"StringDtype.__init__() takes from 1 to 2 positional arguments\").\n",
" # Rebuild with pd.DataFrame(out[\"madrid_block_cv_table\"]).\n",
" \"madrid_block_cv_table\": {c: table[c].tolist() for c in table.columns},\n",
" \"adversarial_auc\": dict(raw=auc, robustz=auc_z, rank=auc_r),\n",
" \"dropped_city_specific\": leaky,\n",
"}\n",
"with open(C.PROC_DIR / \"gbdt_outputs.pkl\", \"wb\") as fh:\n",
" pickle.dump(out, fh)\n",
"final.booster_.save_model(str(C.PROC_DIR / \"model_lgbm.txt\"))\n",
"final_cat.save_model(str(C.PROC_DIR / \"model_catboost.cbm\"))\n",
"print(\"saved:\", C.PROC_DIR / \"gbdt_outputs.pkl\")"
],
"execution_count": null,
"outputs": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"name": "python",
"version": "3.11"
},
"accelerator": "GPU",
"colab": {
"provenance": [],
"gpuType": "L4"
}
},
"nbformat": 4,
"nbformat_minor": 5
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290# %% [markdown]# # 1 - Features: from 40 years of Landsat to one row per building pixel## This notebook turns the two raw parquet files into two feature tables.## It does **two** things at once:## 1. **Reproduces the organisers' 60 features exactly** (Notebook 3), so every# number we report stays comparable with the published Random-Forest# baseline of 0.618 +- 0.004 macro F1 on Madrid.# 2. **Adds an extended set** on top: proper surface reflectance instead of raw# digital numbers, correct spectral indices, construction-event detection,# per-decade means, trends, and label-free neighbourhood context.## Nothing here touches `y_amsterdam`. Amsterdam's *features* are used (for# per-city statistics), its *labels* are not.## Runs on CPU in a few minutes - no GPU needed. Do this once, locally, and the# GPU notebooks just load the parquet files it writes.
# %%import sysfrom pathlib import Path
# Make src/ importable whether we are local, on Kaggle, or on Colab.for cand in [Path.cwd() / "src", Path.cwd().parent / "src", Path("/kaggle/working/src"), Path("/content/hack4dev/src")]: if cand.exists(): sys.path.insert(0, str(cand)) break
import numpy as npimport pandas as pdimport matplotlib.pyplot as plt
import config as Cimport features as Fimport retrieval as R
pd.set_option("display.width", 200)pd.set_option("display.max_columns", 60)print("platform:", C.PLATFORM)print("looking for raw parquet under:", C.RAW_DIR)
# %% [markdown]# ## 1.1 Find the raw files## Expected: `madrid_train.parquet` (about 3.17 M rows) and# `amsterdam_data.parquet` (about 1.06 M rows). On Kaggle they will be inside# `/kaggle/input/<dataset-name>/`; the search below handles that.
# %%def find_parquet(pattern: str) -> Path: roots = [C.RAW_DIR, C.DATA_DIR, C.PROJECT_ROOT, Path("/kaggle/input")] for root in roots: if not root.exists(): continue hits = sorted(root.rglob(pattern)) if hits: return hits[0] raise FileNotFoundError( f"{pattern} not found. Put the two parquet files in {C.RAW_DIR} " "(local) or attach them as a Kaggle dataset.")
MADRID_PARQUET = find_parquet("madrid_train.parquet")AMS_PARQUET = find_parquet("amsterdam_data.parquet")print("Madrid :", MADRID_PARQUET)print("Amsterdam:", AMS_PARQUET)
# %% [markdown]# ## 1.2 What is actually in the raw file## One row per *(pixel, year)*. Up to three summer observations per year are# stored side by side as `Blue_1/Blue_2/Blue_3`, each with a `qa_valid_N`# cloud flag. Band values are raw Landsat Collection-2 integers:## $$\text{surface reflectance} = \text{DN} \times 2.75\times10^{-5} - 0.2$$
# %%peek = pd.read_parquet(MADRID_PARQUET)print(f"{len(peek):,} rows x {peek.shape[1]} columns")print("\ncolumns:")print(list(peek.columns))print("\nyears:", peek["year"].min(), "-", peek["year"].max(), f"({peek['year'].nunique()} distinct)")print("unique pixels:", f"{peek.groupby(C.PID).ngroups:,}")print("\nfirst row:")print(peek.iloc[0].to_string())
# %%# Reflectance sanity check on one band, and the QA-flag hit rate.dn = peek["Red_1"].dropna()sr = dn * C.SR_SCALE + C.SR_OFFSETprint("Red_1 digital numbers :", dn.quantile([0, .01, .5, .99, 1]).round(0).to_dict())print("Red_1 as reflectance :", sr.quantile([0, .01, .5, .99, 1]).round(3).to_dict())for s in (1, 2, 3): col = f"qa_valid_{s}" if col in peek.columns: print(f"{col}: {peek[col].mean():.1%} valid")del peek
# %% [markdown]# ## 1.3 Build both feature sets## The heavy lifting lives in `src/features.py`. Per city it:## * picks the first QA-valid observation per band per year, drops haze# (`Blue > 15000`);# * records `has_early_data` / `has_late_data` on the *observed* years;# * fills the annual series (linear inside, nearest at the edges);# * pivots to one `(pixels x years)` matrix per band, then computes every# statistic with numpy - a whole city in about a minute.
# %%madrid = F.build_city(MADRID_PARQUET, city_hint="Madrid")
# %%amsterdam = F.build_city(AMS_PARQUET, city_hint="Amsterdam")
# %% [markdown]# ## 1.4 Does this match the organisers' own output?## If `preprocessed_data.pkl` from the organisers' Notebook 3 is around, compare# the 60 official features against it. Their arrays are standardised with# Madrid's `StandardScaler`, so we compare **correlation per feature**, which is# invariant to that. Anything below 0.999 means our pipeline has drifted.
# %%pkl = Nonefor root in [C.DATA_DIR, C.PROJECT_ROOT, Path("/kaggle/input")]: if root.exists(): hits = sorted(root.rglob("preprocessed_data.pkl")) if hits: pkl = hits[0] break
if pkl is None: print("preprocessed_data.pkl not found - skipping the cross-check.")else: import pickle with open(pkl, "rb") as fh: ref = pickle.load(fh) print("reference file:", pkl) ours = madrid.set_index(["px_key", "py_key"]) ref_ids = pd.MultiIndex.from_arrays( [ref["pixel_ids_madrid"][:, 0], ref["pixel_ids_madrid"][:, 1]], names=["px_key", "py_key"]) common = ref_ids.intersection(ours.index) print(f"pixels: ours {len(ours):,}, theirs {len(ref_ids):,}, " f"in common {len(common):,}") ref_df = pd.DataFrame(ref["X_madrid"], index=ref_ids, columns=ref["feature_names"]).loc[common] our_df = ours.loc[common, ref["feature_names"]] corr = {c: float(np.corrcoef(ref_df[c], our_df[c])[0, 1]) for c in ref["feature_names"] if ref_df[c].std() > 0 and our_df[c].std() > 0} bad = {k: v for k, v in corr.items() if v < 0.999} print(f"features compared: {len(corr)} | min correlation: " f"{min(corr.values()):.5f}") print("dead features in their file (zero variance):", [c for c in ref["feature_names"] if ref_df[c].std() == 0]) print("features below 0.999:", bad if bad else "none - pipeline matches") # Labels must agree exactly. y_ref = pd.Series(ref["y_madrid"], index=ref_ids).loc[common] print("label agreement:", f"{(y_ref.to_numpy() == our_df.index.map(ours['age_class']).to_numpy()).mean():.4%}")
# %% [markdown]# ## 1.5 Class balance, and the domain gap## Two facts drive every later design decision:## * the classes are unbalanced, differently in each city;# * the same feature has a different *level* in each city, by much more than# the gap between classes - which is why a Madrid model collapses to ~0.34 on# Amsterdam.
# %%for name, df in [("Madrid", madrid), ("Amsterdam", amsterdam)]: n = len(df) counts = df["age_class"].value_counts().sort_index() print(f"\n{name}: {n:,} labelled pixels") for c in C.CLASS_LABELS[name]: k = int(counts.get(c, 0)) print(f" class {c} ({C.CLASS_LABELS[name][c]:>11}): {k:6,} {k / n:6.1%}")
# %%# How far apart are the two cities, feature by feature?# Expressed in Madrid standard deviations, so it is directly comparable.key = ["sr_brightness_mean", "sr_Red_mean", "sr_NIR_mean", "sr_SWIR1_mean", "sr_NDVI_mean", "sr_NDBI_mean", "sr_UI_mean", "sr_MNDWI_mean", "sr_BSI_mean", "sr_brightness_std", "sr_brightness_late_minus_early", "step_brightness_mag", "step_brightness_njumps", "coverage"]key = [k for k in key if k in madrid.columns and k in amsterdam.columns]gap = pd.DataFrame({ "madrid_mean": [madrid[k].mean() for k in key], "amsterdam_mean": [amsterdam[k].mean() for k in key],}, index=key)gap["madrid_sd"] = [madrid[k].std() for k in key]gap["gap_in_madrid_sd"] = (gap.amsterdam_mean - gap.madrid_mean) / gap.madrid_sdprint(gap.round(3).sort_values("gap_in_madrid_sd").to_string())
# %% [markdown]# A feature whose `gap_in_madrid_sd` is near zero is one a Madrid-trained model# can still read in Amsterdam. A feature at +/-2 is telling the model which# *city* it is looking at, not how old the building is.
# %%# Within-class spread versus between-city gap, for the top offenders.fig, axes = plt.subplots(2, 4, figsize=(18, 7))for ax, k in zip(axes.ravel(), key[:8]): for name, df, col in [("Madrid", madrid, "tab:red"), ("Amsterdam", amsterdam, "tab:blue")]: ax.hist(df[k], bins=60, density=True, alpha=0.45, label=name, color=col) ax.set_title(k, fontsize=9) ax.tick_params(labelsize=7)axes.ravel()[0].legend(fontsize=8)plt.suptitle("The same feature in the two cities", fontweight="bold")plt.tight_layout()plt.show()
# %% [markdown]# ## 1.6 Does the construction-event detector actually work?## A genuine test of the extended features. For classes 3 and 4 the building went# up *during* the satellite record, so `step_brightness_year` should land near# `weighted_mean_year`. For classes 1 and 2 it was already standing in 1984, so# the detector should find nothing meaningful. If that pattern does not show up,# the detector is noise and should be dropped.
# %%for name, df in [("Madrid", madrid), ("Amsterdam", amsterdam)]: print(f"\n{name}") for sig in ("brightness", "SWIR1", "NDVI"): sub = df[df.age_class.isin([3, 4])] err = (sub[f"step_{sig}_year"] - sub["weighted_mean_year"]).abs() r = np.corrcoef(sub[f"step_{sig}_year"], sub["weighted_mean_year"])[0, 1] print(f" step_{sig}_year vs true year (classes 3+4): r={r:+.3f} " f"median |error| = {err.median():.1f} years " f"within 5 y: {(err <= 5).mean():.1%}") print(" mean |step magnitude| by class:", df.groupby("age_class")["step_brightness_mag"].apply( lambda s: round(float(s.abs().mean()), 4)).to_dict())
# %%fig, axes = plt.subplots(1, 2, figsize=(13, 4.5))for ax, (name, df) in zip(axes, [("Madrid", madrid), ("Amsterdam", amsterdam)]): sub = df[df.age_class.isin([3, 4])].sample(min(4000, len(df)), random_state=0) ax.scatter(sub["weighted_mean_year"], sub["step_brightness_year"], s=3, alpha=0.25) lims = [1984, 2024] ax.plot(lims, lims, "r--", lw=1) ax.set(xlabel="true construction year", ylabel="detected brightness step year", title=f"{name}: classes 3 and 4", xlim=lims, ylim=lims)plt.tight_layout()plt.show()
# %% [markdown]# ## 1.7 Neighbourhood context - free information, no labels## Buildings go up a street at a time, so a pixel's neighbours carry real signal# about its era. These features average a few key quantities over the 8 nearest# pixels (within 10 pixel units = 300 m) and also store the *difference* between# the pixel and its surroundings. No labels are involved, so this is available# in Amsterdam at n = 0.
# %%madrid = R.add_neighbourhood_features(madrid)amsterdam = R.add_neighbourhood_features(amsterdam)nbr_cols = [c for c in madrid.columns if c.startswith("nbr_")]print(f"added {len(nbr_cols)} neighbourhood features")print(madrid[["age_class"] + nbr_cols[:6]].groupby("age_class").mean().round(4).to_string())
# %% [markdown]# ## 1.8 Save## One parquet per city. Every later notebook starts from these.
# %%C.PROC_DIR.mkdir(parents=True, exist_ok=True)madrid.to_parquet(C.PROC_DIR / "madrid_features.parquet", index=False)amsterdam.to_parquet(C.PROC_DIR / "amsterdam_features.parquet", index=False)for n, df in [("madrid", madrid), ("amsterdam", amsterdam)]: p = C.PROC_DIR / f"{n}_features.parquet" print(f"{p} {p.stat().st_size / 1e6:.1f} MB {df.shape}")print("\nfeature groups:", f"{len(C.FEATURE_COLS_60)} official,", f"{sum(1 for c in madrid.columns if c.startswith('sr_'))} reflectance-based,", f"{sum(1 for c in madrid.columns if c.startswith('step_'))} change-event,", f"{len(nbr_cols)} neighbourhood")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574# %% [markdown]
# # 3 - LightGBM and CatBoost: the two classical models
#
# The organisers ask for at least two models, chosen on Madrid. These are them.
# They are also the honest yardstick the fine-tuned LLM has to beat, and the
# source of the probabilities we later ensemble with it.
#
# Running order:
#
# 1. **Spatial** cross-validation on Madrid - random folds are dishonest here,
# because neighbouring pixels share a construction era.
# 2. **Adversarial validation** - find the features that only say "this is
# Madrid" and drop them.
# 3. **Per-city normalisation** - the single biggest transfer win, and it needs
# no labels.
# 4. **LightGBM vs CatBoost vs ordinal LightGBM**, all judged on Madrid only.
# 5. **The official few-shot protocol** at n = 5, 25, 50, 100, 200.
#
# Runs on CPU. About 20 minutes on a laptop.
# %%
import sys
from pathlib import Path
for cand in [Path.cwd() / "src", Path.cwd().parent / "src",
Path("/kaggle/working/src"), Path("/content/hack4dev/src")]:
if cand.exists():
sys.path.insert(0, str(cand))
break
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import config as C
import evaluation as E
import gbdt as G
import retrieval as R
RNG = np.random.default_rng(C.RANDOM_SEED)
# Prefer the full feature tables from notebook 1. Fall back to the organisers'
# preprocessed_data.pkl, which carries the official 60 features and the pixel
# coordinates - enough for everything in THIS notebook, and only ~50 MB, so it
# is the right thing to grab first if the raw parquet is hard to get hold of.
import features as F
if (C.PROC_DIR / "madrid_features.parquet").exists():
madrid = pd.read_parquet(C.PROC_DIR / "madrid_features.parquet")
amsterdam = pd.read_parquet(C.PROC_DIR / "amsterdam_features.parquet")
SOURCE = "notebook 1 (official 60 + extended)"
else:
pkl = None
for root in [C.DATA_DIR, C.PROJECT_ROOT, Path("/kaggle/input")]:
if root.exists():
hits = sorted(root.rglob("preprocessed_data.pkl"))
if hits:
pkl = hits[0]
break
if pkl is None:
raise FileNotFoundError(
"Neither data/processed/madrid_features.parquet (run notebook 1) "
"nor preprocessed_data.pkl were found.")
madrid, amsterdam = F.from_official_pkl(pkl)
SOURCE = "organisers' preprocessed_data.pkl (official 60 only)"
print(f"\nfeature source: {SOURCE}")
print(madrid.shape, amsterdam.shape)
# %%
# Feature sets we will compare. Keeping them explicit makes the ablation table
# in the report trivial to produce.
DROP = {"px_key", "py_key", "age_class", "weighted_mean_year", "city"}
ALL_FEATS = [c for c in madrid.columns
if c not in DROP and madrid[c].dtype.kind in "fiu"]
DEAD = [c for c in ALL_FEATS if madrid[c].std() == 0 or amsterdam[c].std() == 0]
ALL_FEATS = [c for c in ALL_FEATS if c not in DEAD]
FEATURE_SETS = {
"official60": [c for c in C.FEATURE_COLS_60 if c in ALL_FEATS],
"reflectance": [c for c in ALL_FEATS if c.startswith("sr_")],
"events": [c for c in ALL_FEATS if c.startswith("step_")],
"neighbourhood": [c for c in ALL_FEATS if c.startswith("nbr_")],
"everything": ALL_FEATS,
}
print("dead (zero variance in at least one city):", DEAD)
for k, v in FEATURE_SETS.items():
print(f" {k:<14} {len(v)} features")
y_mad = madrid["age_class"].to_numpy()
y_ams = amsterdam["age_class"].to_numpy() # opened only for scoring
coords_mad = madrid[C.PID].to_numpy(float)
coords_ams = amsterdam[C.PID].to_numpy(float)
# %% [markdown]
# ## 3.1 An honest validation split
#
# `RepeatedStratifiedKFold` on pixels puts a pixel's own neighbours in the
# training fold. Neighbours share an era, so the model can almost look up the
# answer, and Madrid CV comes out flattering - part of why 0.63 on Madrid turns
# into 0.34 on Amsterdam.
#
# Instead: cut Madrid into geographic blocks and hold out whole blocks. That is
# our stand-in for "a city the model has never seen", and it is the only thing
# we are allowed to choose models on.
# %%
blocks_mad = R.spatial_blocks(coords_mad, n_blocks=25)
print("block sizes:", np.bincount(blocks_mad))
fig, ax = plt.subplots(figsize=(7, 5))
ax.scatter(coords_mad[:, 0], coords_mad[:, 1], c=blocks_mad, s=1, cmap="tab20")
ax.set(title="Madrid split into spatial blocks", xlabel="px_key", ylabel="py_key")
plt.tight_layout()
plt.show()
def block_cv(X, y, blocks, fit_fn, n_folds=5, normalise="robustz", seed=0):
"""Hold out whole geographic blocks, score macro F1 on each."""
uniq = np.unique(blocks)
rng = np.random.default_rng(seed)
order = rng.permutation(uniq)
folds = np.array_split(order, n_folds)
scores, oof = [], np.zeros((len(y), 4))
for f in folds:
te = np.isin(blocks, f)
tr = ~te
nrm = G.CityNormaliser(normalise).fit(X[tr]) if normalise else None
Xtr = nrm.transform(X[tr]) if nrm else X[tr]
# The held-out block plays the part of a new city: it gets normalised
# with its OWN statistics, exactly as Amsterdam will be.
nte = G.CityNormaliser(normalise).fit(X[te]) if normalise else None
Xte = nte.transform(X[te]) if nte else X[te]
m = fit_fn(Xtr, y[tr])
p = m.predict_proba(Xte)
oof[te] = p
scores.append(E.macro_f1(y[te], E.CLASSES[np.argmax(p, 1)]))
return np.array(scores), oof
# %% [markdown]
# ## 3.2 Which features betray the city?
#
# Train a classifier to separate Madrid pixels from Amsterdam pixels. If it
# succeeds easily, the features carry a strong city signature. The most
# important features in *that* task are the ones most likely to mislead the age
# model, and are candidates for removal.
# %%
auc, imp = G.adversarial_validation(madrid[ALL_FEATS], amsterdam[ALL_FEATS], ALL_FEATS)
print(f"city-vs-city AUC: {auc:.4f} (1.0 = the two cities are trivially told apart)")
print(imp.head(20).to_string(index=False))
# %% [markdown]
# The joint model tells us the cities are separable; it does not tell us which
# feature is to blame, because importance is shared among correlated features.
# A single-feature AUC does, and the before/after table is the most convincing
# figure in the write-up: 0.5 means a feature is domain-invariant, 1.0 means it
# is a pure city marker and any Madrid split on it is meaningless in Amsterdam.
# %%
Xm_all = madrid[ALL_FEATS].to_numpy(float)
Xa_all = amsterdam[ALL_FEATS].to_numpy(float)
sf_raw = G.single_feature_domain_auc(Xm_all, Xa_all, ALL_FEATS)
# The rankable mask is a STRUCTURAL decision about the features, so it is
# computed once on Madrid - the design city - and shared. Fitting it per city
# lets a column be ranked in one and z-scored in the other, which puts them on
# different scales and reports a domain AUC of 1.000 for a feature that is
# actually domain-invariant. `n_observed_years` did exactly that.
RANKABLE = G.rankable_mask(Xm_all)
print(f"rank-transformable on Madrid: {RANKABLE.sum()} of {len(ALL_FEATS)}; "
f"too heavily tied to rank: {[ALL_FEATS[j] for j in np.flatnonzero(~RANKABLE)]}")
nm_ = G.CityNormaliser("rank", rankable=RANKABLE).fit(Xm_all).transform(Xm_all)
na_ = G.CityNormaliser("rank", rankable=RANKABLE).fit(Xa_all).transform(Xa_all)
sf_rank = G.single_feature_domain_auc(nm_, na_, ALL_FEATS)
screen = (sf_raw.rename(columns={"domain_auc": "auc_raw"})
.merge(sf_rank.rename(columns={"domain_auc": "auc_after_rank"}), on="feature")
.sort_values("auc_raw", ascending=False))
print("worst offenders, raw vs after per-city rank normalisation:")
print(screen.head(25).round(3).to_string(index=False))
print(f"\nmedian domain AUC: raw {screen.auc_raw.median():.3f} -> "
f"after rank {screen.auc_after_rank.median():.3f}")
print(f"features still above 0.90 after normalisation: "
f"{(screen.auc_after_rank > 0.90).sum()} of {len(screen)}")
screen.to_csv(C.REPORT_DIR / "domain_auc_screen.csv", index=False)
fig, ax = plt.subplots(figsize=(7, 5))
ax.scatter(screen.auc_raw, screen.auc_after_rank, s=8, alpha=0.5)
ax.plot([0.5, 1], [0.5, 1], "k--", lw=1)
ax.set(xlabel="domain AUC, raw", ylabel="domain AUC, after per-city rank",
title="Per-city ranking removes the city signature (points below the line)")
plt.tight_layout()
plt.show()
# %%
# Repeat after per-city normalisation: a good normaliser should make the cities
# harder to tell apart without destroying the age signal.
nm = G.CityNormaliser("robustz").fit(Xm_all).transform(Xm_all)
na = G.CityNormaliser("robustz").fit(Xa_all).transform(Xa_all)
auc_z, imp_z = G.adversarial_validation(nm, na, ALL_FEATS)
auc_r, imp_r = G.adversarial_validation(nm_, na_, ALL_FEATS) # shared mask
print(f"AUC raw {auc:.4f} | robust-z {auc_z:.4f} | rank {auc_r:.4f}")
print("\nstill city-specific after rank normalisation:")
print(imp_r.head(12).to_string(index=False))
# %% [markdown]
# Read the two screens together, because they say different things and the
# difference is the point.
#
# Per-city **rank** normalisation forces every feature's marginal distribution
# to be uniform in both cities, so the *single-feature* domain AUC becomes
# exactly 0.5 by construction. That is not evidence that the domain gap is
# gone. If the *joint* adversarial AUC above is still near 1.0 after ranking,
# the city signature has simply moved into the **correlations between**
# features, where a marginal transform cannot reach it.
#
# That is precisely what CORAL addresses - it matches second-order statistics
# rather than marginals. So the honest conclusion from these two cells is:
# ranking is necessary and cheap, and it is not sufficient. Whether CORAL on
# top actually helps is an empirical question answered in section 3.5, not a
# foregone conclusion: in synthetic testing CORAL slightly *hurt* when the
# shift was close to diagonal.
# %% [markdown]
# ### The drop rule, and why it must be conservative
#
# The tempting rule is "drop the top features by adversarial importance". It is
# wrong. With 59 features the average importance share is 1/59 = 0.017, so any
# threshold near that drops whatever happens to be slightly above average -
# and once normalisation has pushed the joint AUC down to ~0.5, those
# importances are *noise*. In an earlier run this rule dropped three features
# whose single-feature domain AUC was exactly 0.500, i.e. perfectly
# domain-invariant ones.
#
# The principled rule needs two conditions, both of them absolute rather than
# relative: a feature is dropped only if it is **still** strongly
# city-discriminative on its own after normalisation, **and** it is not
# carrying much of the age signal on Madrid. Usually that drops nothing, which
# is the correct answer.
# %%
AUC_CUT = 0.90 # still a city marker after normalisation
IMP_CUT = 0.005 # and contributes little to the Madrid model
X_all = madrid[ALL_FEATS].to_numpy(float)
probe = G.fit_lgbm(G.CityNormaliser("rank").fit_transform(X_all), y_mad,
params=dict(n_estimators=300))
age_imp = pd.DataFrame({
"feature": ALL_FEATS,
"age_importance": probe.feature_importances_ / max(probe.feature_importances_.sum(), 1)
})
drop_tbl = screen.merge(age_imp, on="feature")
leaky = drop_tbl[(drop_tbl.auc_after_rank > AUC_CUT)
& (drop_tbl.age_importance < IMP_CUT)].feature.tolist()
FEATURE_SETS["pruned"] = [c for c in ALL_FEATS if c not in leaky]
print(f"features still above AUC {AUC_CUT} after normalisation: "
f"{(drop_tbl.auc_after_rank > AUC_CUT).sum()}")
print(f"dropping {len(leaky)}: {leaky if leaky else 'nothing - as expected'}")
print(f"pruned set: {len(FEATURE_SETS['pruned'])} features")
print("\nmost city-specific features that we KEPT because they carry age signal:")
print(drop_tbl.sort_values("auc_after_rank", ascending=False)
.head(8).round(4).to_string(index=False))
# %% [markdown]
# ## 3.3 Model and feature-set comparison, on Madrid only
#
# Every row of this table is decided with Madrid block-CV. Amsterdam is not
# consulted. This is the table that justifies the final model choice.
# %%
# The comparison runs 4 models x 3 feature sets x 5 blocked folds = 60 fits.
# At full strength (1200 LightGBM rounds, 2000 CatBoost iterations) that is
# tens of minutes on 76k rows, and it buys nothing: we are reading the
# ORDERING of configurations here, not their final scores. So compare cheaply,
# then refit the winner at full strength in section 3.7.
CHEAP_LGB = dict(n_estimators=400, learning_rate=0.06)
CHEAP_CAT = dict(iterations=500, learning_rate=0.06)
def lgbm_balanced(X, y):
return G.fit_lgbm(X, y, params=CHEAP_LGB,
class_weight=dict(zip(range(4), G.balanced_class_weights(y))))
def lgbm_plain(X, y):
return G.fit_lgbm(X, y, params=CHEAP_LGB)
def cat_balanced(X, y):
return G.fit_catboost(X, y, params=CHEAP_CAT,
class_weights=G.balanced_class_weights(y))
def ordinal_lgbm(X, y):
return G.OrdinalGBDT(params=CHEAP_LGB).fit(X, y)
import time
FEATURE_SETS_TO_TRY = [k for k in ("official60", "everything", "pruned")
if len(FEATURE_SETS.get(k, []))]
# Drop a duplicate: with the pkl-only fallback, "everything" == "official60".
seen, uniq = set(), []
for k in FEATURE_SETS_TO_TRY:
sig = tuple(FEATURE_SETS[k])
if sig not in seen:
seen.add(sig)
uniq.append(k)
else:
print(f" (skipping '{k}' - identical to an earlier set)")
FEATURE_SETS_TO_TRY = uniq
rows = []
for fs_name in FEATURE_SETS_TO_TRY:
X = madrid[FEATURE_SETS[fs_name]].to_numpy(float)
models = [("lgbm", lgbm_balanced), ("lgbm_unweighted", lgbm_plain),
("lgbm_ordinal", ordinal_lgbm)]
if fs_name == FEATURE_SETS_TO_TRY[0]:
# CatBoost costs 35 min per feature set against LightGBM's 10 and came
# in about 0.008 behind on every set, so it runs on one set only. It
# still ships as the second required model.
models.append(("catboost", cat_balanced))
for mdl_name, fn in models:
t0 = time.time()
s, oof = block_cv(X, y_mad, blocks_mad, fn)
rows.append(dict(features=fs_name, model=mdl_name, n_feat=X.shape[1],
macro_f1=s.mean(), std=s.std(ddof=1),
minutes=(time.time() - t0) / 60))
print(f" {fs_name:<12} {mdl_name:<16} {s.mean():.4f} +- "
f"{s.std(ddof=1):.4f} ({rows[-1]['minutes']:.1f} min)")
table = pd.DataFrame(rows).sort_values("macro_f1", ascending=False)
print("\n" + table.round(4).to_string(index=False))
# %% [markdown]
# ### Does per-city normalisation actually help? Decide it on Madrid.
#
# This has to be settled here and not on the Amsterdam score, because the
# Amsterdam score is not ours to choose on. `block_cv` is the right instrument:
# it normalises the held-out block with the block's OWN statistics, exactly as
# Amsterdam will be normalised, so each fold is a miniature transfer problem.
#
# Worth doing carefully, because the intuition ("absolute reflectance does not
# transfer, so normalise it away") is strong and may still be wrong. Per-city
# normalisation also destroys genuine between-city differences in LEVEL, and if
# a city's overall darkness happens to correlate with its class mix, removing
# the level removes a real cue along with the nuisance.
# %%
norm_rows = []
X_best = madrid[FEATURE_SETS[table.iloc[0].features]].to_numpy(float)
for norm in (None, "robustz", "rank"):
s, _ = block_cv(X_best, y_mad, blocks_mad, lgbm_plain, normalise=norm)
norm_rows.append(dict(normalise=str(norm), macro_f1=s.mean(),
std=s.std(ddof=1)))
print(f" normalise={str(norm):8} {s.mean():.4f} +- {s.std(ddof=1):.4f}")
norm_table = pd.DataFrame(norm_rows).sort_values("macro_f1", ascending=False)
print("\n" + norm_table.round(4).to_string(index=False))
BEST_NORM = None if norm_table.iloc[0].normalise == "None" else norm_table.iloc[0].normalise
print(f"\nnormalisation chosen on Madrid: {BEST_NORM}")
print("Whatever Amsterdam says later, this is the choice the rules allow us to")
print("make. If Amsterdam disagrees, that is a finding to report, not a reason")
print("to switch.")
# %% [markdown]
# ## 3.4 The decision rule matters as much as the model
#
# Macro F1 is not maximised by `argmax`. Three cheap post-processing steps,
# each measured separately on Madrid block-CV:
#
# * **class weights** tuned by coordinate ascent on out-of-fold probabilities;
# * **prior correction** towards the class prior EM estimates from *unlabelled*
# target features;
# * **spatial smoothing** of the probabilities over neighbouring pixels.
# %%
BEST_FS = table.iloc[0].features
X_mad = madrid[FEATURE_SETS[BEST_FS]].to_numpy(float)
X_ams = amsterdam[FEATURE_SETS[BEST_FS]].to_numpy(float)
scores, oof = block_cv(X_mad, y_mad, blocks_mad, lgbm_balanced)
print(f"baseline argmax, Madrid block-CV: {E.macro_f1(y_mad, E.CLASSES[np.argmax(oof, 1)]):.4f}")
w = E.tune_class_weights(oof, y_mad)
print("tuned class weights:", np.round(w, 3))
print("after weighting: ",
f"{E.macro_f1(y_mad, E.predict_weighted(oof, w)):.4f}")
for radius in (2.0, 4.0, 8.0):
sm = E.spatial_smooth(oof, coords_mad, radius=radius, alpha=0.5)
print(f"spatial smoothing r={radius:>4}: "
f"{E.macro_f1(y_mad, E.predict_weighted(sm, w)):.4f}")
# %%
print(pd.DataFrame(E.confusion_proportions(y_mad, E.predict_weighted(oof, w)),
index=[f"true {c}" for c in E.CLASSES],
columns=[f"pred {c}" for c in E.CLASSES]).round(3).to_string())
# %% [markdown]
# ## 3.5 The simulated-shift harness - choosing the decision rule on Madrid
#
# This is the most important cell in the notebook, and the thing I would most
# want the team to copy.
#
# None of the adaptation tricks above can be chosen honestly without a way to
# *simulate* Amsterdam from Madrid. So: hold out a spatial block, and build four
# versions of it.
#
# * `clean` - as-is;
# * `label` - resampled to a random Dirichlet class prior (pure label shift);
# * `covariate` - every feature quantile-mapped onto Amsterdam's own marginal
# (pure covariate shift, using `X_amsterdam` only, no labels);
# * `both`.
#
# Then score every candidate decision rule on all four. A rule that helps under
# label shift can lose badly under covariate shift, and without this there is no
# way to tell which regime you are actually in. **Ship only rules that are
# non-negative in the worst case.**
#
# In synthetic testing this harness caught a trap: free SLD-EM prior estimation
# looked excellent under label shift and lost 0.19 macro F1 on average (0.35 at
# worst) under covariate shift, because EM assumes label shift only. The
# macro-F1 plug-in rule driven by the *source* prior was the robust winner.
# %%
# Note the UNWEIGHTED model here. The whole point of this cell is to choose the
# operating point, so the probabilities going into it must be an honest estimate
# of the Madrid posterior. class_weight='balanced' bakes a decision into the fit,
# where no decision rule can undo it.
harness_df, harness_table = E.shift_harness(
lgbm_plain, X_mad, y_mad, blocks_mad, X_ams,
E.DEFAULT_STRATEGIES, n_folds=5, n_rep=4, seed=C.RANDOM_SEED)
harness_table.to_csv(C.REPORT_DIR / "shift_harness.csv")
# %%
# The criterion is the PER-REGIME worst case: for each rule, its deficit
# against argmax in whichever regime it handles worst. An earlier version used
# a column that compared each rule's worst cell anywhere against argmax's worst
# cell anywhere - two different regimes and two different folds - so a rule
# could look safe merely because its bad regime was also argmax's bad regime.
WORST = "delta_vs_argmax_worst_regime"
safe = harness_table[harness_table.get(WORST, 0) >= 0]
print("rules that never lose to plain argmax in ANY regime:")
print(safe.round(4).to_string() if len(safe) else " none - keep plain argmax")
print("\nrules to avoid:")
risky = harness_table[harness_table.get(WORST, 0) < -0.01]
print(risky.round(4).to_string() if len(risky) else " none")
CHOSEN_RULE = (harness_table[WORST].idxmax()
if WORST in harness_table else "argmax")
print(f"\nrule chosen on Madrid alone: {CHOSEN_RULE}")
DECISION = E.DEFAULT_STRATEGIES[CHOSEN_RULE]
# %% [markdown]
# ## 3.6 The official few-shot protocol
#
# `y_amsterdam` enters here and only here: to draw the n labelled pixels per
# class that the rules allow, and to score the remainder. Nothing above was
# tuned on it.
# %%
N_LIST = (5, 25, 50, 100, 200)
N_REPEATS = 12
# Score a fixed random 8,000-pixel sample of Amsterdam rather than all 25,992.
# Full scoring cost 19 s per draw - 32 minutes for one variant and hours for the
# table - and bought nothing: the variants that ignore the labelled sample have
# a standard deviation of 0.0001 across draws. The subsample is fixed, so every
# row of the table is compared on identical pixels. Re-run the winner on all
# 25,992 once, at the end, for the number that goes in the report.
EVAL_SUBSAMPLE = 8000
src_prior = np.array([(y_mad == c).mean() for c in E.CLASSES])
print('Madrid class prior:', np.round(src_prior, 3))
# Cost control. Most variants cache the Madrid-trained model across repeats, so
# 20 draws are cheap. `upweighted shots, retrained` refits from scratch on every
# draw - 100 full fits on 76k rows - so it gets cheap params and fewer draws,
# and its std is correspondingly noisier. That is noted in the table.
REPEATS = {"upweighted shots, retrained": 5}
variants = {
# the two baselines everything must beat
"organisers' prototype (Euclidean, Madrid scaler)": G.mc_prototype_official(),
"pure retrieval k-NN (no source model)": G.mc_knn(),
# zero-shot: does normalisation alone carry us?
"zero-shot, no normalisation": G.mc_zero_shot(normalise=None),
"zero-shot, robust z": G.mc_zero_shot(normalise="robustz"),
"zero-shot, rank": G.mc_zero_shot(normalise="rank"),
"zero-shot, robust z + CORAL": G.mc_zero_shot(normalise="robustz", use_coral=True),
# the prototype metric ablation. On synthetic anisotropic data the pooled
# WITHIN-class Mahalanobis metric beat the organisers' Euclidean prototype
# by +0.11 macro F1 at n=25 - the largest single gain of anything tried.
# The total-covariance version is worse because the target city's total
# covariance is dominated by BETWEEN-class spread, so it shrinks exactly the
# directions that separate the classes. Confirm the ordering here on the
# real features before believing it.
"prototype, robust z + euclidean": G.mc_prototype(metric="euclidean"),
"prototype, rank + euclidean": G.mc_prototype(normalise="rank", metric="euclidean"),
"prototype, robust z + total-cov Mahalanobis": G.mc_prototype(metric="total"),
"prototype, robust z + within-class Mahalanobis": G.mc_prototype(metric="within"),
# using the labelled sample with the source model
"recalibrated (stratification-corrected)": G.mc_recalibrated(normalise="robustz"),
"refit leaf values (structure frozen)": G.mc_refit(),
"upweighted shots, retrained": G.mc_shot_weighted(
normalise="robustz", fit=lambda X, y, **kw: G.fit_lgbm(X, y, params=CHEAP_LGB, **kw)),
"catboost recalibrated": G.mc_recalibrated(fit=G.fit_catboost, normalise="robustz"),
}
protocol = {}
for name, mc in variants.items():
print(f"\n{name}")
reps = REPEATS.get(name, N_REPEATS)
t0 = time.time()
protocol[name] = E.evaluate_protocol(
mc, X_mad, y_mad, X_ams, y_ams, n_list=N_LIST, n_repeats=reps,
decision=lambda p: DECISION(p, src_prior),
eval_subsample=EVAL_SUBSAMPLE)
print(f" ({reps} draws per n, {(time.time() - t0) / 60:.1f} min)")
# %%
summary = pd.DataFrame({name: {n: r["mean"] for n, r in res.items()}
for name, res in protocol.items()}).T
summary["average"] = summary.mean(axis=1)
summary["peak"] = summary[list(N_LIST)].max(axis=1)
print(summary.round(4).sort_values("average", ascending=False).to_string())
# %%
fig, ax = plt.subplots(figsize=(8, 5))
for name, res in protocol.items():
m = [res[n]["mean"] for n in N_LIST]
s = [res[n]["std"] for n in N_LIST]
ax.errorbar(np.log2(N_LIST), m, yerr=s, marker="o", capsize=3, label=name)
ax.axhline(0.618, ls="--", c="k", lw=1, label="published Madrid baseline 0.618")
ax.set(xlabel="log2(labelled Amsterdam pixels per class)", ylabel="macro F1 on Amsterdam",
title="Macro F1 against labelling budget")
ax.legend(fontsize=7)
plt.tight_layout()
plt.show()
# %% [markdown]
# ## 3.7 Save the probabilities for the ensemble
#
# The LLM notebook loads these and blends them with its own predictions.
# %%
import pickle
best_name = summary.sort_values("average", ascending=False).index[0]
print("best classical variant on the protocol:", best_name)
nrm_m = G.CityNormaliser("robustz").fit(X_mad)
nrm_a = G.CityNormaliser("robustz").fit(X_ams)
final = G.fit_lgbm(nrm_m.transform(X_mad), y_mad,
class_weight=dict(zip(range(4), G.balanced_class_weights(y_mad))))
final_cat = G.fit_catboost(nrm_m.transform(X_mad), y_mad,
class_weights=G.balanced_class_weights(y_mad))
out = {
"feature_set": BEST_FS,
"feature_names": FEATURE_SETS[BEST_FS],
"madrid_oof_proba": oof,
"madrid_blocks": blocks_mad,
"class_weights": w,
"amsterdam_proba_lgbm": final.predict_proba(nrm_a.transform(X_ams)),
"amsterdam_proba_catboost": final_cat.predict_proba(nrm_a.transform(X_ams)),
"protocol": {k: {n: dict(mean=r["mean"], std=r["std"],
per_class=r["per_class"].tolist())
for n, r in v.items()} for k, v in protocol.items()},
# Plain lists, not a DataFrame: this file is read on Colab, whose pandas
# 2.x cannot unpickle a pandas 3 DataFrame with string columns
# ("StringDtype.__init__() takes from 1 to 2 positional arguments").
# Rebuild with pd.DataFrame(out["madrid_block_cv_table"]).
"madrid_block_cv_table": {c: table[c].tolist() for c in table.columns},
"adversarial_auc": dict(raw=auc, robustz=auc_z, rank=auc_r),
"dropped_city_specific": leaky,
}
with open(C.PROC_DIR / "gbdt_outputs.pkl", "wb") as fh:
pickle.dump(out, fh)
final.booster_.save_model(str(C.PROC_DIR / "model_lgbm.txt"))
final_cat.save_model(str(C.PROC_DIR / "model_catboost.cbm"))
print("saved:", C.PROC_DIR / "gbdt_outputs.pkl")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171# %% [markdown]# # The two winners, end to end## Building age class (1-4) per 30 m Landsat pixel. Train on Madrid, predict# Amsterdam, scored by macro F1 at n = 5, 25, 50, 100, 200 labelled Amsterdam# pixels per class.## * **Zero-shot LightGBM** - trained on Madrid only, never sees an Amsterdam# label. Best model if you may not use Amsterdam at all: **0.593**.# * **Retrained LightGBM** - refit on Madrid plus the n labelled Amsterdam pixels# per class the protocol gives you, those pixels weighted 30x. Best average# (**0.656**) and best peak (**0.720** at n=200) over the whole protocol.## Everything here runs on a laptop CPU. The heavy lifting is in `winners.py`;# this notebook just calls it. All numbers are on ALL of Amsterdam minus the# labelled pixels of each draw.
# %%import jsonimport sysfrom pathlib import Path
import numpy as npimport pandas as pd
ROOT = Path.cwd() if (Path.cwd() / "winners.py").exists() else Path.cwd().parentsys.path.insert(0, str(ROOT))import winners as W
d = W.load_data()print("Madrid ", d["X_mad"].shape, " Amsterdam", d["X_ams"].shape, " features", len(d["feature_names"]))print("Madrid class shares ", np.round(d["madrid_prior"], 3))print("Amsterdam class shares", np.round([(d["y_ams"] == c).mean() for c in W.CLASSES], 3))
# %% [markdown]# ## 1. Zero-shot LightGBM: Madrid only## 1,200 boosting rounds, class-balanced, raw features (per-city scaling made# things *worse* on Madrid's own spatial cross-validation, so none is applied).# The final step is the decision rule: tau = 0.5 logit adjustment by the Madrid# class prior, then the macro-F1 plug-in rule. It uses no Amsterdam labels, only# the predicted class shares of the batch being labelled.
# %%zs = W.load_zero_shot()P = W.predict(zs, d["X_ams"])lab = W.decide(P, d["madrid_prior"])from sklearn.metrics import confusion_matrix, f1_scoreprint(f"macro F1, all {len(lab):,} Amsterdam pixels: {W.macro_f1(d['y_ams'], lab):.4f}")print(f" same model, plain argmax instead of the rule: " f"{W.macro_f1(d['y_ams'], W.CLASSES[P.argmax(1)]):.4f}")print("per-class F1:", np.round(f1_score(d["y_ams"], lab, labels=W.CLASSES, average=None), 3))cm = confusion_matrix(d["y_ams"], lab, labels=W.CLASSES, normalize="true")print(pd.DataFrame(cm, index=[f"true {c}" for c in W.CLASSES], columns=[f"pred {c}" for c in W.CLASSES]).round(3).to_string())
# %% [markdown]# ## 2. Retrained LightGBM: one draw## The protocol hands you n labelled Amsterdam pixels per class. Here n = 25,# draw 0 - the exact pixels behind the reported number. A fresh LightGBM# (400 rounds) is fit on all 76k Madrid pixels plus these 100, the 100 weighted# 30x. Each city is robust-z scaled with its own median and IQR, Amsterdam's# taken from its unlabelled features. The 100 pixels are removed before scoring.
# %%import timen, rep = 25, 0shot = W.shots_for(d["y_ams"], n, rep)keep = np.setdiff1d(np.arange(len(d["y_ams"])), shot)print(f"{len(shot)} labelled pixels, classes {np.bincount(d['y_ams'][shot])[1:]}; " f"scoring the other {len(keep):,}")t0 = time.time()model, ams_stats = W.train_retrained(d["X_mad"], d["y_mad"], d["X_ams"], d["X_ams"][shot], d["y_ams"][shot])P = W.predict_retrained(model, ams_stats, d["X_ams"][keep])lab = W.decide(P, d["madrid_prior"])print(f"trained in {time.time() - t0:.0f} s; macro F1 {W.macro_f1(d['y_ams'][keep], lab):.4f}")print("per-class F1:", np.round(f1_score(d["y_ams"][keep], lab, labels=W.CLASSES, average=None), 3))
# %% [markdown]# ## 3. The full protocol, as reported## Every n, several draws, scored on all of Amsterdam. These come from# `results/full_score_*.json` (produced by `tools/full_score.py`); to recompute# them run `python winners.py protocol --model retrained --reps 5` (~35 min).# The zero-shot and organisers' rows come from an earlier full-city run# (`results/logs/03_gbdt_models_fullscore_run.log`, 20 draws per n).
# %%N = [5, 25, 50, 100, 200]R = ROOT / "results"rows = {}for key, label in [("upweighted", "retrained LightGBM (5 draws per n)"), ("prototype", "prototype, within-class Mahalanobis (12 draws)")]: s = json.loads((R / f"full_score_{key}.json").read_text())["summary"]["full"] rows[label] = {n: s[str(n)]["mean"] for n in N} | {"std@25": s["25"]["std"]}rows["zero-shot LightGBM (20 draws)"] = dict(zip(N, [0.5928, 0.5925, 0.5922, 0.5918, 0.5903]))rows["organisers' prototype, our re-run on 393 features (20 draws)"] = dict(zip(N, [0.5066, 0.5821, 0.5965, 0.6034, 0.5972]))table = pd.DataFrame(rows).Ttable["average"] = table[N].mean(axis=1)table["peak"] = table[N].max(axis=1)print(table.round(4).to_string())
# %%import matplotlib.pyplot as plt
INK, INK2, MUTED, GRID, SURF = "#0b0b0b", "#52514e", "#898781", "#e1e0d9", "#fcfcfb"series = [ # fixed categorical order: blue, orange, aqua ("upweighted", "Retrained LightGBM", "#2a78d6"), ("prototype", "Prototype (within-class Mahalanobis)", "#eb6834"),]fig, ax = plt.subplots(figsize=(8.5, 5), facecolor=SURF)ax.set_facecolor(SURF)x = np.log2(N)for key, name, col in series: s = json.loads((R / f"full_score_{key}.json").read_text())["summary"]["full"] m = np.array([s[str(n)]["mean"] for n in N]) e = np.array([s[str(n)]["std"] for n in N]) ax.fill_between(x, m - e, m + e, color=col, alpha=0.12, lw=0) ax.plot(x, m, color=col, lw=2, marker="o", ms=8, mec=SURF, mew=2, label=name) dy = 7 if key == "upweighted" else -7 # keep the two end labels apart ax.annotate(name, (x[-1], m[-1]), xytext=(10, dy), textcoords="offset points", va="center", color=INK2, fontsize=9)zs_m = np.array(list(rows["zero-shot LightGBM (20 draws)"].values()))ax.plot(x, zs_m, color="#1baf7a", lw=2, marker="o", ms=8, mec=SURF, mew=2, label="Zero-shot LightGBM (Madrid only)")ax.annotate("Zero-shot LightGBM", (x[-1], zs_m[-1]), xytext=(10, -9), textcoords="offset points", va="center", color=INK2, fontsize=9)base = np.array(list(rows["organisers' prototype, our re-run on 393 features (20 draws)"].values()))ax.plot(x, base, color=MUTED, lw=1.5, ls="--", label="Organisers' prototype (our re-run)")ax.annotate("Organisers' prototype (re-run)", (x[-1], base[-1]), xytext=(10, 8), textcoords="offset points", va="center", color=MUTED, fontsize=9)ax.set_xticks(x, [str(n) for n in N])ax.set_xlabel("Labelled Amsterdam pixels per class (log scale)", color=INK2)ax.set_ylabel("Macro F1, all of Amsterdam", color=INK2)ax.set_title("Macro F1 against labelling budget", loc="left", color=INK, fontsize=12)ax.grid(axis="y", color=GRID, lw=0.8)ax.set_axisbelow(True)for sp in ("top", "right"): ax.spines[sp].set_visible(False)for sp in ("left", "bottom"): ax.spines[sp].set_color(GRID)ax.tick_params(colors=MUTED)ax.set_xlim(x[0] - 0.3, x[-1] + 2.6)ax.legend(loc="lower right", frameon=False, fontsize=8, labelcolor=INK2)plt.tight_layout()fig.savefig(R / "f1_vs_n_full_city.png", dpi=160, facecolor=SURF)plt.show()
# %% [markdown]# ## 4. Using them on your own data## Your features must be the same 393 columns, in `models/meta.json` order# (`W.feature_names()`); `src/features.py` / notebook 1 builds them from the# raw hackathon parquet files.## ```python# # zero-shot: no target labels at all# P = W.predict(W.load_zero_shot(), X_target)# labels = W.decide(P, madrid_prior) # or P.argmax(1) + 1## # retrained: you have n labelled target pixels per class# model, stats = W.train_retrained(X_mad, y_mad, X_target_all, X_shot, y_shot)# labels = W.decide(W.predict_retrained(model, stats, X_rest), madrid_prior)# ```## To compare with your own model on identical draws, use `W.shots_for(y_ams, n,# rep)` for the labelled pixels and score on the rest of Amsterdam - that is the# setup behind every number in the table above.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884{
"variant": "prototype, robust z + within-class Mahalanobis",
"key": "prototype",
"seed": 42,
"n_repeats": 12,
"complete": true,
"minutes": 1.0,
"summary": {
"full": {
"5": {
"mean": 0.5040134544059031,
"std": 0.04021859373385611
},
"25": {
"mean": 0.6361018748678128,
"std": 0.017000180812003537
},
"50": {
"mean": 0.6732725857102647,
"std": 0.01345779825462668
},
"100": {
"mean": 0.7023483182129454,
"std": 0.006656872378539378
},
"200": {
"mean": 0.7140912076382394,
"std": 0.003112708631110763
},
"average": 0.6459654881670331,
"peak": 0.7140912076382394
},
"sub2000": {
"5": {
"mean": 0.502055921409773,
"std": 0.03767702957238527
},
"25": {
"mean": 0.6343220327127315,
"std": 0.020571814234869437
},
"50": {
"mean": 0.6706418571061313,
"std": 0.012976731694065123
},
"100": {
"mean": 0.6935287159302076,
"std": 0.005102727884790501
},
"200": {
"mean": 0.706650164661898,
"std": 0.004865731656175073
},
"average": 0.6414397383641484,
"peak": 0.706650164661898
},
"sub8000": {
"5": {
"mean": 0.5024695988340874,
"std": 0.04055649098254216
},
"25": {
"mean": 0.6334132402958002,
"std": 0.019190847360900567
},
"50": {
"mean": 0.6694949059810421,
"std": 0.013232307229607042
},
"100": {
"mean": 0.6967362989316824,
"std": 0.005985273723055242
},
"200": {
"mean": 0.7085324191993009,
"std": 0.002440110517091129
},
"average": 0.6421292926483826,
"peak": 0.7085324191993009
}
},
"draws": [
{
"n": 5,
"rep": 0,
"n_shots": 20,
"full": 0.5154424688500305,
"full_n_scored": 25972,
"full_per_class": [
0.6124050317598705,
0.5037013196009011,
0.5162102612527542,
0.4294532627865961
],
"sub2000": 0.5257512950480522,
"sub2000_n_scored": 2000,
"sub2000_per_class": [
0.605414273995078,
0.5209742895805142,
0.49513513513513513,
0.48148148148148145
],
"sub8000": 0.5134392880785523,
"sub8000_n_scored": 7995,
"sub8000_per_class": [
0.6041834271922768,
0.5072587532023911,
0.5009256810367627,
0.44138929088277856
],
"seconds": 39.8
},
{
"n": 5,
"rep": 1,
"n_shots": 20,
"full": 0.5326295828708851,
"full_n_scored": 25972,
"full_per_class": [
0.5560405918702874,
0.5418573898891262,
0.40981810212579445,
0.6228022475983325
],
"sub2000": 0.5267168025537948,
"sub2000_n_scored": 1998,
"sub2000_per_class": [
0.5521835677276091,
0.5410691003911343,
0.4094955489614243,
0.6041189931350115
],
"sub8000": 0.5269621001826816,
"sub8000_n_scored": 7989,
"sub8000_per_class": [
0.5532614653754796,
0.5414490861618799,
0.40131578947368424,
0.6118220597196831
],
"seconds": 35.2
},
{
"n": 5,
"rep": 2,
"n_shots": 20,
"full": 0.5137821179640637,
"full_n_scored": 25972,
"full_per_class": [
0.5787100814026299,
0.5056806444949391,
0.5766300425054134,
0.3941077034532722
],
"sub2000": 0.4876887682276281,
"sub2000_n_scored": 1999,
"sub2000_per_class": [
0.5804837364470392,
0.5074821080026025,
0.5479744136460555,
0.3148148148148148
],
"sub8000": 0.5131155290628532,
"sub8000_n_scored": 7994,
"sub8000_per_class": [
0.5848521668691778,
0.5130234091658424,
0.5740197385969592,
0.3805668016194332
],
"seconds": 27.8
},
{
"n": 5,
"rep": 3,
"n_shots": 20,
"full": 0.5246630594618923,
"full_n_scored": 25972,
"full_per_class": [
0.5900469706879125,
0.5285010147868947,
0.5155802984613006,
0.4645239539114615
],
"sub2000": 0.5102206127354992,
"sub2000_n_scored": 1997,
"sub2000_per_class": [
0.5787432117920869,
0.5407788390889052,
0.48370136698212407,
0.43765903307888043
],
"sub8000": 0.5209184933017256,
"sub8000_n_scored": 7990,
"sub8000_per_class": [
0.5779394867866717,
0.5269195189639223,
0.5113871635610766,
0.4674278038952317
],
"seconds": 27.2
},
{
"n": 5,
"rep": 4,
"n_shots": 20,
"full": 0.5268593323268136,
"full_n_scored": 25972,
"full_per_class": [
0.5894369450289997,
0.5089075630252101,
0.4094387755102041,
0.5996540457428406
],
"sub2000": 0.5213589711822051,
"sub2000_n_scored": 1997,
"sub2000_per_class": [
0.5939799331103679,
0.5292439372325249,
0.39710144927536234,
0.5651105651105651
],
"sub8000": 0.520376795826306,
"sub8000_n_scored": 7992,
"sub8000_per_class": [
0.5819983484723369,
0.5062016897357541,
0.40028388928317954,
0.5930232558139535
],
"seconds": 27.6
},
{
"n": 5,
"rep": 5,
"n_shots": 20,
"full": 0.5471240648440912,
"full_n_scored": 25972,
"full_per_class": [
0.6156672995651375,
0.5271687321258341,
0.5570912183712524,
0.48856900931414055
],
"sub2000": 0.5534035506246425,
"sub2000_n_scored": 1998,
"sub2000_per_class": [
0.6097560975609756,
0.5557251908396946,
0.5255198487712666,
0.5226130653266332
],
"sub8000": 0.5484807588173956,
"sub8000_n_scored": 7994,
"sub8000_per_class": [
0.615263261684086,
0.5338706582229898,
0.5482661668228679,
0.4965229485396384
],
"seconds": 27.6
},
{
"n": 5,
"rep": 6,
"n_shots": 20,
"full": 0.46987007052344576,
"full_n_scored": 25972,
"full_per_class": [
0.45782431646305993,
0.47055798405759836,
0.4908051305825993,
0.4602928509905254
],
"sub2000": 0.4803513443960111,
"sub2000_n_scored": 1997,
"sub2000_per_class": [
0.45048543689320386,
0.4915693904020752,
0.4968944099378882,
0.4824561403508772
],
"sub8000": 0.4765089772639029,
"sub8000_n_scored": 7992,
"sub8000_per_class": [
0.457655107336636,
0.4862204724409449,
0.5025614754098361,
0.4595988538681948
],
"seconds": 34.9
},
{
"n": 5,
"rep": 7,
"n_shots": 20,
"full": 0.4917213402701698,
"full_n_scored": 25972,
"full_per_class": [
0.5128599302311831,
0.5368910239674168,
0.5493389370457928,
0.36779546983628614
],
"sub2000": 0.49679984874412175,
"sub2000_n_scored": 1999,
"sub2000_per_class": [
0.5030769230769231,
0.5381526104417671,
0.5437352245862884,
0.4022346368715084
],
"sub8000": 0.4965408085174481,
"sub8000_n_scored": 7994,
"sub8000_per_class": [
0.5141329258976318,
0.5416877210712481,
0.5490423679628554,
0.38130021913805695
],
"seconds": 45.0
},
{
"n": 5,
"rep": 8,
"n_shots": 20,
"full": 0.4951747256979879,
"full_n_scored": 25972,
"full_per_class": [
0.5407663348976329,
0.47215399554463927,
0.4596954314720812,
0.5080831408775982
],
"sub2000": 0.5003407962157336,
"sub2000_n_scored": 1999,
"sub2000_per_class": [
0.5452109845947756,
0.48520710059171596,
0.46132971506105835,
0.5096153846153846
],
"sub8000": 0.49407311500154427,
"sub8000_n_scored": 7994,
"sub8000_per_class": [
0.5343511450381679,
0.4681793027116768,
0.46380697050938335,
0.5099550417469493
],
"seconds": 61.9
},
{
"n": 5,
"rep": 9,
"n_shots": 20,
"full": 0.5105027094316081,
"full_n_scored": 25972,
"full_per_class": [
0.5187257856220404,
0.44122837980938934,
0.5274665702927358,
0.5545901020022668
],
"sub2000": 0.4913459895921074,
"sub2000_n_scored": 1998,
"sub2000_per_class": [
0.4989339019189765,
0.4460856720827179,
0.4902439024390244,
0.5301204819277109
],
"sub8000": 0.5075218336707972,
"sub8000_n_scored": 7995,
"sub8000_per_class": [
0.5158371040723982,
0.4420180722891566,
0.5225171488219504,
0.5497150094996833
],
"seconds": 55.9
},
{
"n": 5,
"rep": 10,
"n_shots": 20,
"full": 0.3943778679352975,
"full_n_scored": 25972,
"full_per_class": [
0.5376032331751889,
0.3708198667634061,
0.298419173890872,
0.3706691979117228
],
"sub2000": 0.40268980129722615,
"sub2000_n_scored": 1999,
"sub2000_per_class": [
0.533256880733945,
0.3829787234042553,
0.3004059539918809,
0.3941176470588235
],
"sub8000": 0.3875502403605131,
"sub8000_n_scored": 7995,
"sub8000_per_class": [
0.530970942593905,
0.3642902475142797,
0.2881413523615359,
0.366798418972332
],
"seconds": 68.2
},
{
"n": 5,
"rep": 11,
"n_shots": 20,
"full": 0.5260141126945512,
"full_n_scored": 25972,
"full_per_class": [
0.5339580866072807,
0.4479087452471483,
0.5311679470971507,
0.5910216718266253
],
"sub2000": 0.5280032763002531,
"sub2000_n_scored": 1999,
"sub2000_per_class": [
0.552,
0.48097165991902835,
0.48787061994609165,
0.5911708253358925
],
"sub8000": 0.5241472459253292,
"sub8000_n_scored": 7995,
"sub8000_per_class": [
0.5301645338208409,
0.45690004046944555,
0.5241334629089731,
0.5853909465020576
],
"seconds": 59.9
},
{
"n": 25,
"rep": 0,
"n_shots": 100,
"full": 0.640875282604727,
"full_n_scored": 25892,
"full_per_class": [
0.6361733563161783,
0.5780404285872086,
0.6706143597335307,
0.6786729857819905
],
"sub2000": 0.6400644522880872,
"sub2000_n_scored": 1992,
"sub2000_per_class": [
0.6412593206296603,
0.5989010989010989,
0.6644370122630993,
0.6556603773584906
],
"sub8000": 0.6375518275829706,
"sub8000_n_scored": 7974,
"sub8000_per_class": [
0.6381789137380192,
0.5861887190300474,
0.6650246305418719,
0.6608150470219436
],
"seconds": 68.6
},
{
"n": 25,
"rep": 1,
"n_shots": 100,
"full": 0.6462353536164829,
"full_n_scored": 25892,
"full_per_class": [
0.6434660898333121,
0.579883027390121,
0.7014319626311356,
0.6601603346113628
],
"sub2000": 0.6543340178062504,
"sub2000_n_scored": 1989,
"sub2000_per_class": [
0.6503791069924179,
0.6036363636363636,
0.6951983298538622,
0.6681222707423581
],
"sub8000": 0.6498008979870565,
"sub8000_n_scored": 7965,
"sub8000_per_class": [
0.645227788084931,
0.5950321987120515,
0.7054322876817138,
0.6535113174695298
],
"seconds": 61.2
},
{
"n": 25,
"rep": 2,
"n_shots": 100,
"full": 0.6049705877379048,
"full_n_scored": 25892,
"full_per_class": [
0.6285833637930134,
0.4990295160966468,
0.678342089900759,
0.6139273811611998
],
"sub2000": 0.5999868198166421,
"sub2000_n_scored": 1997,
"sub2000_per_class": [
0.629553264604811,
0.4970414201183432,
0.6562847608453838,
0.6170678336980306
],
"sub8000": 0.600316966641765,
"sub8000_n_scored": 7970,
"sub8000_per_class": [
0.6238655462184874,
0.49592449592449594,
0.6746053724729991,
0.6068724519510774
],
"seconds": 91.6
},
{
"n": 25,
"rep": 3,
"n_shots": 100,
"full": 0.6219319589295691,
"full_n_scored": 25892,
"full_per_class": [
0.624221844934918,
0.581067472306143,
0.6577428663033024,
0.6246956521739131
],
"sub2000": 0.6287105382480286,
"sub2000_n_scored": 1992,
"sub2000_per_class": [
0.6223880597014926,
0.6126984126984127,
0.6616541353383458,
0.6181015452538632
],
"sub8000": 0.6203997388313052,
"sub8000_n_scored": 7971,
"sub8000_per_class": [
0.6186471663619744,
0.5868215501702383,
0.6595801222428913,
0.6165501165501166
],
"seconds": 64.1
},
{
"n": 25,
"rep": 4,
"n_shots": 100,
"full": 0.6076829582379857,
"full_n_scored": 25892,
"full_per_class": [
0.6168258859784284,
0.5792551230047938,
0.614207650273224,
0.6204431736954967
],
"sub2000": 0.6012618929248565,
"sub2000_n_scored": 1992,
"sub2000_per_class": [
0.6019417475728155,
0.5868983957219251,
0.5987577639751552,
0.6174496644295302
],
"sub8000": 0.5991046254256172,
"sub8000_n_scored": 7962,
"sub8000_per_class": [
0.6048741510187775,
0.58025520483546,
0.6010995723885155,
0.6101895734597157
],
"seconds": 52.0
},
{
"n": 25,
"rep": 5,
"n_shots": 100,
"full": 0.6520096487766935,
"full_n_scored": 25892,
"full_per_class": [
0.6863331737673528,
0.6187339510996985,
0.6821985233798196,
0.6207729468599034
],
"sub2000": 0.6490206537222208,
"sub2000_n_scored": 1992,
"sub2000_per_class": [
0.6833463643471462,
0.6182336182336182,
0.6511111111111111,
0.6433915211970075
],
"sub8000": 0.6512923308153209,
"sub8000_n_scored": 7970,
"sub8000_per_class": [
0.68145861470191,
0.6198288159771754,
0.6781232951445717,
0.6257585974376264
],
"seconds": 23.6
},
{
"n": 25,
"rep": 6,
"n_shots": 100,
"full": 0.6534945461223763,
"full_n_scored": 25892,
"full_per_class": [
0.6531046569854783,
0.5963722664858451,
0.6980535684578273,
0.6664476925603547
],
"sub2000": 0.6631011526610081,
"sub2000_n_scored": 1994,
"sub2000_per_class": [
0.6583541147132169,
0.6167146974063401,
0.7079646017699115,
0.6693711967545639
],
"sub8000": 0.6553572804150688,
"sub8000_n_scored": 7971,
"sub8000_per_class": [
0.6585907530789421,
0.6051486584481508,
0.7012345679012346,
0.6564551422319475
],
"seconds": 24.5
},
{
"n": 25,
"rep": 7,
"n_shots": 100,
"full": 0.6382474330533008,
"full_n_scored": 25892,
"full_per_class": [
0.6490729295426453,
0.594467333725721,
0.6640413056795309,
0.6454081632653061
],
"sub2000": 0.629982052018506,
"sub2000_n_scored": 1990,
"sub2000_per_class": [
0.6415396952686447,
0.6004112405757368,
0.6587112171837709,
0.6192660550458715
],
"sub8000": 0.6365399735546273,
"sub8000_n_scored": 7962,
"sub8000_per_class": [
0.6452642073778664,
0.5956349888296958,
0.6660854402789886,
0.6391752577319587
],
"seconds": 27.0
},
{
"n": 25,
"rep": 8,
"n_shots": 100,
"full": 0.6442699308876451,
"full_n_scored": 25892,
"full_per_class": [
0.7078610603290676,
0.6310214659980844,
0.6169136878814299,
0.6212835093419984
],
"sub2000": 0.6364944946680255,
"sub2000_n_scored": 1995,
"sub2000_per_class": [
0.6973365617433414,
0.6278409090909091,
0.5992865636147443,
0.6215139442231076
],
"sub8000": 0.637549048329748,
"sub8000_n_scored": 7969,
"sub8000_per_class": [
0.6984500686678439,
0.6288603937150081,
0.6132484813422042,
0.6096372495939361
],
"seconds": 25.4
},
{
"n": 25,
"rep": 9,
"n_shots": 100,
"full": 0.6337083777720867,
"full_n_scored": 25892,
"full_per_class": [
0.5752280611589361,
0.5840117593848937,
0.6890940384916289,
0.686499652052888
],
"sub2000": 0.6472006053609829,
"sub2000_n_scored": 1990,
"sub2000_per_class": [
0.5823223570190641,
0.6200997861724875,
0.6804979253112033,
0.7058823529411765
],
"sub8000": 0.6350662432396932,
"sub8000_n_scored": 7970,
"sub8000_per_class": [
0.571667363142499,
0.5942159152146578,
0.6847265221878225,
0.6896551724137931
],
"seconds": 28.9
},
{
"n": 25,
"rep": 10,
"n_shots": 100,
"full": 0.6328845987720971,
"full_n_scored": 25892,
"full_per_class": [
0.6445723588580732,
0.6005224834639542,
0.6450345828708052,
0.641408969895556
],
"sub2000": 0.6126794912079919,
"sub2000_n_scored": 1996,
"sub2000_per_class": [
0.6372093023255814,
0.6146341463414634,
0.6127562642369021,
0.5861182519280206
],
"sub8000": 0.624315516214057,
"sub8000_n_scored": 7978,
"sub8000_per_class": [
0.6394761459307764,
0.6042037762736017,
0.628668171557562,
0.6249139710942877
],
"seconds": 28.2
},
{
"n": 25,
"rep": 11,
"n_shots": 100,
"full": 0.6569118219028849,
"full_n_scored": 25892,
"full_per_class": [
0.6585581043609781,
0.6374685207489325,
0.6773131379650972,
0.6543075245365322
],
"sub2000": 0.6490282218301774,
"sub2000_n_scored": 1986,
"sub2000_per_class": [
0.6488294314381271,
0.6411682892906815,
0.6747787610619469,
0.631336405529954
],
"sub8000": 0.6536644345123719,
"sub8000_n_scored": 7963,
"sub8000_per_class": [
0.6559446254071661,
0.6368577941434332,
0.6795640326975477,
0.6422912858013407
],
"seconds": 28.2
},
{
"n": 50,
"rep": 0,
"n_shots": 200,
"full": 0.6880158094676923,
"full_n_scored": 25792,
"full_per_class": [
0.7072850989450028,
0.660347728547392,
0.6904608443441831,
0.6939695660341912
],
"sub2000": 0.6816534505616696,
"sub2000_n_scored": 1990,
"sub2000_per_class": [
0.6990131578947368,
0.6652631578947369,
0.6652221018418202,
0.6971153846153846
],
"sub8000": 0.6822419934147161,
"sub8000_n_scored": 7937,
"sub8000_per_class": [
0.6990369181380417,
0.6651121076233184,
0.688367129135539,
0.6764518187619656
],
"seconds": 31.1
},
{
"n": 50,
"rep": 1,
"n_shots": 200,
"full": 0.6868617534245177,
"full_n_scored": 25792,
"full_per_class": [
0.7091687041564793,
0.6400612160809935,
0.7025649195475545,
0.6956521739130435
],
"sub2000": 0.6815708796518979,
"sub2000_n_scored": 1989,
"sub2000_per_class": [
0.6987951807228916,
0.653817642698295,
0.6981740064446831,
0.6754966887417219
],
"sub8000": 0.6806289615933406,
"sub8000_n_scored": 7944,
"sub8000_per_class": [
0.6986571879936809,
0.640598690364827,
0.7044791942751126,
0.6787807737397421
],
"seconds": 38.5
},
{
"n": 50,
"rep": 2,
"n_shots": 200,
"full": 0.6761533776528186,
"full_n_scored": 25792,
"full_per_class": [
0.7218229838462011,
0.6528491620111732,
0.7049630774514855,
0.6249782873024144
],
"sub2000": 0.684266315844529,
"sub2000_n_scored": 1982,
"sub2000_per_class": [
0.7095709570957096,
0.6713881019830028,
0.7053469852104665,
0.6507592190889371
],
"sub8000": 0.6776552885349774,
"sub8000_n_scored": 7952,
"sub8000_per_class": [
0.7142005958291956,
0.6607015032211883,
0.7030542986425339,
0.6326647564469914
],
"seconds": 46.1
},
{
"n": 50,
"rep": 3,
"n_shots": 200,
"full": 0.6751606852878018,
"full_n_scored": 25792,
"full_per_class": [
0.6960825234034941,
0.6345070823141248,
0.6862860506180106,
0.6837670848155776
],
"sub2000": 0.6592988990639563,
"sub2000_n_scored": 1984,
"sub2000_per_class": [
0.6766561514195584,
0.6344628695025234,
0.6704161979752531,
0.6556603773584906
],
"sub8000": 0.6707430962063111,
"sub8000_n_scored": 7921,
"sub8000_per_class": [
0.6888888888888889,
0.6409655917852639,
0.6868686868686869,
0.6662492172824045
],
"seconds": 45.4
},
{
"n": 50,
"rep": 4,
"n_shots": 200,
"full": 0.6800384167589169,
"full_n_scored": 25792,
"full_per_class": [
0.6942928039702233,
0.6617647058823529,
0.6892243623112962,
0.6748717948717948
],
"sub2000": 0.6796779663644648,
"sub2000_n_scored": 1986,
"sub2000_per_class": [
0.6995884773662552,
0.6782006920415224,
0.6713947990543735,
0.6695278969957081
],
"sub8000": 0.6780713521299202,
"sub8000_n_scored": 7930,
"sub8000_per_class": [
0.6851628468033776,
0.6670180987524161,
0.6865412445730825,
0.6735632183908046
],
"seconds": 45.5
},
{
"n": 50,
"rep": 5,
"n_shots": 200,
"full": 0.674532717112151,
"full_n_scored": 25792,
"full_per_class": [
0.7144553465408412,
0.6238737478314399,
0.6625876978299886,
0.6972140762463344
],
"sub2000": 0.6655712354880495,
"sub2000_n_scored": 1984,
"sub2000_per_class": [
0.7127746135069162,
0.6275911365260901,
0.6355555555555555,
0.6863636363636364
],
"sub8000": 0.6650162387328394,
"sub8000_n_scored": 7954,
"sub8000_per_class": [
0.7032438926712055,
0.6213176218532405,
0.6550408719346049,
0.6804625684723068
],
"seconds": 46.3
},
{
"n": 50,
"rep": 6,
"n_shots": 200,
"full": 0.6507196917015792,
"full_n_scored": 25792,
"full_per_class": [
0.6819444444444445,
0.6029737036126812,
0.700801282051282,
0.6171593366979091
],
"sub2000": 0.647336654012965,
"sub2000_n_scored": 1989,
"sub2000_per_class": [
0.6671802773497689,
0.6004654771140419,
0.7017913593256059,
0.6199095022624435
],
"sub8000": 0.6466769599736414,
"sub8000_n_scored": 7950,
"sub8000_per_class": [
0.6756352765321375,
0.5990964447063445,
0.7034883720930233,
0.6084877465630604
],
"seconds": 45.0
},
{
"n": 50,
"rep": 7,
"n_shots": 200,
"full": 0.647643882382783,
"full_n_scored": 25792,
"full_per_class": [
0.6565767079990275,
0.5822250864139669,
0.6838989410489452,
0.6678747940691927
],
"sub2000": 0.6529559435392345,
"sub2000_n_scored": 1988,
"sub2000_per_class": [
0.6493083807973963,
0.6031976744186046,
0.675,
0.6843177189409368
],
"sub8000": 0.6467267201387928,
"sub8000_n_scored": 7947,
"sub8000_per_class": [
0.6532052538717898,
0.5883014623172104,
0.6838032061912659,
0.6615969581749049
],
"seconds": 45.8
},
{
"n": 50,
"rep": 8,
"n_shots": 200,
"full": 0.6856794797538986,
"full_n_scored": 25792,
"full_per_class": [
0.7064713064713065,
0.6492123114873577,
0.7034019319613608,
0.6836323690955693
],
"sub2000": 0.6787286673127968,
"sub2000_n_scored": 1978,
"sub2000_per_class": [
0.6871463217461601,
0.6475644699140402,
0.6968325791855203,
0.683371298405467
],
"sub8000": 0.6853339089700422,
"sub8000_n_scored": 7928,
"sub8000_per_class": [
0.6972404208854477,
0.6550797348145494,
0.7109874826147426,
0.6780279975654291
],
"seconds": 43.8
},
{
"n": 50,
"rep": 9,
"n_shots": 200,
"full": 0.665854189312306,
"full_n_scored": 25792,
"full_per_class": [
0.6847287627668033,
0.6492554151624549,
0.6882217090069284,
0.6412108703130375
],
"sub2000": 0.6644871528777947,
"sub2000_n_scored": 1985,
"sub2000_per_class": [
0.6780210867802109,
0.6657101865136298,
0.6902857142857143,
0.6239316239316239
],
"sub8000": 0.6623832546172512,
"sub8000_n_scored": 7943,
"sub8000_per_class": [
0.6786419265692855,
0.6528478731074261,
0.6880317640385706,
0.6300114547537228
],
"seconds": 44.9
},
{
"n": 50,
"rep": 10,
"n_shots": 200,
"full": 0.683092386543684,
"full_n_scored": 25792,
"full_per_class": [
0.7214936143405303,
0.6243424632686377,
0.7066171505739365,
0.6799163179916318
],
"sub2000": 0.6853432711878056,
"sub2000_n_scored": 1982,
"sub2000_per_class": [
0.7136294027565084,
0.6338880484114977,
0.7037457434733257,
0.6901098901098901
],
"sub8000": 0.6775123371964548,
"sub8000_n_scored": 7933,
"sub8000_per_class": [
0.7108052817556259,
0.6208228703882558,
0.707880813143971,
0.6705403834979663
],
"seconds": 45.5
},
{
"n": 50,
"rep": 11,
"n_shots": 200,
"full": 0.6655186391250288,
"full_n_scored": 25792,
"full_per_class": [
0.6858205171539632,
0.612555026231683,
0.6933265839871763,
0.6703724291272929
],
"sub2000": 0.6668118493684136,
"sub2000_n_scored": 1987,
"sub2000_per_class": [
0.6793025018953753,
0.6318147871545929,
0.6818181818181818,
0.6743119266055045
],
"sub8000": 0.6609487602642184,
"sub8000_n_scored": 7947,
"sub8000_per_class": [
0.6763742264288315,
0.6167113836719049,
0.6898290837769684,
0.6608803471791692
],
"seconds": 45.4
},
{
"n": 100,
"rep": 0,
"n_shots": 400,
"full": 0.6956605327583154,
"full_n_scored": 25592,
"full_per_class": [
0.7147677771642432,
0.6651706082053053,
0.6988453858841913,
0.7038583597795223
],
"sub2000": 0.6911555855989419,
"sub2000_n_scored": 1979,
"sub2000_per_class": [
0.7035256410256411,
0.6505847953216374,
0.6877192982456141,
0.7227926078028748
],
"sub8000": 0.6886388554939394,
"sub8000_n_scored": 7885,
"sub8000_per_class": [
0.7018375815056312,
0.6601584085466937,
0.6996547756041427,
0.6929046563192904
],
"seconds": 45.2
},
{
"n": 100,
"rep": 1,
"n_shots": 400,
"full": 0.7031505961965816,
"full_n_scored": 25592,
"full_per_class": [
0.7306061361935645,
0.6826262981869389,
0.7102562030227108,
0.6891137473831124
],
"sub2000": 0.6991707855706939,
"sub2000_n_scored": 1963,
"sub2000_per_class": [
0.7275720164609053,
0.6887218045112782,
0.7006507592190889,
0.6797385620915033
],
"sub8000": 0.6970262639275365,
"sub8000_n_scored": 7873,
"sub8000_per_class": [
0.7239782564928529,
0.6821179574147352,
0.7091442282058118,
0.6728646135967461
],
"seconds": 44.2
},
{
"n": 100,
"rep": 2,
"n_shots": 400,
"full": 0.6995821570081839,
"full_n_scored": 25592,
"full_per_class": [
0.731018024241663,
0.6614014251781473,
0.6998252026060703,
0.7060839760068551
],
"sub2000": 0.6893029935349051,
"sub2000_n_scored": 1971,
"sub2000_per_class": [
0.7252931323283082,
0.6636904761904762,
0.6915688367129136,
0.6766595289079229
],
"sub8000": 0.6921564711310434,
"sub8000_n_scored": 7873,
"sub8000_per_class": [
0.725422348870344,
0.6627643504531722,
0.6942322886489334,
0.6862068965517242
],
"seconds": 44.7
},
{
"n": 100,
"rep": 3,
"n_shots": 400,
"full": 0.7156568141977783,
"full_n_scored": 25592,
"full_per_class": [
0.7436728587457923,
0.6855245075584059,
0.7246083880747852,
0.7088215024121296
],
"sub2000": 0.7004211598844011,
"sub2000_n_scored": 1963,
"sub2000_per_class": [
0.7213930348258707,
0.6734842951059167,
0.7026406429391504,
0.7041666666666667
],
"sub8000": 0.7069554378068514,
"sub8000_n_scored": 7869,
"sub8000_per_class": [
0.7330097087378641,
0.6855059252506837,
0.7150055991041433,
0.694300518134715
],
"seconds": 44.9
},
{
"n": 100,
"rep": 4,
"n_shots": 400,
"full": 0.7102531753981858,
"full_n_scored": 25592,
"full_per_class": [
0.7277865404837014,
0.6795448237579794,
0.7163207163207164,
0.7173606210303458
],
"sub2000": 0.7030202908862202,
"sub2000_n_scored": 1977,
"sub2000_per_class": [
0.7226596675415573,
0.6847977684797768,
0.6956521739130435,
0.7089715536105032
],
"sub8000": 0.7039681905253619,
"sub8000_n_scored": 7873,
"sub8000_per_class": [
0.7210739399105051,
0.6818181818181818,
0.7183060841597427,
0.6946745562130178
],
"seconds": 44.4
},
{
"n": 100,
"rep": 5,
"n_shots": 400,
"full": 0.6970234156619769,
"full_n_scored": 25592,
"full_per_class": [
0.7195786414820197,
0.6650714911000876,
0.7104996623902768,
0.6929438676755235
],
"sub2000": 0.688869420562793,
"sub2000_n_scored": 1975,
"sub2000_per_class": [
0.7059748427672956,
0.6607142857142857,
0.7029478458049887,
0.6858407079646017
],
"sub8000": 0.6916788231103608,
"sub8000_n_scored": 7893,
"sub8000_per_class": [
0.7110162916989915,
0.6641665104069004,
0.7119777158774373,
0.6795547744581136
],
"seconds": 43.7
},
{
"n": 100,
"rep": 6,
"n_shots": 400,
"full": 0.7015577779706541,
"full_n_scored": 25592,
"full_per_class": [
0.7212658227848101,
0.6631010021393987,
0.7084815887463798,
0.7133826982120282
],
"sub2000": 0.6977101464965301,
"sub2000_n_scored": 1962,
"sub2000_per_class": [
0.7040816326530612,
0.6741731175228712,
0.7034949267192785,
0.7090909090909091
],
"sub8000": 0.6957511266536937,
"sub8000_n_scored": 7872,
"sub8000_per_class": [
0.7123793882159721,
0.6647574727044926,
0.7050754458161865,
0.7007921998781231
],
"seconds": 45.0
},
{
"n": 100,
"rep": 7,
"n_shots": 400,
"full": 0.6993930933138065,
"full_n_scored": 25592,
"full_per_class": [
0.7156596794081381,
0.6734982732265187,
0.7083440971325239,
0.700070323488045
],
"sub2000": 0.6927554786238601,
"sub2000_n_scored": 1977,
"sub2000_per_class": [
0.7064516129032258,
0.6714801444043321,
0.6972477064220184,
0.6958424507658644
],
"sub8000": 0.6971786214673333,
"sub8000_n_scored": 7893,
"sub8000_per_class": [
0.7149375123983337,
0.6808510638297872,
0.7087461081234079,
0.684179801517805
],
"seconds": 43.7
},
{
"n": 100,
"rep": 8,
"n_shots": 400,
"full": 0.6991747950902661,
"full_n_scored": 25592,
"full_per_class": [
0.7125256673511293,
0.667913196215083,
0.7251976848455205,
0.6910626319493315
],
"sub2000": 0.6887564297762729,
"sub2000_n_scored": 1970,
"sub2000_per_class": [
0.6941870261162595,
0.661849710982659,
0.7048458149779736,
0.6941431670281996
],
"sub8000": 0.6941301594269301,
"sub8000_n_scored": 7885,
"sub8000_per_class": [
0.7019429516329062,
0.667871340802313,
0.7200866269626421,
0.6866197183098591
],
"seconds": 44.4
},
{
"n": 100,
"rep": 9,
"n_shots": 400,
"full": 0.6925297553913796,
"full_n_scored": 25592,
"full_per_class": [
0.7182587666263603,
0.6724587315377932,
0.7003060633633882,
0.6790954600379768
],
"sub2000": 0.6901187483592387,
"sub2000_n_scored": 1972,
"sub2000_per_class": [
0.7092709270927092,
0.6815415821501014,
0.6957494407158836,
0.6739130434782609
],
"sub8000": 0.6894561113837702,
"sub8000_n_scored": 7871,
"sub8000_per_class": [
0.7115761935905821,
0.6777546777546778,
0.6991247264770241,
0.6693688477127968
],
"seconds": 44.8
},
{
"n": 100,
"rep": 10,
"n_shots": 400,
"full": 0.7087579739936903,
"full_n_scored": 25592,
"full_per_class": [
0.731912721704734,
0.6695611358835954,
0.7198021381841392,
0.7137559002022926
],
"sub2000": 0.6897127029583479,
"sub2000_n_scored": 1965,
"sub2000_per_class": [
0.7061812023708721,
0.6558105107327905,
0.7019438444924406,
0.6949152542372882
],
"sub8000": 0.704166307882562,
"sub8000_n_scored": 7871,
"sub8000_per_class": [
0.7248101785347835,
0.6714232069095005,
0.7198093220338984,
0.7006225240520656
],
"seconds": 43.5
},
{
"n": 100,
"rep": 11,
"n_shots": 400,
"full": 0.7054397315745257,
"full_n_scored": 25592,
"full_per_class": [
0.7395912187736563,
0.6750114836931557,
0.7118727050183599,
0.6952835188129306
],
"sub2000": 0.6913508489102866,
"sub2000_n_scored": 1975,
"sub2000_per_class": [
0.7257663628831814,
0.6647230320699709,
0.6951754385964912,
0.6797385620915033
],
"sub8000": 0.6997292183708061,
"sub8000_n_scored": 7865,
"sub8000_per_class": [
0.7301587301587301,
0.6732782369146005,
0.7130434782608696,
0.6824364281490243
],
"seconds": 45.0
},
{
"n": 200,
"rep": 0,
"n_shots": 800,
"full": 0.7126308732675979,
"full_n_scored": 25192,
"full_per_class": [
0.7305864739959643,
0.6934458444110507,
0.7190252737301391,
0.7074659009332376
],
"sub2000": 0.7085476058479627,
"sub2000_n_scored": 1944,
"sub2000_per_class": [
0.7174103237095363,
0.6960926193921853,
0.7142857142857143,
0.7064017660044151
],
"sub8000": 0.7088247983564959,
"sub8000_n_scored": 7767,
"sub8000_per_class": [
0.7246682115020012,
0.7003131331736968,
0.7191500953418687,
0.6911677534084173
],
"seconds": 48.2
},
{
"n": 200,
"rep": 1,
"n_shots": 800,
"full": 0.712263430940032,
"full_n_scored": 25192,
"full_per_class": [
0.7431735726561008,
0.6780061422159225,
0.7214309373964889,
0.7064430714916152
],
"sub2000": 0.7039979119751034,
"sub2000_n_scored": 1948,
"sub2000_per_class": [
0.7225042301184433,
0.6731054977711739,
0.7155361050328227,
0.7048458149779736
],
"sub8000": 0.7097915636104388,
"sub8000_n_scored": 7763,
"sub8000_per_class": [
0.7340885684860968,
0.6783625730994152,
0.730349344978166,
0.6963657678780774
],
"seconds": 41.2
},
{
"n": 200,
"rep": 2,
"n_shots": 800,
"full": 0.710147876753136,
"full_n_scored": 25192,
"full_per_class": [
0.7323607427055703,
0.6860651974288338,
0.7245699014531485,
0.6975956654249915
],
"sub2000": 0.7071637332744507,
"sub2000_n_scored": 1935,
"sub2000_per_class": [
0.7272727272727273,
0.6814486326681448,
0.7228381374722838,
0.6970954356846473
],
"sub8000": 0.7027890498369546,
"sub8000_n_scored": 7774,
"sub8000_per_class": [
0.7264975484971221,
0.6817429674572532,
0.7204832509610104,
0.6824324324324325
],
"seconds": 41.1
},
{
"n": 200,
"rep": 3,
"n_shots": 800,
"full": 0.7139186438938164,
"full_n_scored": 25192,
"full_per_class": [
0.7215813350615684,
0.6846558426709353,
0.7344632768361582,
0.7149741210066036
],
"sub2000": 0.7086510412647167,
"sub2000_n_scored": 1951,
"sub2000_per_class": [
0.7182978723404255,
0.6808199121522694,
0.724669603524229,
0.7108167770419426
],
"sub8000": 0.707901303466429,
"sub8000_n_scored": 7752,
"sub8000_per_class": [
0.7096234309623431,
0.6837763519706691,
0.7345454545454545,
0.7036599763872491
],
"seconds": 41.4
},
{
"n": 200,
"rep": 4,
"n_shots": 800,
"full": 0.718636301061127,
"full_n_scored": 25192,
"full_per_class": [
0.7340804890473764,
0.6870220094576449,
0.7302932137220699,
0.7231494920174165
],
"sub2000": 0.7081455493129629,
"sub2000_n_scored": 1929,
"sub2000_per_class": [
0.7281964436917866,
0.6933333333333334,
0.7138047138047138,
0.6972477064220184
],
"sub8000": 0.7116828386105452,
"sub8000_n_scored": 7770,
"sub8000_per_class": [
0.7318275154004107,
0.6885368126747438,
0.7296703296703296,
0.6966966966966966
],
"seconds": 41.4
},
{
"n": 200,
"rep": 5,
"n_shots": 800,
"full": 0.7159053357442459,
"full_n_scored": 25192,
"full_per_class": [
0.7451309170643622,
0.6943847627896174,
0.7167630057803468,
0.7073426573426573
],
"sub2000": 0.709536245263495,
"sub2000_n_scored": 1938,
"sub2000_per_class": [
0.7291666666666666,
0.6964809384164223,
0.7096774193548387,
0.702819956616052
],
"sub8000": 0.7095375989140849,
"sub8000_n_scored": 7753,
"sub8000_per_class": [
0.7353493222106361,
0.690511489992587,
0.717096148517595,
0.6951934349355217
],
"seconds": 40.9
},
{
"n": 200,
"rep": 6,
"n_shots": 800,
"full": 0.720830638139817,
"full_n_scored": 25192,
"full_per_class": [
0.758879694462126,
0.6939720004628023,
0.7177783456853224,
0.7126925119490175
],
"sub2000": 0.700926963819813,
"sub2000_n_scored": 1947,
"sub2000_per_class": [
0.7421808960270498,
0.6870451237263464,
0.6945701357466063,
0.6799116997792495
],
"sub8000": 0.7113216854149917,
"sub8000_n_scored": 7771,
"sub8000_per_class": [
0.7491789819376026,
0.689706154130475,
0.7140039447731755,
0.6923976608187135
],
"seconds": 41.2
},
{
"n": 200,
"rep": 7,
"n_shots": 800,
"full": 0.7118383061544808,
"full_n_scored": 25192,
"full_per_class": [
0.7403766358123205,
0.6793680847287142,
0.7180671229487919,
0.709541381128097
],
"sub2000": 0.7099530096487899,
"sub2000_n_scored": 1922,
"sub2000_per_class": [
0.7345890410958904,
0.6852409638554217,
0.7166853303471444,
0.7032967032967034
],
"sub8000": 0.7065874945196432,
"sub8000_n_scored": 7739,
"sub8000_per_class": [
0.7332228666114333,
0.6789724072312083,
0.7178930219929406,
0.6962616822429907
],
"seconds": 43.7
},
{
"n": 200,
"rep": 8,
"n_shots": 800,
"full": 0.7149652917652629,
"full_n_scored": 25192,
"full_per_class": [
0.7509486465975209,
0.6841824328331653,
0.7204743864272772,
0.7042557012030886
],
"sub2000": 0.7057496330827919,
"sub2000_n_scored": 1933,
"sub2000_per_class": [
0.7422334172963896,
0.6833333333333333,
0.7142857142857143,
0.6831460674157304
],
"sub8000": 0.7079957561410746,
"sub8000_n_scored": 7764,
"sub8000_per_class": [
0.7466340269277846,
0.6825667234525837,
0.7163774403470716,
0.686404833836858
],
"seconds": 42.9
},
{
"n": 200,
"rep": 9,
"n_shots": 800,
"full": 0.7125345871281019,
"full_n_scored": 25192,
"full_per_class": [
0.7208996448770222,
0.6787582839204743,
0.7336075489958868,
0.7168728707190246
],
"sub2000": 0.6945571524997171,
"sub2000_n_scored": 1947,
"sub2000_per_class": [
0.7053649956024626,
0.6686046511627907,
0.7155172413793104,
0.6887417218543046
],
"sub8000": 0.7067249502339726,
"sub8000_n_scored": 7757,
"sub8000_per_class": [
0.7136770345121431,
0.6779033154287831,
0.7330655957161981,
0.7022538552787663
],
"seconds": 42.9
},
{
"n": 200,
"rep": 10,
"n_shots": 800,
"full": 0.7141411828291568,
"full_n_scored": 25192,
"full_per_class": [
0.7355947652841982,
0.6862779228314476,
0.7277310924369748,
0.7069609507640068
],
"sub2000": 0.7104950356445686,
"sub2000_n_scored": 1938,
"sub2000_per_class": [
0.729636048526863,
0.6873614190687362,
0.713963963963964,
0.7110187110187111
],
"sub8000": 0.7106255772139292,
"sub8000_n_scored": 7736,
"sub8000_per_class": [
0.7296554639611076,
0.6921790822961174,
0.725752508361204,
0.6949152542372882
],
"seconds": 28.6
},
{
"n": 200,
"rep": 11,
"n_shots": 800,
"full": 0.7112820239820997,
"full_n_scored": 25192,
"full_per_class": [
0.7345115556418722,
0.683256600034967,
0.7239469709682833,
0.7034129692832765
],
"sub2000": 0.7120780943084037,
"sub2000_n_scored": 1947,
"sub2000_per_class": [
0.7297527706734868,
0.6962305986696231,
0.7239819004524887,
0.6983471074380165
],
"sub8000": 0.7086064140730504,
"sub8000_n_scored": 7763,
"sub8000_per_class": [
0.7280334728033473,
0.687037037037037,
0.7248471372984991,
0.6945080091533181
],
"seconds": 32.9
}
]
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834{
"variant": "upweighted shots, retrained",
"key": "upweighted",
"seed": 42,
"n_repeats": 5,
"complete": true,
"minutes": 35.2,
"summary": {
"full": {
"5": {
"mean": 0.5657712701607671,
"std": 0.010763078238031729
},
"25": {
"mean": 0.6283681875535173,
"std": 0.011971948185350032
},
"50": {
"mean": 0.66966152039057,
"std": 0.008673459655728825
},
"100": {
"mean": 0.6973059347465853,
"std": 0.003834880518714044
},
"200": {
"mean": 0.7203877077810819,
"std": 0.0060460647590979385
},
"average": 0.6562989241265044,
"peak": 0.7203877077810819
},
"sub2000": {
"5": {
"mean": 0.5659755325794811,
"std": 0.011462273225451226
},
"25": {
"mean": 0.6291022015454792,
"std": 0.014826792915094249
},
"50": {
"mean": 0.6689620638167193,
"std": 0.008095887938584241
},
"100": {
"mean": 0.6961219395643318,
"std": 0.006245123984700372
},
"200": {
"mean": 0.7230323369848072,
"std": 0.011642660688516835
},
"average": 0.6566388148981637,
"peak": 0.7230323369848072
},
"sub8000": {
"5": {
"mean": 0.5609268681598608,
"std": 0.01047234508091067
},
"25": {
"mean": 0.6259357981888064,
"std": 0.01260466365218293
},
"50": {
"mean": 0.6663725210444166,
"std": 0.010295292878052831
},
"100": {
"mean": 0.6948528587219436,
"std": 0.0029177058143673947
},
"200": {
"mean": 0.7181758724416476,
"std": 0.005218893626224835
},
"average": 0.6532527837113349,
"peak": 0.7181758724416476
}
},
"draws": [
{
"n": 5,
"rep": 0,
"n_shots": 20,
"full": 0.5658086665322979,
"full_n_scored": 25972,
"full_per_class": [
0.5928475235672602,
0.5579149456047472,
0.5534818067754078,
0.5589903901817761
],
"sub2000": 0.57501534222845,
"sub2000_n_scored": 2000,
"sub2000_per_class": [
0.5899705014749262,
0.5680297397769517,
0.5660377358490566,
0.5760233918128655
],
"sub8000": 0.56315166517848,
"sub8000_n_scored": 7995,
"sub8000_per_class": [
0.5910636231180184,
0.5671808214086601,
0.5535301668806162,
0.5408320493066255
],
"seconds": 74.1
},
{
"n": 5,
"rep": 1,
"n_shots": 20,
"full": 0.5755307163274996,
"full_n_scored": 25972,
"full_per_class": [
0.5934548649242258,
0.5673783486663195,
0.5781237460877939,
0.563165905631659
],
"sub2000": 0.5755930780881062,
"sub2000_n_scored": 1998,
"sub2000_per_class": [
0.5883495145631068,
0.5701624815361891,
0.564755838641189,
0.5791044776119403
],
"sub8000": 0.5699378066813413,
"sub8000_n_scored": 7989,
"sub8000_per_class": [
0.580845474086458,
0.5711648513937604,
0.5795811518324607,
0.548159749412686
],
"seconds": 51.6
},
{
"n": 5,
"rep": 2,
"n_shots": 20,
"full": 0.5476248161842202,
"full_n_scored": 25972,
"full_per_class": [
0.5695845697329377,
0.5309744985503816,
0.5586407614253127,
0.5312994350282486
],
"sub2000": 0.548263502745409,
"sub2000_n_scored": 1999,
"sub2000_per_class": [
0.5621301775147929,
0.5330330330330331,
0.5615141955835962,
0.536376604850214
],
"sub8000": 0.5430038132164742,
"sub8000_n_scored": 7994,
"sub8000_per_class": [
0.5634824667472793,
0.5402450518378887,
0.5556984821198868,
0.5125892521608418
],
"seconds": 50.4
},
{
"n": 5,
"rep": 3,
"n_shots": 20,
"full": 0.5685362129160143,
"full_n_scored": 25972,
"full_per_class": [
0.6126534190531853,
0.5615434234445552,
0.5600506689889954,
0.5398973401773215
],
"sub2000": 0.5611926106997139,
"sub2000_n_scored": 1997,
"sub2000_per_class": [
0.5916585838991271,
0.5439519158527423,
0.5581395348837209,
0.5510204081632653
],
"sub8000": 0.5621566106140353,
"sub8000_n_scored": 7990,
"sub8000_per_class": [
0.6044086276368807,
0.5598796766309456,
0.5587170201758924,
0.5256211180124224
],
"seconds": 116.9
},
{
"n": 5,
"rep": 4,
"n_shots": 20,
"full": 0.5713559388438034,
"full_n_scored": 25972,
"full_per_class": [
0.5914583802446897,
0.5779437560119957,
0.5587102983638114,
0.557311320754717
],
"sub2000": 0.569813129135726,
"sub2000_n_scored": 1997,
"sub2000_per_class": [
0.5804540967423495,
0.5753823743627094,
0.5570971184631803,
0.5663189269746647
],
"sub8000": 0.5663844451089731,
"sub8000_n_scored": 7992,
"sub8000_per_class": [
0.5850804485616772,
0.5869762379829494,
0.5545073375262054,
0.5389737563650607
],
"seconds": 179.8
},
{
"n": 25,
"rep": 0,
"n_shots": 100,
"full": 0.6302737351779462,
"full_n_scored": 25892,
"full_per_class": [
0.6702978952323314,
0.5876472688325598,
0.6476267748478702,
0.6155230017990234
],
"sub2000": 0.6323146358738826,
"sub2000_n_scored": 1992,
"sub2000_per_class": [
0.6725820763087844,
0.5865457294028723,
0.6477644492911668,
0.6223662884927067
],
"sub8000": 0.6322177365617214,
"sub8000_n_scored": 7974,
"sub8000_per_class": [
0.673232654847888,
0.5971671388101983,
0.6550079491255962,
0.6034632034632035
],
"seconds": 161.0
},
{
"n": 25,
"rep": 1,
"n_shots": 100,
"full": 0.6184984160990994,
"full_n_scored": 25892,
"full_per_class": [
0.675191466083151,
0.5813030469560969,
0.6292063492063492,
0.5882928021508005
],
"sub2000": 0.6252231849389315,
"sub2000_n_scored": 1989,
"sub2000_per_class": [
0.6745240253853128,
0.594383775351014,
0.6378947368421053,
0.5940902021772939
],
"sub8000": 0.6161232340806198,
"sub8000_n_scored": 7965,
"sub8000_per_class": [
0.6718472468916519,
0.5854517012123582,
0.6351842241826674,
0.5720097640358015
],
"seconds": 252.8
},
{
"n": 25,
"rep": 2,
"n_shots": 100,
"full": 0.6265213468503279,
"full_n_scored": 25892,
"full_per_class": [
0.6902949267481288,
0.594574780058651,
0.6242608548741342,
0.5969548257203976
],
"sub2000": 0.6143179742821969,
"sub2000_n_scored": 1997,
"sub2000_per_class": [
0.6788990825688074,
0.5727773406766326,
0.6078212290502794,
0.5977742448330684
],
"sub8000": 0.6196619541280792,
"sub8000_n_scored": 7970,
"sub8000_per_class": [
0.6834233485666805,
0.5927513639906469,
0.6243415580815082,
0.5781315458734814
],
"seconds": 46.6
},
{
"n": 25,
"rep": 3,
"n_shots": 100,
"full": 0.6477776392710577,
"full_n_scored": 25892,
"full_per_class": [
0.7180120812740253,
0.6435045317220544,
0.6294688659142925,
0.6001250781738586
],
"sub2000": 0.652890475221296,
"sub2000_n_scored": 1992,
"sub2000_per_class": [
0.7223230490018149,
0.656298600311042,
0.6291666666666667,
0.6037735849056604
],
"sub8000": 0.6451965860388205,
"sub8000_n_scored": 7971,
"sub8000_per_class": [
0.7131991051454138,
0.6509652509652509,
0.6342592592592593,
0.5823627287853578
],
"seconds": 46.6
},
{
"n": 25,
"rep": 4,
"n_shots": 100,
"full": 0.6187698003691553,
"full_n_scored": 25892,
"full_per_class": [
0.642973221225182,
0.596907753778447,
0.6185633058380716,
0.6166349206349206
],
"sub2000": 0.6207647374110891,
"sub2000_n_scored": 1992,
"sub2000_per_class": [
0.6409048067860509,
0.6066420664206642,
0.6288770053475936,
0.6066350710900474
],
"sub8000": 0.6164794801347909,
"sub8000_n_scored": 7962,
"sub8000_per_class": [
0.6382488479262672,
0.5981928821685414,
0.6276987888362296,
0.6017774016081253
],
"seconds": 49.6
},
{
"n": 50,
"rep": 0,
"n_shots": 200,
"full": 0.6657850238597829,
"full_n_scored": 25792,
"full_per_class": [
0.7333892852147154,
0.6585910854992356,
0.6566231268531132,
0.6145365978720677
],
"sub2000": 0.6693202889467833,
"sub2000_n_scored": 1990,
"sub2000_per_class": [
0.7379182156133829,
0.6661665416354089,
0.6489925768822906,
0.6242038216560509
],
"sub8000": 0.6587402393105977,
"sub8000_n_scored": 7937,
"sub8000_per_class": [
0.7293421352151149,
0.6570193572636722,
0.6536842105263158,
0.5949152542372881
],
"seconds": 50.7
},
{
"n": 50,
"rep": 1,
"n_shots": 200,
"full": 0.6740992113506705,
"full_n_scored": 25792,
"full_per_class": [
0.7241239892183289,
0.6627476338839574,
0.6629086809470124,
0.6466165413533834
],
"sub2000": 0.6748175232223903,
"sub2000_n_scored": 1989,
"sub2000_per_class": [
0.7133872416891285,
0.6736370425690814,
0.6582010582010582,
0.6540447504302926
],
"sub8000": 0.670791186902067,
"sub8000_n_scored": 7944,
"sub8000_per_class": [
0.7223919685726757,
0.6660384470410856,
0.6708727655099895,
0.6238615664845173
],
"seconds": 75.8
},
{
"n": 50,
"rep": 2,
"n_shots": 200,
"full": 0.6785650147371174,
"full_n_scored": 25792,
"full_per_class": [
0.7314858096828046,
0.6651240061706419,
0.6872041850037366,
0.6304460580912863
],
"sub2000": 0.6779123990533649,
"sub2000_n_scored": 1982,
"sub2000_per_class": [
0.7371225577264654,
0.6772486772486772,
0.6674082313681868,
0.6298701298701299
],
"sub8000": 0.6807228928512371,
"sub8000_n_scored": 7952,
"sub8000_per_class": [
0.7365916955017301,
0.6726201786053582,
0.6998098342841619,
0.6138698630136986
],
"seconds": 79.3
},
{
"n": 50,
"rep": 3,
"n_shots": 200,
"full": 0.6733592680779585,
"full_n_scored": 25792,
"full_per_class": [
0.7138979010792558,
0.6354566385264774,
0.6879363533041079,
0.6561461794019934
],
"sub2000": 0.6654221219213152,
"sub2000_n_scored": 1984,
"sub2000_per_class": [
0.7006145741878841,
0.6328538985616957,
0.670926517571885,
0.6572934973637962
],
"sub8000": 0.6670591031920785,
"sub8000_n_scored": 7921,
"sub8000_per_class": [
0.7130285468984761,
0.634025528672128,
0.6862326574172892,
0.6349496797804208
],
"seconds": 75.8
},
{
"n": 50,
"rep": 4,
"n_shots": 200,
"full": 0.6564990839273208,
"full_n_scored": 25792,
"full_per_class": [
0.6987918536416983,
0.6346898647440863,
0.6606104072037613,
0.6319042101197373
],
"sub2000": 0.6573379859397431,
"sub2000_n_scored": 1986,
"sub2000_per_class": [
0.7039413382218148,
0.6536144578313253,
0.6437768240343348,
0.6280193236714976
],
"sub8000": 0.6545491829661025,
"sub8000_n_scored": 7930,
"sub8000_per_class": [
0.6958867161159811,
0.6416382252559727,
0.6666666666666666,
0.61400512382579
],
"seconds": 75.8
},
{
"n": 100,
"rep": 0,
"n_shots": 400,
"full": 0.7015724606580533,
"full_n_scored": 25592,
"full_per_class": [
0.7581886989429727,
0.6852300242130751,
0.7042970996631337,
0.658574019813032
],
"sub2000": 0.7054498451890512,
"sub2000_n_scored": 1979,
"sub2000_per_class": [
0.7592752372735116,
0.6898148148148148,
0.6991341991341992,
0.6735751295336787
],
"sub8000": 0.6991970661760609,
"sub8000_n_scored": 7885,
"sub8000_per_class": [
0.7551972846839202,
0.6843326885880078,
0.7103355704697987,
0.6469227209625174
],
"seconds": 75.6
},
{
"n": 100,
"rep": 1,
"n_shots": 400,
"full": 0.6984739849914747,
"full_n_scored": 25592,
"full_per_class": [
0.757210417638047,
0.681917211328976,
0.699968030690537,
0.6548002803083391
],
"sub2000": 0.6901250639689709,
"sub2000_n_scored": 1963,
"sub2000_per_class": [
0.7511071744906997,
0.6833073322932918,
0.6780021253985122,
0.6480836236933798
],
"sub8000": 0.6932988533770741,
"sub8000_n_scored": 7873,
"sub8000_per_class": [
0.7516254876462939,
0.6824534161490683,
0.7043137254901961,
0.6348027842227378
],
"seconds": 71.3
},
{
"n": 100,
"rep": 2,
"n_shots": 400,
"full": 0.6913773887112747,
"full_n_scored": 25592,
"full_per_class": [
0.7481803005008347,
0.6678057114962167,
0.6891409534385659,
0.6603825894094816
],
"sub2000": 0.6964998689575894,
"sub2000_n_scored": 1971,
"sub2000_per_class": [
0.7528991971454059,
0.6872586872586872,
0.6861924686192469,
0.6596491228070176
],
"sub8000": 0.6913190180359224,
"sub8000_n_scored": 7873,
"sub8000_per_class": [
0.7485329276244295,
0.675223648385842,
0.6954936181297213,
0.6460258780036968
],
"seconds": 69.3
},
{
"n": 100,
"rep": 3,
"n_shots": 400,
"full": 0.6989650082863244,
"full_n_scored": 25592,
"full_per_class": [
0.7544545273895475,
0.683009708737864,
0.7019051479529793,
0.6564906490649065
],
"sub2000": 0.6978739077912046,
"sub2000_n_scored": 1963,
"sub2000_per_class": [
0.743978590544157,
0.6902927580893683,
0.7007616974972797,
0.6564625850340136
],
"sub8000": 0.6952100373158328,
"sub8000_n_scored": 7869,
"sub8000_per_class": [
0.7509727626459144,
0.6890691386635767,
0.7073886369698587,
0.6334096109839817
],
"seconds": 70.0
},
{
"n": 100,
"rep": 4,
"n_shots": 400,
"full": 0.6961408310857994,
"full_n_scored": 25592,
"full_per_class": [
0.7297572914542118,
0.6625096502167587,
0.7057907845579079,
0.6865055981143194
],
"sub2000": 0.6906610119148429,
"sub2000_n_scored": 1977,
"sub2000_per_class": [
0.7171532846715328,
0.6661698956780924,
0.6907962771458118,
0.6885245901639344
],
"sub8000": 0.6952393187048275,
"sub8000_n_scored": 7873,
"sub8000_per_class": [
0.7325066430469442,
0.6708333333333333,
0.7066939192641799,
0.6709233791748527
],
"seconds": 69.8
},
{
"n": 200,
"rep": 0,
"n_shots": 800,
"full": 0.7264520284114167,
"full_n_scored": 25192,
"full_per_class": [
0.7794158170294847,
0.716264012948864,
0.7321570497536163,
0.6779712339137017
],
"sub2000": 0.7356052106575132,
"sub2000_n_scored": 1944,
"sub2000_per_class": [
0.7804428044280443,
0.7388342165026495,
0.7276550998948476,
0.6954887218045113
],
"sub8000": 0.7244993307381107,
"sub8000_n_scored": 7767,
"sub8000_per_class": [
0.7783516730294183,
0.7232500476826245,
0.7360749609578344,
0.6603206412825652
],
"seconds": 71.0
},
{
"n": 200,
"rep": 1,
"n_shots": 800,
"full": 0.712509515337747,
"full_n_scored": 25192,
"full_per_class": [
0.7726071936598252,
0.6942394741737459,
0.71399209486166,
0.6691992986557569
],
"sub2000": 0.7080344138130289,
"sub2000_n_scored": 1948,
"sub2000_per_class": [
0.7576301615798923,
0.6897637795275591,
0.7144340602284528,
0.6703096539162113
],
"sub8000": 0.7113541517684345,
"sub8000_n_scored": 7763,
"sub8000_per_class": [
0.7650681918169819,
0.6929633300297324,
0.7242628039317124,
0.6631222812953117
],
"seconds": 70.1
},
{
"n": 200,
"rep": 2,
"n_shots": 800,
"full": 0.7180229359779726,
"full_n_scored": 25192,
"full_per_class": [
0.770847835166365,
0.7027319773739319,
0.7245050871519836,
0.6740068442196102
],
"sub2000": 0.7149225707742534,
"sub2000_n_scored": 1935,
"sub2000_per_class": [
0.7636022514071295,
0.7097767513471901,
0.7099476439790576,
0.6763636363636364
],
"sub8000": 0.7154840310541581,
"sub8000_n_scored": 7774,
"sub8000_per_class": [
0.770725096001807,
0.7087155963302753,
0.7244053774560496,
0.6580900544285008
],
"seconds": 70.4
},
{
"n": 200,
"rep": 3,
"n_shots": 800,
"full": 0.7184116256432109,
"full_n_scored": 25192,
"full_per_class": [
0.7688070929607738,
0.6962648041299727,
0.7291430422809007,
0.6794315632011967
],
"sub2000": 0.7239447557025716,
"sub2000_n_scored": 1951,
"sub2000_per_class": [
0.7715555555555556,
0.7079783113865221,
0.7228144989339019,
0.6934306569343066
],
"sub8000": 0.7175247037326138,
"sub8000_n_scored": 7752,
"sub8000_per_class": [
0.7662366061666303,
0.6992627085758634,
0.7320331285065456,
0.672566371681416
],
"seconds": 75.8
},
{
"n": 200,
"rep": 4,
"n_shots": 800,
"full": 0.7265424335350622,
"full_n_scored": 25192,
"full_per_class": [
0.7739442825188098,
0.7075471698113207,
0.7328964194373402,
0.6917818623727784
],
"sub2000": 0.7326547339766687,
"sub2000_n_scored": 1929,
"sub2000_per_class": [
0.777676120768527,
0.7307398932112891,
0.7348242811501597,
0.6873786407766991
],
"sub8000": 0.7220171449149205,
"sub8000_n_scored": 7770,
"sub8000_per_class": [
0.7695019832525342,
0.7113421914115156,
0.738880167451596,
0.6683442375440363
],
"seconds": 78.8
}
]
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374# Notebook 5 results (Qwen3-4B LoRA, Amsterdam), transcribed from Colab
Run: A100 High-RAM, 2026-11-10, finished about 18:50 AST. The runtime thendisconnected, so `/content/hack4dev/data/processed/llm_results.pkl` and`/content/hack4dev/reports/protocol_results.csv` were written only to theColab VM's disk, not to Drive. They are recovered from the downloaded notebook:
- `reports/05_evaluate_and_adapt_colab_run.ipynb`: the executed notebook with every cell's output (no errors).- `reports/protocol_results.csv`: rebuilt from cell 7's per-draw log (30 rows: 5 values of n x 6 repeats). - Values are rounded to 4 decimals as printed. - The means and stds match the notebook's summary table to within 1e-4.- `reports/f1_vs_log2_samples.png`: the plot, taken from the notebook output.
`llm_results.pkl` (the zero-shot probabilities) is not recoverable without are-run. Nothing downstream needs it.
## Zero-shot (n = 0, no Amsterdam labels)
- Macro F1 **0.5537** on 6,000 random Amsterdam pixels.- Bootstrap std 0.0067, 95% interval [0.5411, 0.5669].- That band is sampling noise on a single prediction set, not variation across labelled draws.
## Protocol: macro F1 mean (std) on a fixed 2,000-pixel evaluation set
| n per class | retrieval + Madrid rule | + bias recalibration | + tuned decision weights | ens LLM 0.3 / LGBM 0.7 | ens 0.5 / 0.5 | ens 0.7 / 0.3 ||---|---|---|---|---|---|---|| 5 | 0.5140 (0.0111) | n/a | n/a | 0.5600 (0.0042) | 0.5490 (0.0497) | 0.5471 (0.0359) || 25 | 0.5174 (0.0165) | n/a | n/a | 0.5647 (0.0011) | 0.4756 (0.0053) | 0.4732 (0.0053) || 50 | 0.5378 (0.0258) | 0.5044 (0.0443) | n/a | 0.5770 (0.0048) | 0.4753 (0.0072) | 0.4754 (0.0057) || 100 | 0.5492 (0.0303) | 0.5298 (0.0590) | n/a | 0.5800 (0.0039) | 0.4825 (0.0030) | 0.4804 (0.0042) || 200 | 0.5677 (0.0223) | 0.5993 (0.0149) | **0.6222** (0.0256) | 0.5847 (0.0039) | 0.4904 (0.0054) | 0.4908 (0.0039) |
The "+ bias recalibration" step needs n >= 50 and the "+ tuned decisionweights" step needs n >= 200, so the other cells are empty by design.
Notebook summary for the deliverable rule (as specified: richest stepavailable at each n):
- 5: 0.5140, 25: 0.5174, 50: 0.5044, 100: 0.5298, 200: 0.6222- Average across n: 0.5376. Peak: 0.6222. Low-data (n=25): 0.5174 +- 0.0165.- Best single fixed variant: ensemble LLM 0.3 / LightGBM 0.7, with average 0.5733, peak 0.5847 and 0.5647 at n=25.
## Against the classical models (notebook 3)
Classical best, scored on all of Amsterdam:- Average 0.6563 and peak 0.7204, from the upweighted-shots LightGBM.- Best at n=25: 0.6361, from the within-class Mahalanobis prototype.- Zero-shot LightGBM trained on Madrid only, with no normalisation, scores 0.5928 at every n.
The LLM zero-shot score of 0.5537 has a 95% interval of [0.541, 0.567], whichsits clearly below that.
The LLM track does not beat them at any n.
## Things to look into
1. **Retrieval hurts.** The zero-shot model (0.554) beats the retrieval-from-Amsterdam-shots variant at every n up to 100. The model was trained with a large Madrid retrieval pool, and a handful of Amsterdam shots gives far, sparse neighbours.2. **The ensemble uses the Madrid-only LightGBM.** `amsterdam_proba_lgbm` comes from notebook 3's `final` model and is the same for every n; it never sees the Amsterdam shots. That explains why its std is tiny and why it stays below the classical track, which retrains with the shots.3. **The ensemble is not monotone in the weight.** At n >= 25, the 0.5/0.5 and 0.7/0.3 mixes (about 0.48) score below both of their parts. That needs checking: - whether the class order of `Pc` and the LightGBM probabilities match; - how `macro_f1_plugin`'s prior interacts with the mixed probabilities.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129platform: local
looking for raw parquet under: C:\Users\Lenovo\Desktop\hack4dev\data\raw
Madrid : C:\Users\Lenovo\Desktop\hack4dev\data\raw\madrid_train.parquet
Amsterdam: C:\Users\Lenovo\Desktop\hack4dev\data\raw\amsterdam_data.parquet
3,172,765 rows x 48 columns
columns:
['pixel_id', 'city', 'year', 'px_key', 'py_key', 'pixel_x', 'pixel_y', 'row', 'col', 'coverage', 'usable_label', 'weighted_mean_year', 'Blue_1', 'Green_1', 'Red_1', 'NIR_1', 'SWIR1_1', 'SWIR2_1', 'QA_PIXEL_1', 'QA_RADSAT_1', 'doy_1', 'scene_id_1', 'dataset_1', 'qa_valid_1', 'Blue_2', 'Green_2', 'Red_2', 'NIR_2', 'SWIR1_2', 'SWIR2_2', 'QA_PIXEL_2', 'QA_RADSAT_2', 'doy_2', 'scene_id_2', 'dataset_2', 'qa_valid_2', 'Blue_3', 'Green_3', 'Red_3', 'NIR_3', 'SWIR1_3', 'SWIR2_3', 'QA_PIXEL_3', 'QA_RADSAT_3', 'doy_3', 'scene_id_3', 'dataset_3', 'qa_valid_3']
years: 1984 - 2025 (42 distinct)
unique pixels: 76,263
first row:
pixel_id Madrid_14194_149671_1984
city Madrid
year 1984
px_key 14194
py_key 149671
pixel_x 425820.0
pixel_y 4490130.0
row 5
col 20
coverage 0.15
usable_label True
weighted_mean_year 2014.0
Blue_1 9184.207031
Green_1 9821.585938
Red_1 10537.317383
NIR_1 15736.041016
SWIR1_1 16615.345703
SWIR2_1 13306.133789
QA_PIXEL_1 5440
QA_RADSAT_1 0
doy_1 199
scene_id_1 LT05_L2SP_201032_19840717_20200918_02_T1
dataset_1 landsat_tm_c2_l2
qa_valid_1 True
Blue_2 9511.026367
Green_2 10161.28125
Red_2 10884.139648
NIR_2 15506.376953
SWIR1_2 16767.910156
SWIR2_2 13043.585938
QA_PIXEL_2 5440
QA_RADSAT_2 0
doy_2 231
scene_id_2 LT05_L2SP_201032_19840818_20200918_02_T1
dataset_2 landsat_tm_c2_l2
qa_valid_2 True
Blue_3 9323.154297
Green_3 10433.227539
Red_3 11603.330078
NIR_3 16555.982422
SWIR1_3 18056.576172
SWIR2_3 13991.788086
QA_PIXEL_3 5440
QA_RADSAT_3 0
doy_3 247
scene_id_3 LT05_L2SP_201032_19840903_20201008_02_T2
dataset_3 landsat_tm_c2_l2
qa_valid_3 True
Red_1 digital numbers : {0.0: 0.0, 0.01: 0.0, 0.5: 12419.0, 0.99: 18727.0, 1.0: 65454.0}
Red_1 as reflectance : {0.0: -0.2, 0.01: -0.2, 0.5: 0.142, 0.99: 0.315, 1.0: 1.6}
qa_valid_1: 95.0% valid
qa_valid_2: 95.7% valid
qa_valid_3: 90.1% valid
reading C:\Users\Lenovo\Desktop\hack4dev\data\raw\madrid_train.parquet
3,172,765 rows x 48 cols | years 1984-2025
removed 36,017 haze rows (Blue > 15,000)
-> 76,263 labelled pixels | 60 official + 316 extended features
reading C:\Users\Lenovo\Desktop\hack4dev\data\raw\amsterdam_data.parquet
1,062,877 rows x 48 cols | years 1984-2025
removed 6,340 haze rows (Blue > 15,000)
-> 25,992 labelled pixels | 60 official + 316 extended features
preprocessed_data.pkl not found - skipping the cross-check.
Madrid: 76,263 labelled pixels
class 1 (before 1960): 13,794 18.1%
class 2 ( 1960-1984): 27,152 35.6%
class 3 ( 1984-2004): 18,672 24.5%
class 4 ( 2004-2024): 16,645 21.8%
Amsterdam: 25,992 labelled pixels
class 1 (before 1945): 7,568 29.1%
class 2 ( 1945-1984): 8,802 33.9%
class 3 ( 1984-2004): 6,745 26.0%
class 4 ( 2004-2024): 2,877 11.1%
madrid_mean amsterdam_mean madrid_sd gap_in_madrid_sd
sr_Red_mean 0.151 0.083 0.035 -1.971
sr_brightness_mean 0.173 0.113 0.033 -1.857
sr_SWIR1_mean 0.245 0.162 0.050 -1.648
sr_NIR_mean 0.225 0.175 0.038 -1.307
sr_BSI_mean 0.103 0.022 0.066 -1.218
sr_UI_mean -0.055 -0.163 0.116 -0.926
sr_NDBI_mean 0.034 -0.034 0.079 -0.861
sr_brightness_std 0.028 0.021 0.014 -0.530
sr_MNDWI_mean -0.347 -0.381 0.072 -0.470
coverage 0.505 0.421 0.251 -0.334
step_brightness_njumps 9.831 9.781 4.004 -0.012
step_brightness_mag -0.003 0.001 0.057 0.079
sr_brightness_late_minus_early -0.019 -0.008 0.030 0.364
sr_NDVI_mean 0.204 0.355 0.099 1.534
C:\Users\Lenovo\Desktop\hack4dev\notebooks\src\01_build_features.py:220: UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown
plt.show()
Madrid
step_brightness_year vs true year (classes 3+4): r=+0.206 median |error| = 6.1 years within 5 y: 44.6%
step_SWIR1_year vs true year (classes 3+4): r=+0.240 median |error| = 6.0 years within 5 y: 47.6%
step_NDVI_year vs true year (classes 3+4): r=+0.130 median |error| = 7.0 years within 5 y: 41.1%
mean |step magnitude| by class: {1: 0.0356, 2: 0.0399, 3: 0.054, 4: 0.0687}
Amsterdam
step_brightness_year vs true year (classes 3+4): r=+0.481 median |error| = 3.0 years within 5 y: 69.4%
step_SWIR1_year vs true year (classes 3+4): r=+0.473 median |error| = 2.7 years within 5 y: 70.0%
step_NDVI_year vs true year (classes 3+4): r=+0.321 median |error| = 3.0 years within 5 y: 64.5%
mean |step magnitude| by class: {1: 0.0216, 2: 0.0264, 3: 0.0505, 4: 0.0647}
C:\Users\Lenovo\Desktop\hack4dev\notebooks\src\01_build_features.py:256: UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown
plt.show()
added 15 neighbourhood features
nbr_sr_brightness_mean nbr_sr_brightness_mean_diff nbr_sr_NDVI_mean nbr_sr_NDVI_mean_diff nbr_sr_SWIR1_mean nbr_sr_SWIR1_mean_diff
age_class
1 0.1625 -0.0003 0.1808 0.0044 0.2340 0.0006
2 0.1658 -0.0011 0.2074 0.0015 0.2335 -0.0017
3 0.1747 -0.0001 0.2051 0.0007 0.2440 -0.0008
4 0.1925 0.0015 0.2087 -0.0000 0.2747 0.0023
C:\Users\Lenovo\Desktop\hack4dev\data\processed\madrid_features.parquet 165.5 MB (76263, 400)
C:\Users\Lenovo\Desktop\hack4dev\data\processed\amsterdam_features.parquet 56.2 MB (25992, 400)
feature groups: 60 official, 276 reflectance-based, 15 change-event, 15 neighbourhood123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
feature source: notebook 1 (official 60 + extended)
(76263, 400) (25992, 400)
dead (zero variance in at least one city): ['has_early_data', 'sat_share_oli_early']
official60 59 features
reflectance 276 features
events 15 features
neighbourhood 15 features
everything 393 features
block sizes: [3933 4437 785 2982 3078 3441 2820 3521 2363 3020 2929 2330 3738 2660
3573 2154 3367 3580 2947 3250 2674 2376 3575 4257 2473]
C:\Users\Lenovo\Desktop\hack4dev\notebooks\src\03_gbdt_models.py:115: UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown
plt.show()
city-vs-city AUC: 1.0000 (1.0 = the two cities are trivially told apart)
feature city_importance
sat_share_oli_late 0.036333
sat_share_tm_early 0.035556
sat_share_etm_late 0.034222
sat_switches 0.032667
nbr_sr_brightness_mean 0.032000
sr_NDVI_early_std 0.030556
sat_share_etm_early 0.028778
sr_BSI_dec84_93_mean 0.026222
sat_share_oli 0.025778
sat_share_etm 0.024333
sr_NDVI_dec84_93_mean 0.023444
nbr_sr_SWIR1_mean 0.020111
radial_frac 0.019778
nbr_sr_NDVI_mean 0.016556
radial_px 0.016111
sr_Red_dec84_93_mean 0.014667
sr_NDVI_max 0.014444
n_observed_years 0.013444
dist_to_water_px 0.013000
sat_share_tm 0.011333
worst offenders, raw vs after per-city rank normalisation:
feature auc_raw auc_after_rank
sat_share_etm_late 0.990 0.971
sat_share_oli_late 0.989 0.593
sat_share_oli 0.988 0.579
sat_share_etm 0.972 0.607
sr_Red_dec84_93_mean 0.969 0.500
nbr_sr_brightness_mean 0.966 0.500
sr_Red_early_mean 0.963 0.500
Red_early_mean 0.963 0.500
sr_Red_tm_mean 0.957 0.500
nbr_sr_SWIR1_mean 0.957 0.500
sr_SWIR2_dec84_93_mean 0.955 0.500
sr_brightness_dec84_93_mean 0.951 0.500
sr_Red_min 0.951 0.500
sr_Red_mean 0.951 0.500
Red_mean 0.951 0.500
sr_Green_dec84_93_mean 0.948 0.500
sr_brightness_early_mean 0.947 0.500
SWIR2_early_mean 0.945 0.500
sr_SWIR2_early_mean 0.945 0.500
Green_early_mean 0.944 0.500
sr_Green_early_mean 0.944 0.500
sr_brightness_mean 0.941 0.500
sat_switches 0.941 0.906
sr_brightness_tm_mean 0.940 0.500
sr_TCB_early_mean 0.939 0.500
median domain AUC: raw 0.750 -> after rank 0.500
features still above 0.90 after normalisation: 5 of 393
C:\Users\Lenovo\Desktop\hack4dev\notebooks\src\03_gbdt_models.py:183: UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown
plt.show()
AUC raw 1.0000 | robust-z 1.0000 | rank 1.0000
still city-specific after rank normalisation:
feature city_importance
sat_share_tm 0.109133
n_observed_years 0.094531
sat_share_tm_late 0.083899
sat_share_etm_late 0.072243
sat_switches 0.053670
sat_share_etm 0.043294
sat_share_oli 0.043294
sat_share_oli_late 0.041629
sat_share_tm_early 0.033944
sat_share_etm_early 0.017805
step_SWIR1_njumps 0.015883
last_observed_year 0.014090
features still above AUC 0.9 after normalisation: 5
dropping 4: ['sat_share_etm_late', 'sat_switches', 'sat_share_tm_late', 'n_observed_years']
pruned set: 389 features
most city-specific features that we KEPT because they carry age signal:
feature auc_raw auc_after_rank age_importance
n_observed_years 0.6849 1.0000 0.0049
sat_share_tm_late 0.7312 0.9943 0.0016
sat_share_tm 0.5642 0.9912 0.0064
sat_share_etm_late 0.9901 0.9715 0.0011
sat_switches 0.9410 0.9063 0.0013
pre_state 0.7931 0.7109 0.0001
sat_share_etm 0.9718 0.6065 0.0037
sat_share_oli_late 0.9890 0.5930 0.0015
official60 lgbm 0.5557 +- 0.0540 (4.1 min)
official60 lgbm_unweighted 0.5504 +- 0.0633 (4.2 min)
official60 lgbm_ordinal 0.5462 +- 0.0637 (3.2 min)
official60 catboost 0.5446 +- 0.0480 (7.5 min)
everything lgbm 0.5702 +- 0.0703 (12.4 min)
everything lgbm_unweighted 0.5690 +- 0.0830 (11.1 min)
everything lgbm_ordinal 0.5623 +- 0.0912 (11.0 min)
pruned lgbm 0.5693 +- 0.0730 (12.9 min)
pruned lgbm_unweighted 0.5688 +- 0.0853 (12.1 min)
pruned lgbm_ordinal 0.5631 +- 0.0897 (10.2 min)
features model n_feat macro_f1 std minutes
everything lgbm 393 0.5702 0.0703 12.4381
pruned lgbm 389 0.5693 0.0730 12.8702
everything lgbm_unweighted 393 0.5690 0.0830 11.1390
pruned lgbm_unweighted 389 0.5688 0.0853 12.1380
pruned lgbm_ordinal 389 0.5631 0.0897 10.1615
everything lgbm_ordinal 393 0.5623 0.0912 10.9793
official60 lgbm 59 0.5557 0.0540 4.0525
official60 lgbm_unweighted 59 0.5504 0.0633 4.1540
official60 lgbm_ordinal 59 0.5462 0.0637 3.2285
official60 catboost 59 0.5446 0.0480 7.5037
normalise=None 0.5989 +- 0.0230
normalise=robustz 0.5690 +- 0.0830
normalise=rank 0.5697 +- 0.0789
normalise macro_f1 std
None 0.5989 0.0230
rank 0.5697 0.0789
robustz 0.5690 0.0830
normalisation chosen on Madrid: None
Whatever Amsterdam says later, this is the choice the rules allow us to
make. If Amsterdam disagrees, that is a finding to report, not a reason
to switch.
baseline argmax, Madrid block-CV: 0.5761
tuned class weights: [1.058 1.333 0.943 0.666]
after weighting: 0.5821
spatial smoothing r= 2.0: 0.5906
spatial smoothing r= 4.0: 0.5868
spatial smoothing r= 8.0: 0.5835
pred 1 pred 2 pred 3 pred 4
true 1 0.446 0.427 0.083 0.044
true 2 0.170 0.681 0.091 0.058
true 3 0.069 0.221 0.587 0.123
true 4 0.056 0.172 0.183 0.589
regime both clean covariate label delta_vs_argmax_mean delta_vs_argmax_worst
strategy
argmax 0.4766 0.6056 0.5329 0.5392 0.0000 0.0000
em_free 0.3589 0.5312 0.3768 0.4900 -0.0993 -0.1079
em_pinned_shrunk 0.4406 0.5838 0.4792 0.5267 -0.0310 -0.0333
em_shrunk 0.4563 0.5895 0.4965 0.5314 -0.0201 -0.0063
logit_adj_tau0.25 0.4803 0.6093 0.5369 0.5438 0.0040 0.0010
logit_adj_tau0.5 0.4819 0.6102 0.5392 0.5469 0.0060 0.0014
logit_adj_tau1.0 0.4806 0.6068 0.5351 0.5477 0.0040 0.0156
plugin_srcprior 0.4885 0.6143 0.5524 0.5460 0.0117 0.0211
tau0.5_em_plugin 0.4693 0.6030 0.5212 0.5428 -0.0045 0.0159
tau0.5_then_plugin 0.4889 0.6134 0.5531 0.5472 0.0121 0.0267
rules that never lose to plain argmax in any regime:
regime both clean covariate label delta_vs_argmax_mean delta_vs_argmax_worst
strategy
argmax 0.4766 0.6056 0.5329 0.5392 0.0000 0.0000
logit_adj_tau0.25 0.4803 0.6093 0.5369 0.5438 0.0040 0.0010
logit_adj_tau0.5 0.4819 0.6102 0.5392 0.5469 0.0060 0.0014
logit_adj_tau1.0 0.4806 0.6068 0.5351 0.5477 0.0040 0.0156
plugin_srcprior 0.4885 0.6143 0.5524 0.5460 0.0117 0.0211
tau0.5_em_plugin 0.4693 0.6030 0.5212 0.5428 -0.0045 0.0159
tau0.5_then_plugin 0.4889 0.6134 0.5531 0.5472 0.0121 0.0267
rules to avoid:
regime both clean covariate label delta_vs_argmax_mean delta_vs_argmax_worst
strategy
em_free 0.3589 0.5312 0.3768 0.4900 -0.0993 -0.1079
em_pinned_shrunk 0.4406 0.5838 0.4792 0.5267 -0.0310 -0.0333
rule chosen on Madrid alone: tau0.5_then_plugin
Madrid class prior: [0.181 0.356 0.245 0.218]
organisers' prototype (Euclidean, Madrid scaler)
n=5 macro F1 = 0.5133 +- 0.0277 per-class [0.554 0.493 0.51 0.496]
n=25 macro F1 = 0.5805 +- 0.0161 per-class [0.627 0.563 0.568 0.565]
n=50 macro F1 = 0.5914 +- 0.0150 per-class [0.65 0.562 0.578 0.576]
n=100 macro F1 = 0.6000 +- 0.0069 per-class [0.648 0.599 0.581 0.572]
n=200 macro F1 = 0.5921 +- 0.0052 per-class [0.63 0.593 0.576 0.569]
(12 draws per n, 0.6 min)
pure retrieval k-NN (no source model)
n=5 macro F1 = 0.3834 +- 0.0652 per-class [0.286 0.446 0.385 0.417]
n=25 macro F1 = 0.6165 +- 0.0110 per-class [0.673 0.594 0.641 0.558]
n=50 macro F1 = 0.6301 +- 0.0098 per-class [0.693 0.609 0.653 0.566]
n=100 macro F1 = 0.6496 +- 0.0060 per-class [0.714 0.632 0.679 0.573]
n=200 macro F1 = 0.6646 +- 0.0044 per-class [0.73 0.653 0.686 0.589]
(12 draws per n, 4.7 min)
zero-shot, no normalisation
n=5 macro F1 = 0.5871 +- 0.0002 per-class [0.583 0.55 0.621 0.594]
n=25 macro F1 = 0.5868 +- 0.0004 per-class [0.584 0.549 0.621 0.593]
n=50 macro F1 = 0.5867 +- 0.0005 per-class [0.583 0.55 0.621 0.593]
n=100 macro F1 = 0.5858 +- 0.0004 per-class [0.583 0.55 0.62 0.59 ]
n=200 macro F1 = 0.5852 +- 0.0013 per-class [0.584 0.55 0.621 0.587]
(12 draws per n, 9.7 min)
zero-shot, robust z
n=5 macro F1 = 0.5245 +- 0.0002 per-class [0.513 0.532 0.541 0.513]
n=25 macro F1 = 0.5243 +- 0.0004 per-class [0.513 0.532 0.54 0.512]
n=50 macro F1 = 0.5242 +- 0.0006 per-class [0.513 0.532 0.54 0.512]
n=100 macro F1 = 0.5229 +- 0.0005 per-class [0.513 0.532 0.54 0.507]
n=200 macro F1 = 0.5222 +- 0.0013 per-class [0.513 0.531 0.54 0.504]
(12 draws per n, 10.9 min)
zero-shot, rank
n=5 macro F1 = 0.5542 +- 0.0001 per-class [0.563 0.571 0.562 0.522]
n=25 macro F1 = 0.5541 +- 0.0003 per-class [0.563 0.571 0.562 0.521]
n=50 macro F1 = 0.5540 +- 0.0007 per-class [0.563 0.571 0.562 0.521]
n=100 macro F1 = 0.5527 +- 0.0006 per-class [0.563 0.571 0.561 0.516]
n=200 macro F1 = 0.5523 +- 0.0013 per-class [0.563 0.571 0.563 0.513]
(12 draws per n, 13.7 min)
zero-shot, robust z + CORAL
n=5 macro F1 = 0.5377 +- 0.0001 per-class [0.544 0.516 0.564 0.527]
n=25 macro F1 = 0.5375 +- 0.0004 per-class [0.544 0.516 0.564 0.526]
n=50 macro F1 = 0.5375 +- 0.0006 per-class [0.544 0.516 0.564 0.526]
n=100 macro F1 = 0.5363 +- 0.0007 per-class [0.544 0.516 0.563 0.522]
n=200 macro F1 = 0.5355 +- 0.0012 per-class [0.544 0.516 0.564 0.518]
(12 draws per n, 10.9 min)
prototype, robust z + euclidean
n=5 macro F1 = 0.4515 +- 0.0671 per-class [0.416 0.435 0.466 0.489]
n=25 macro F1 = 0.4148 +- 0.1209 per-class [0.42 0.342 0.475 0.422]
n=50 macro F1 = 0.4335 +- 0.1161 per-class [0.497 0.328 0.491 0.419]
n=100 macro F1 = 0.4524 +- 0.0918 per-class [0.433 0.308 0.554 0.514]
n=200 macro F1 = 0.2526 +- 0.1068 per-class [0.113 0.199 0.316 0.383]
(12 draws per n, 14.7 min)
prototype, rank + euclidean
n=5 macro F1 = 0.5181 +- 0.0402 per-class [0.587 0.503 0.517 0.466]
n=25 macro F1 = 0.5939 +- 0.0157 per-class [0.643 0.574 0.634 0.524]
n=50 macro F1 = 0.6041 +- 0.0146 per-class [0.656 0.576 0.651 0.534]
n=100 macro F1 = 0.6192 +- 0.0068 per-class [0.668 0.602 0.653 0.554]
n=200 macro F1 = 0.6189 +- 0.0055 per-class [0.665 0.609 0.651 0.551]
(12 draws per n, 19.8 min)
prototype, robust z + total-cov Mahalanobis
n=5 macro F1 = 0.4181 +- 0.0458 per-class [0.492 0.451 0.327 0.403]
n=25 macro F1 = 0.6097 +- 0.0205 per-class [0.622 0.564 0.626 0.626]
n=50 macro F1 = 0.6460 +- 0.0513 per-class [0.676 0.581 0.673 0.654]
n=100 macro F1 = 0.6865 +- 0.0102 per-class [0.71 0.661 0.699 0.676]
n=200 macro F1 = 0.6992 +- 0.0031 per-class [0.716 0.679 0.717 0.685]
(12 draws per n, 17.1 min)
prototype, robust z + within-class Mahalanobis
n=5 macro F1 = 0.5025 +- 0.0406 per-class [0.55 0.491 0.482 0.487]
n=25 macro F1 = 0.6334 +- 0.0192 per-class [0.64 0.594 0.663 0.636]
n=50 macro F1 = 0.6695 +- 0.0132 per-class [0.69 0.636 0.692 0.66 ]
n=100 macro F1 = 0.6967 +- 0.0060 per-class [0.718 0.673 0.71 0.687]
n=200 macro F1 = 0.7085 +- 0.0024 per-class [0.73 0.686 0.724 0.694]
(12 draws per n, 17.3 min)
recalibrated (stratification-corrected)
n=5 macro F1 = 0.5309 +- 0.0083 per-class [0.499 0.546 0.549 0.529]
n=25 macro F1 = 0.5349 +- 0.0042 per-class [0.517 0.545 0.55 0.528]
n=50 macro F1 = 0.5452 +- 0.0081 per-class [0.53 0.547 0.561 0.542]
n=100 macro F1 = 0.5514 +- 0.0167 per-class [0.542 0.539 0.573 0.551]
n=200 macro F1 = 0.5591 +- 0.0054 per-class [0.55 0.546 0.583 0.557]
(12 draws per n, 25.8 min)
refit leaf values (structure frozen)
n=5 macro F1 = 0.5702 +- 0.0056 per-class [0.571 0.584 0.582 0.545]
n=25 macro F1 = 0.5999 +- 0.0070 per-class [0.633 0.596 0.607 0.564]
n=50 macro F1 = 0.6155 +- 0.0063 per-class [0.654 0.61 0.622 0.577]
n=100 macro F1 = 0.6314 +- 0.0040 per-class [0.673 0.629 0.638 0.586]
n=200 macro F1 = 0.6437 +- 0.0019 per-class [0.687 0.64 0.653 0.594]
(12 draws per n, 11.1 min)
upweighted shots, retrained
n=5 macro F1 = 0.5609 +- 0.0105 per-class [0.585 0.565 0.56 0.533]
n=25 macro F1 = 0.6259 +- 0.0126 per-class [0.676 0.605 0.635 0.588]
n=50 macro F1 = 0.6664 +- 0.0103 per-class [0.719 0.654 0.675 0.616]
n=100 macro F1 = 0.6949 +- 0.0029 per-class [0.748 0.68 0.705 0.646]
n=200 macro F1 = 0.7182 +- 0.0052 per-class [0.77 0.707 0.731 0.664]
(5 draws per n, 56.7 min)
catboost recalibrated
n=5 macro F1 = 0.5453 +- 0.0052 per-class [0.586 0.523 0.554 0.519]
n=25 macro F1 = 0.5477 +- 0.0036 per-class [0.592 0.523 0.555 0.521]
n=50 macro F1 = 0.5487 +- 0.0061 per-class [0.597 0.518 0.557 0.523]
n=100 macro F1 = 0.5550 +- 0.0068 per-class [0.597 0.51 0.574 0.539]
n=200 macro F1 = 0.5541 +- 0.0070 per-class [0.598 0.509 0.574 0.535]
(12 draws per n, 24.8 min)
5 25 50 100 200 average peak
upweighted shots, retrained 0.5609 0.6259 0.6664 0.6949 0.7182 0.6533 0.7182
prototype, robust z + within-class Mahalanobis 0.5025 0.6334 0.6695 0.6967 0.7085 0.6421 0.7085
refit leaf values (structure frozen) 0.5702 0.5999 0.6155 0.6314 0.6437 0.6121 0.6437
prototype, robust z + total-cov Mahalanobis 0.4181 0.6097 0.6460 0.6865 0.6992 0.6119 0.6992
prototype, rank + euclidean 0.5181 0.5939 0.6041 0.6192 0.6189 0.5908 0.6192
pure retrieval k-NN (no source model) 0.3834 0.6165 0.6301 0.6496 0.6646 0.5889 0.6646
zero-shot, no normalisation 0.5871 0.5868 0.5867 0.5858 0.5852 0.5863 0.5871
organisers' prototype (Euclidean, Madrid scaler) 0.5133 0.5805 0.5914 0.6000 0.5921 0.5754 0.6000
zero-shot, rank 0.5542 0.5541 0.5540 0.5527 0.5523 0.5535 0.5542
catboost recalibrated 0.5453 0.5477 0.5487 0.5550 0.5541 0.5502 0.5550
recalibrated (stratification-corrected) 0.5309 0.5349 0.5452 0.5514 0.5591 0.5443 0.5591
zero-shot, robust z + CORAL 0.5377 0.5375 0.5375 0.5363 0.5355 0.5369 0.5377
zero-shot, robust z 0.5245 0.5243 0.5242 0.5229 0.5222 0.5236 0.5245
prototype, robust z + euclidean 0.4515 0.4148 0.4335 0.4524 0.2526 0.4010 0.4524
C:\Users\Lenovo\Desktop\hack4dev\notebooks\src\03_gbdt_models.py:517: UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown
plt.show()
best classical variant on the protocol: upweighted shots, retrained
saved: C:\Users\Lenovo\Desktop\hack4dev\data\processed\gbdt_outputs.pkl123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
feature source: notebook 1 (official 60 + extended)
(76263, 400) (25992, 400)
dead (zero variance in at least one city): ['has_early_data', 'sat_share_oli_early']
official60 59 features
reflectance 276 features
events 15 features
neighbourhood 15 features
everything 393 features
block sizes: [3933 4437 785 2982 3078 3441 2820 3521 2363 3020 2929 2330 3738 2660
3573 2154 3367 3580 2947 3250 2674 2376 3575 4257 2473]
C:\Users\Lenovo\Desktop\hack4dev\notebooks\src\03_gbdt_models.py:115: UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown
plt.show()
city-vs-city AUC: 1.0000 (1.0 = the two cities are trivially told apart)
feature city_importance
sat_share_oli_late 0.036333
sat_share_tm_early 0.035556
sat_share_etm_late 0.034222
sat_switches 0.032667
nbr_sr_brightness_mean 0.032000
sr_NDVI_early_std 0.030556
sat_share_etm_early 0.028778
sr_BSI_dec84_93_mean 0.026222
sat_share_oli 0.025778
sat_share_etm 0.024333
sr_NDVI_dec84_93_mean 0.023444
nbr_sr_SWIR1_mean 0.020111
radial_frac 0.019778
nbr_sr_NDVI_mean 0.016556
radial_px 0.016111
sr_Red_dec84_93_mean 0.014667
sr_NDVI_max 0.014444
n_observed_years 0.013444
dist_to_water_px 0.013000
sat_share_tm 0.011333
worst offenders, raw vs after per-city rank normalisation:
feature auc_raw auc_after_rank
sat_share_etm_late 0.990 0.971
sat_share_oli_late 0.989 0.593
sat_share_oli 0.988 0.579
sat_share_etm 0.972 0.607
sr_Red_dec84_93_mean 0.969 0.500
nbr_sr_brightness_mean 0.966 0.500
sr_Red_early_mean 0.963 0.500
Red_early_mean 0.963 0.500
sr_Red_tm_mean 0.957 0.500
nbr_sr_SWIR1_mean 0.957 0.500
sr_SWIR2_dec84_93_mean 0.955 0.500
sr_brightness_dec84_93_mean 0.951 0.500
sr_Red_min 0.951 0.500
sr_Red_mean 0.951 0.500
Red_mean 0.951 0.500
sr_Green_dec84_93_mean 0.948 0.500
sr_brightness_early_mean 0.947 0.500
SWIR2_early_mean 0.945 0.500
sr_SWIR2_early_mean 0.945 0.500
Green_early_mean 0.944 0.500
sr_Green_early_mean 0.944 0.500
sr_brightness_mean 0.941 0.500
sat_switches 0.941 0.906
sr_brightness_tm_mean 0.940 0.500
sr_TCB_early_mean 0.939 0.500
median domain AUC: raw 0.750 -> after rank 0.500
features still above 0.90 after normalisation: 5 of 393
C:\Users\Lenovo\Desktop\hack4dev\notebooks\src\03_gbdt_models.py:183: UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown
plt.show()
AUC raw 1.0000 | robust-z 1.0000 | rank 1.0000
still city-specific after rank normalisation:
feature city_importance
sat_share_tm 0.109133
n_observed_years 0.094531
sat_share_tm_late 0.083899
sat_share_etm_late 0.072243
sat_switches 0.053670
sat_share_etm 0.043294
sat_share_oli 0.043294
sat_share_oli_late 0.041629
sat_share_tm_early 0.033944
sat_share_etm_early 0.017805
step_SWIR1_njumps 0.015883
last_observed_year 0.014090
features still above AUC 0.9 after normalisation: 5
dropping 4: ['sat_share_etm_late', 'sat_switches', 'sat_share_tm_late', 'n_observed_years']
pruned set: 389 features
most city-specific features that we KEPT because they carry age signal:
feature auc_raw auc_after_rank age_importance
n_observed_years 0.6849 1.0000 0.0049
sat_share_tm_late 0.7312 0.9943 0.0016
sat_share_tm 0.5642 0.9912 0.0064
sat_share_etm_late 0.9901 0.9715 0.0011
sat_switches 0.9410 0.9063 0.0013
pre_state 0.7931 0.7109 0.0001
sat_share_etm 0.9718 0.6065 0.0037
sat_share_oli_late 0.9890 0.5930 0.0015
official60 lgbm 0.5557 +- 0.0540 (2.2 min)
official60 lgbm_unweighted 0.5504 +- 0.0633 (2.2 min)
official60 catboost 0.5446 +- 0.0480 (6.6 min)
official60 lgbm_ordinal 0.5462 +- 0.0637 (1.8 min)
everything lgbm 0.5702 +- 0.0703 (11.7 min)
everything lgbm_unweighted 0.5690 +- 0.0830 (9.6 min)
everything catboost 0.5621 +- 0.0671 (34.8 min)
everything lgbm_ordinal 0.5623 +- 0.0912 (7.8 min)
pruned lgbm 0.5693 +- 0.0730 (9.3 min)
pruned lgbm_unweighted 0.5688 +- 0.0853 (8.9 min)
pruned catboost 0.5627 +- 0.0692 (35.2 min)
pruned lgbm_ordinal 0.5631 +- 0.0897 (7.6 min)
features model n_feat macro_f1 std minutes
everything lgbm 393 0.5702 0.0703 11.7390
pruned lgbm 389 0.5693 0.0730 9.2962
everything lgbm_unweighted 393 0.5690 0.0830 9.5889
pruned lgbm_unweighted 389 0.5688 0.0853 8.8673
pruned lgbm_ordinal 389 0.5631 0.0897 7.5890
pruned catboost 389 0.5627 0.0692 35.2418
everything lgbm_ordinal 393 0.5623 0.0912 7.7758
everything catboost 393 0.5621 0.0671 34.8359
official60 lgbm 59 0.5557 0.0540 2.1759
official60 lgbm_unweighted 59 0.5504 0.0633 2.2104
official60 lgbm_ordinal 59 0.5462 0.0637 1.8472
official60 catboost 59 0.5446 0.0480 6.5561
baseline argmax, Madrid block-CV: 0.5761
tuned class weights: [1.058 1.333 0.943 0.666]
after weighting: 0.5821
spatial smoothing r= 2.0: 0.5906
spatial smoothing r= 4.0: 0.5868
spatial smoothing r= 8.0: 0.5835
pred 1 pred 2 pred 3 pred 4
true 1 0.446 0.427 0.083 0.044
true 2 0.170 0.681 0.091 0.058
true 3 0.069 0.221 0.587 0.123
true 4 0.056 0.172 0.183 0.589
regime both clean covariate label delta_vs_argmax_mean delta_vs_argmax_worst
strategy
argmax 0.4766 0.6056 0.5329 0.5392 0.0000 0.0000
em_free 0.3589 0.5312 0.3768 0.4900 -0.0993 -0.1079
em_pinned_shrunk 0.4406 0.5838 0.4792 0.5267 -0.0310 -0.0333
em_shrunk 0.4563 0.5895 0.4965 0.5314 -0.0201 -0.0063
logit_adj_tau0.25 0.4803 0.6093 0.5369 0.5438 0.0040 0.0010
logit_adj_tau0.5 0.4819 0.6102 0.5392 0.5469 0.0060 0.0014
logit_adj_tau1.0 0.4806 0.6068 0.5351 0.5477 0.0040 0.0156
plugin_srcprior 0.4885 0.6143 0.5524 0.5460 0.0117 0.0211
tau0.5_em_plugin 0.4693 0.6030 0.5212 0.5428 -0.0045 0.0159
tau0.5_then_plugin 0.4889 0.6134 0.5531 0.5472 0.0121 0.0267
rules that never lose to plain argmax in any regime:
regime both clean covariate label delta_vs_argmax_mean delta_vs_argmax_worst
strategy
argmax 0.4766 0.6056 0.5329 0.5392 0.0000 0.0000
logit_adj_tau0.25 0.4803 0.6093 0.5369 0.5438 0.0040 0.0010
logit_adj_tau0.5 0.4819 0.6102 0.5392 0.5469 0.0060 0.0014
logit_adj_tau1.0 0.4806 0.6068 0.5351 0.5477 0.0040 0.0156
plugin_srcprior 0.4885 0.6143 0.5524 0.5460 0.0117 0.0211
tau0.5_em_plugin 0.4693 0.6030 0.5212 0.5428 -0.0045 0.0159
tau0.5_then_plugin 0.4889 0.6134 0.5531 0.5472 0.0121 0.0267
rules to avoid:
regime both clean covariate label delta_vs_argmax_mean delta_vs_argmax_worst
strategy
em_free 0.3589 0.5312 0.3768 0.4900 -0.0993 -0.1079
em_pinned_shrunk 0.4406 0.5838 0.4792 0.5267 -0.0310 -0.0333
rule chosen on Madrid alone: tau0.5_then_plugin
Madrid class prior: [0.181 0.356 0.245 0.218]
organisers' prototype (Euclidean, Madrid scaler)
n=5 macro F1 = 0.5066 +- 0.0358 per-class [0.552 0.471 0.504 0.499]
n=25 macro F1 = 0.5821 +- 0.0166 per-class [0.626 0.555 0.573 0.574]
n=50 macro F1 = 0.5965 +- 0.0142 per-class [0.649 0.571 0.583 0.583]
n=100 macro F1 = 0.6034 +- 0.0086 per-class [0.661 0.591 0.583 0.579]
n=200 macro F1 = 0.5972 +- 0.0057 per-class [0.643 0.591 0.579 0.577]
(20 draws per n, 2.0 min)
pure retrieval k-NN (no source model)
n=5 macro F1 = 0.3775 +- 0.0758 per-class [0.292 0.43 0.366 0.422]
n=25 macro F1 = 0.6139 +- 0.0155 per-class [0.67 0.583 0.638 0.563]
n=50 macro F1 = 0.6375 +- 0.0112 per-class [0.697 0.613 0.659 0.581]
n=100 macro F1 = 0.6533 +- 0.0063 per-class [0.717 0.632 0.676 0.588]
n=200 macro F1 = 0.6699 +- 0.0037 per-class [0.734 0.654 0.687 0.605]
(20 draws per n, 12.6 min)
zero-shot, no normalisation
n=5 macro F1 = 0.5928 +- 0.0001 per-class [0.587 0.547 0.631 0.605]
n=25 macro F1 = 0.5925 +- 0.0002 per-class [0.588 0.548 0.631 0.604]
n=50 macro F1 = 0.5922 +- 0.0003 per-class [0.587 0.548 0.631 0.603]
n=100 macro F1 = 0.5918 +- 0.0004 per-class [0.587 0.548 0.631 0.601]
n=200 macro F1 = 0.5903 +- 0.0006 per-class [0.587 0.548 0.63 0.595]
(20 draws per n, 32.0 min)
zero-shot, robust z
n=5 macro F1 = 0.5268 +- 0.0001 per-class [0.512 0.521 0.543 0.531]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374prototype, robust z + within-class Mahalanobis: 393 features, dead ['has_early_data', 'sat_share_oli_early'], Madrid (76263, 393), Amsterdam (25992, 393)
n=5 rep=0 full=0.5154 sub2000=0.5258 sub8000=0.5134 (39.8s)
n=5 rep=1 full=0.5326 sub2000=0.5267 sub8000=0.5270 (35.2s)
n=5 rep=2 full=0.5138 sub2000=0.4877 sub8000=0.5131 (27.8s)
n=5 rep=3 full=0.5247 sub2000=0.5102 sub8000=0.5209 (27.2s)
n=5 rep=4 full=0.5269 sub2000=0.5214 sub8000=0.5204 (27.6s)
n=5 rep=5 full=0.5471 sub2000=0.5534 sub8000=0.5485 (27.6s)
n=5 rep=6 full=0.4699 sub2000=0.4804 sub8000=0.4765 (34.9s)
n=5 rep=7 full=0.4917 sub2000=0.4968 sub8000=0.4965 (45.0s)
n=5 rep=8 full=0.4952 sub2000=0.5003 sub8000=0.4941 (61.9s)
n=5 rep=9 full=0.5105 sub2000=0.4913 sub8000=0.5075 (55.9s)
n=5 rep=10 full=0.3944 sub2000=0.4027 sub8000=0.3876 (68.2s)
n=5 rep=11 full=0.5260 sub2000=0.5280 sub8000=0.5241 (59.9s)
n=25 rep=0 full=0.6409 sub2000=0.6401 sub8000=0.6376 (68.6s)
n=25 rep=1 full=0.6462 sub2000=0.6543 sub8000=0.6498 (61.2s)
n=25 rep=2 full=0.6050 sub2000=0.6000 sub8000=0.6003 (91.6s)
n=25 rep=3 full=0.6219 sub2000=0.6287 sub8000=0.6204 (64.1s)
n=25 rep=4 full=0.6077 sub2000=0.6013 sub8000=0.5991 (52.0s)
n=25 rep=5 full=0.6520 sub2000=0.6490 sub8000=0.6513 (23.6s)
n=25 rep=6 full=0.6535 sub2000=0.6631 sub8000=0.6554 (24.5s)
n=25 rep=7 full=0.6382 sub2000=0.6300 sub8000=0.6365 (27.0s)
n=25 rep=8 full=0.6443 sub2000=0.6365 sub8000=0.6375 (25.4s)
n=25 rep=9 full=0.6337 sub2000=0.6472 sub8000=0.6351 (28.9s)
n=25 rep=10 full=0.6329 sub2000=0.6127 sub8000=0.6243 (28.2s)
n=25 rep=11 full=0.6569 sub2000=0.6490 sub8000=0.6537 (28.2s)
n=50 rep=0 full=0.6880 sub2000=0.6817 sub8000=0.6822 (31.1s)
n=50 rep=1 full=0.6869 sub2000=0.6816 sub8000=0.6806 (38.5s)
n=50 rep=2 full=0.6762 sub2000=0.6843 sub8000=0.6777 (46.1s)
n=50 rep=3 full=0.6752 sub2000=0.6593 sub8000=0.6707 (45.4s)
n=50 rep=4 full=0.6800 sub2000=0.6797 sub8000=0.6781 (45.5s)
n=50 rep=5 full=0.6745 sub2000=0.6656 sub8000=0.6650 (46.3s)
n=50 rep=6 full=0.6507 sub2000=0.6473 sub8000=0.6467 (45.0s)
n=50 rep=7 full=0.6476 sub2000=0.6530 sub8000=0.6467 (45.8s)
n=50 rep=8 full=0.6857 sub2000=0.6787 sub8000=0.6853 (43.8s)
n=50 rep=9 full=0.6659 sub2000=0.6645 sub8000=0.6624 (44.9s)
n=50 rep=10 full=0.6831 sub2000=0.6853 sub8000=0.6775 (45.5s)
n=50 rep=11 full=0.6655 sub2000=0.6668 sub8000=0.6609 (45.4s)
n=100 rep=0 full=0.6957 sub2000=0.6912 sub8000=0.6886 (45.2s)
n=100 rep=1 full=0.7032 sub2000=0.6992 sub8000=0.6970 (44.2s)
n=100 rep=2 full=0.6996 sub2000=0.6893 sub8000=0.6922 (44.7s)
n=100 rep=3 full=0.7157 sub2000=0.7004 sub8000=0.7070 (44.9s)
n=100 rep=4 full=0.7103 sub2000=0.7030 sub8000=0.7040 (44.4s)
n=100 rep=5 full=0.6970 sub2000=0.6889 sub8000=0.6917 (43.7s)
n=100 rep=6 full=0.7016 sub2000=0.6977 sub8000=0.6958 (45.0s)
n=100 rep=7 full=0.6994 sub2000=0.6928 sub8000=0.6972 (43.7s)
n=100 rep=8 full=0.6992 sub2000=0.6888 sub8000=0.6941 (44.4s)
n=100 rep=9 full=0.6925 sub2000=0.6901 sub8000=0.6895 (44.8s)
n=100 rep=10 full=0.7088 sub2000=0.6897 sub8000=0.7042 (43.5s)
n=100 rep=11 full=0.7054 sub2000=0.6914 sub8000=0.6997 (45.0s)
n=200 rep=0 full=0.7126 sub2000=0.7085 sub8000=0.7088 (48.2s)
n=200 rep=1 full=0.7123 sub2000=0.7040 sub8000=0.7098 (41.2s)
n=200 rep=2 full=0.7101 sub2000=0.7072 sub8000=0.7028 (41.1s)
n=200 rep=3 full=0.7139 sub2000=0.7087 sub8000=0.7079 (41.4s)
n=200 rep=4 full=0.7186 sub2000=0.7081 sub8000=0.7117 (41.4s)
n=200 rep=5 full=0.7159 sub2000=0.7095 sub8000=0.7095 (40.9s)
n=200 rep=6 full=0.7208 sub2000=0.7009 sub8000=0.7113 (41.2s)
n=200 rep=7 full=0.7118 sub2000=0.7100 sub8000=0.7066 (43.7s)
n=200 rep=8 full=0.7150 sub2000=0.7057 sub8000=0.7080 (42.9s)
n=200 rep=9 full=0.7125 sub2000=0.6946 sub8000=0.7067 (42.9s)
prototype, robust z + within-class Mahalanobis: 393 features, dead ['has_early_data', 'sat_share_oli_early'], Madrid (76263, 393), Amsterdam (25992, 393)
resuming: 58 draws already saved
n=200 rep=10 full=0.7141 sub2000=0.7105 sub8000=0.7106 (28.6s)
n=200 rep=11 full=0.7113 sub2000=0.7121 sub8000=0.7086 (32.9s)
full sub2000 sub8000
5 0.5040 0.5021 0.5025
25 0.6361 0.6343 0.6334
50 0.6733 0.6706 0.6695
100 0.7023 0.6935 0.6967
200 0.7141 0.7067 0.7085
full average 0.6460 peak 0.7141
sub2000 average 0.6414 peak 0.7067
sub8000 average 0.6421 peak 0.7085
done in 1.0 min12345678910111213141516171819202122232425262728293031323334353637upweighted shots, retrained: 393 features, dead ['has_early_data', 'sat_share_oli_early'], Madrid (76263, 393), Amsterdam (25992, 393)
n=5 rep=0 full=0.5658 sub2000=0.5750 sub8000=0.5632 (74.1s)
n=5 rep=1 full=0.5755 sub2000=0.5756 sub8000=0.5699 (51.6s)
n=5 rep=2 full=0.5476 sub2000=0.5483 sub8000=0.5430 (50.4s)
n=5 rep=3 full=0.5685 sub2000=0.5612 sub8000=0.5622 (116.9s)
n=5 rep=4 full=0.5714 sub2000=0.5698 sub8000=0.5664 (179.8s)
n=25 rep=0 full=0.6303 sub2000=0.6323 sub8000=0.6322 (161.0s)
n=25 rep=1 full=0.6185 sub2000=0.6252 sub8000=0.6161 (252.8s)
n=25 rep=2 full=0.6265 sub2000=0.6143 sub8000=0.6197 (46.6s)
n=25 rep=3 full=0.6478 sub2000=0.6529 sub8000=0.6452 (46.6s)
n=25 rep=4 full=0.6188 sub2000=0.6208 sub8000=0.6165 (49.6s)
n=50 rep=0 full=0.6658 sub2000=0.6693 sub8000=0.6587 (50.7s)
n=50 rep=1 full=0.6741 sub2000=0.6748 sub8000=0.6708 (75.8s)
n=50 rep=2 full=0.6786 sub2000=0.6779 sub8000=0.6807 (79.3s)
n=50 rep=3 full=0.6734 sub2000=0.6654 sub8000=0.6671 (75.8s)
n=50 rep=4 full=0.6565 sub2000=0.6573 sub8000=0.6545 (75.8s)
n=100 rep=0 full=0.7016 sub2000=0.7054 sub8000=0.6992 (75.6s)
n=100 rep=1 full=0.6985 sub2000=0.6901 sub8000=0.6933 (71.3s)
n=100 rep=2 full=0.6914 sub2000=0.6965 sub8000=0.6913 (69.3s)
n=100 rep=3 full=0.6990 sub2000=0.6979 sub8000=0.6952 (70.0s)
n=100 rep=4 full=0.6961 sub2000=0.6907 sub8000=0.6952 (69.8s)
n=200 rep=0 full=0.7265 sub2000=0.7356 sub8000=0.7245 (71.0s)
n=200 rep=1 full=0.7125 sub2000=0.7080 sub8000=0.7114 (70.1s)
n=200 rep=2 full=0.7180 sub2000=0.7149 sub8000=0.7155 (70.4s)
n=200 rep=3 full=0.7184 sub2000=0.7239 sub8000=0.7175 (75.8s)
n=200 rep=4 full=0.7265 sub2000=0.7327 sub8000=0.7220 (78.8s)
full sub2000 sub8000
5 0.5658 0.5660 0.5609
25 0.6284 0.6291 0.6259
50 0.6697 0.6690 0.6664
100 0.6973 0.6961 0.6949
200 0.7204 0.7230 0.7182
full average 0.6563 peak 0.7204
sub2000 average 0.6566 peak 0.7230
sub8000 average 0.6533 peak 0.7182
done in 35.2 min12345678910111213141516171819202122232425262728293031retrieval + Madrid rule,+ bias recalibration,+ tuned decision weights,ensemble LLM 0.3 / LightGBM 0.7,ensemble LLM 0.5 / LightGBM 0.5,ensemble LLM 0.7 / LightGBM 0.3,n,rep
0.5202,,,0.5588,0.4828,0.4765,5,0
0.5224,,,0.5606,0.5846,0.5711,5,1
0.4924,,,0.5525,0.4872,0.5468,5,2
0.5195,,,0.5633,0.5763,0.5649,5,3
0.5161,,,0.5639,0.5792,0.5531,5,4
0.5133,,,0.5611,0.584,0.5702,5,5
0.5376,,,0.5646,0.4759,0.4775,25,0
0.5318,,,0.566,0.4687,0.4682,25,1
0.512,,,0.5646,0.4715,0.467,25,2
0.5243,,,0.5629,0.4745,0.4715,25,3
0.5027,,,0.5657,0.4795,0.4802,25,4
0.4961,,,0.5642,0.4832,0.4751,25,5
0.5797,0.4727,,0.5759,0.4745,0.4818,50,0
0.5193,0.497,,0.5684,0.4745,0.4682,50,1
0.528,0.5064,,0.5782,0.4817,0.4803,50,2
0.5238,0.4917,,0.5763,0.4689,0.4769,50,3
0.5595,0.5899,,0.5818,0.4852,0.4762,50,4
0.5162,0.4688,,0.5811,0.4666,0.4687,50,5
0.4982,0.4817,,0.5749,0.4791,0.478,100,0
0.5687,0.5728,,0.586,0.4863,0.4847,100,1
0.5367,0.4953,,0.5796,0.4813,0.4767,100,2
0.573,0.4902,,0.5801,0.4827,0.4762,100,3
0.541,0.5091,,0.5771,0.4797,0.4809,100,4
0.5777,0.63,,0.5826,0.4857,0.486,100,5
0.59,0.5981,0.6099,0.5831,0.4952,0.4947,200,0
0.5413,0.6088,0.6506,0.5849,0.4907,0.4939,200,1
0.5607,0.6105,0.594,0.5924,0.4812,0.4918,200,2
0.5432,0.571,0.6483,0.5828,0.4961,0.4915,200,3
0.5822,0.6088,0.5958,0.5815,0.4882,0.4841,200,4
0.5889,0.5985,0.6346,0.5836,0.4907,0.4887,200,51234567891011strategy,both,clean,covariate,label,delta_vs_argmax_mean,delta_vs_argmax_worst
argmax,0.4766277348013709,0.6055506844084575,0.5328959332264072,0.5391639540527374,0.0,0.0
em_free,0.3589397742522877,0.5312464491381202,0.37684760869683986,0.48997794293710095,-0.09930663286615615,-0.10786078556270207
em_pinned_shrunk,0.4406480520203647,0.5837780673295816,0.47917846504948114,0.5266926677475531,-0.030985263585498135,-0.033297506683739375
em_shrunk,0.45634006963730467,0.5894954166977777,0.4964833569867393,0.5314349516494004,-0.02012112787943776,-0.006301657202695876
logit_adj_tau0.25,0.4802725787074079,0.6092793116373957,0.5368932017851271,0.5438140379788996,0.004005205904964226,0.0010334968999556327
logit_adj_tau0.5,0.48188297075609177,0.6101659145541751,0.5392044403543397,0.54686169194163,0.005969177779315826,0.0014135450449920817
logit_adj_tau1.0,0.48058168514340693,0.6067736712706344,0.5350619082752373,0.5477426130512237,0.003980392812882316,0.01562759837422195
plugin_srcprior,0.48850202153623157,0.6143242551861514,0.5523741536954043,0.5459945788738292,0.011739175700660853,0.021085184321292028
tau0.5_em_plugin,0.46927968168607403,0.6029738936298857,0.5211543503419801,0.5427893252057969,-0.004510263906309153,0.015860548689450027
tau0.5_then_plugin,0.4888571435470125,0.6133924481265582,0.5530570356897002,0.547176443156529,0.01206119100770664,0.02671852147426451123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111"""Shared configuration for the Building-Age-Classification hackathon(Madrid -> Amsterdam transfer).
Everything that both the GBDT track and the LLM track need lives here so thetwo never disagree about class boundaries, feature names or file paths."""from __future__ import annotations
import osfrom pathlib import Path
# --------------------------------------------------------------------------- ## 1. Paths (work on a laptop, on Kaggle and on Colab without edits)# --------------------------------------------------------------------------- #
def _detect_platform() -> str: if os.path.exists("/kaggle/working"): return "kaggle" try: # noqa: SIM105 import google.colab # noqa: F401 return "colab" except Exception: return "local"
PLATFORM = _detect_platform()
if PLATFORM == "kaggle": PROJECT_ROOT = Path("/kaggle/working") DATA_DIR = Path("/kaggle/input") # the attached dataset lives hereelif PLATFORM == "colab": PROJECT_ROOT = Path("/content/hack4dev") DATA_DIR = PROJECT_ROOT / "data"else: PROJECT_ROOT = Path(__file__).resolve().parent.parent DATA_DIR = PROJECT_ROOT / "data"
RAW_DIR = DATA_DIR / "raw"PROC_DIR = DATA_DIR / "processed"REPORT_DIR = PROJECT_ROOT / "results" # "reports" in the original projectfor _d in (PROC_DIR, REPORT_DIR): try: _d.mkdir(parents=True, exist_ok=True) except Exception: pass
RANDOM_SEED = 42
# --------------------------------------------------------------------------- ## Hugging Face settings for the LLM track (notebooks 2, 4, 5). That track is# not part of this release; nothing here uses these names.# --------------------------------------------------------------------------- #HF_USER = os.environ.get("HF_USER", "Karar-git")DATASET_REPO = f"{HF_USER}/building-age-prompts"MODEL_REPO_PREFIX = f"{HF_USER}/"
def hf_ready() -> bool: return bool(HF_USER) and HF_USER != "YOUR_HF_USERNAME"
# --------------------------------------------------------------------------- ## 2. The task definition (from the organisers' Notebook 1 / 3)# --------------------------------------------------------------------------- #
BASE_BANDS = ["Blue", "Green", "Red", "NIR", "SWIR1", "SWIR2"]INDEX_COLS = ["NDVI", "NDBI", "UI", "MNDWI", "BSI"]
# Landsat Collection-2 Level-2 surface-reflectance scaling: SR = DN*2.75e-5 - 0.2SR_SCALE, SR_OFFSET = 2.75e-5, -0.2
BLUE_MAX = 15_000 # haze threshold from the organisers' Notebook 2EARLY_CUTOFF = 2003 # early period = 1984..2003LATE_START = 2004 # late period = 2004..PID = ["px_key", "py_key"]
# City-specific boundary between class 1 and class 2CLASS_EVENTS = {"Amsterdam": 1945, "Madrid": 1960}
CLASS_LABELS = { "Amsterdam": {1: "before 1945", 2: "1945-1984", 3: "1984-2004", 4: "2004-2024"}, "Madrid": {1: "before 1960", 2: "1960-1984", 3: "1984-2004", 4: "2004-2024"},}
# Published class shares (organisers' guide) - used only for sanity checks,# never to fit anything.PUBLISHED_SHARES = {"Madrid": {2: 0.356}, "Amsterdam": {4: 0.111}}
# --------------------------------------------------------------------------- ## 3. The official 60 features, in the official order# --------------------------------------------------------------------------- #
FEAT_OVERALL = [f"{b}_mean" for b in BASE_BANDS] + [f"{b}_std" for b in BASE_BANDS]FEAT_INDICES = [f"{i}_mean" for i in INDEX_COLS] + [f"{i}_std" for i in INDEX_COLS]FEAT_EARLY = [f"{b}_early_mean" for b in BASE_BANDS] + [f"{b}_early_std" for b in BASE_BANDS]FEAT_LATE = [f"{b}_late_mean" for b in BASE_BANDS] + [f"{b}_late_std" for b in BASE_BANDS]FEAT_YOY = [f"d_{b}_mean" for b in BASE_BANDS] + [f"d_{b}_std" for b in BASE_BANDS]FEAT_IND = ["has_early_data", "has_late_data"]
FEATURE_COLS_60 = FEAT_OVERALL + FEAT_INDICES + FEAT_EARLY + FEAT_LATE + FEAT_YOY + FEAT_IND
FEAT_GROUPS_60 = { "overall": FEAT_OVERALL, "indices": FEAT_INDICES, "early": FEAT_EARLY, "late": FEAT_LATE, "yoy": FEAT_YOY, "indicators": FEAT_IND,}
assert len(FEATURE_COLS_60) == 60, len(FEATURE_COLS_60)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519"""The official evaluation protocol, plus the decision-rule and prior-shift toolsthat every model in this project shares.
Protocol (organisers' Notebook 1, section 1.5): 1. train a Stage-1 model on Madrid only; 2. adapt it with n labelled Amsterdam pixels per class, n in {5,25,50,100,200}; 3. score macro F1 on the *rest* of Amsterdam; 4. repeat over many random draws and report mean +- std for every n.
`modelCreate` is any callable with this signature:
predict_proba_fn = model_create( X_src, y_src, # Madrid, labelled X_tgt_unlabelled, # all target features, NO labels X_shot, y_shot, # the n-per-class labelled target sample )
and must return a function mapping X -> (n, 4) probabilities. Keeping it aclosure means every adaptation trick (recalibration, prototypes, continuedboosting, retrieval prompts) fits the same harness."""from __future__ import annotations
import numpy as npfrom sklearn.metrics import confusion_matrix, f1_score
CLASSES = np.array([1, 2, 3, 4])
# --------------------------------------------------------------------------- ## Metrics# --------------------------------------------------------------------------- #def macro_f1(y_true, y_pred) -> float: return float(f1_score(y_true, y_pred, labels=CLASSES, average="macro", zero_division=0))
def per_class_f1(y_true, y_pred) -> np.ndarray: return f1_score(y_true, y_pred, labels=CLASSES, average=None, zero_division=0)
def confusion_proportions(y_true, y_pred) -> np.ndarray: cm = confusion_matrix(y_true, y_pred, labels=CLASSES).astype(float) return cm / np.clip(cm.sum(axis=1, keepdims=True), 1, None)
# --------------------------------------------------------------------------- ## Decision rules. argmax is NOT the macro-F1 optimum.# --------------------------------------------------------------------------- #def predict_weighted(proba: np.ndarray, weights: np.ndarray) -> np.ndarray: """argmax of w_k * p_k -> class label.""" return CLASSES[np.argmax(proba * np.asarray(weights, dtype=float), axis=1)]
def macro_f1_weighted(y_true, y_pred, sample_weight=None) -> float: """ Macro F1 computed from a *weighted* confusion matrix.
This exists because the few-shot sample is drawn n-per-class: on it, a rare class looks far more precise than it really is, so tuning a decision rule on the raw sample over-predicts rare classes. Feeding `gbdt.stratification_weights(...)` here makes the estimate behave like macro F1 on a random sample of the city, using only legal information. """ y_true = np.asarray(y_true) y_pred = np.asarray(y_pred) w = np.ones(len(y_true)) if sample_weight is None else np.asarray(sample_weight, float) f1s = [] for c in CLASSES: tp = w[(y_true == c) & (y_pred == c)].sum() fp = w[(y_true != c) & (y_pred == c)].sum() fn = w[(y_true == c) & (y_pred != c)].sum() denom = 2 * tp + fp + fn f1s.append(0.0 if denom <= 0 else 2 * tp / denom) return float(np.mean(f1s))
def tune_class_weights(proba: np.ndarray, y_true, n_rounds: int = 6, grid=None, sample_weight=None, shrink: float = 0.0) -> np.ndarray: """ Coordinate ascent on per-class multipliers to maximise macro F1.
Fit this on a validation split of the TRAINING city, or on the labelled few-shot sample - never on the full target labels.
shrink: pull the result back towards 1 (no adjustment). With only 20 labelled rows (n=5 per class) the search overfits, so shrink hard; with 800 rows it can be left at 0. """ if grid is None: grid = np.exp(np.linspace(np.log(0.25), np.log(4.0), 25)) w = np.ones(4) score = lambda ww: macro_f1_weighted(y_true, predict_weighted(proba, ww), # noqa: E731 sample_weight) best = score(w) for _ in range(n_rounds): improved = False for k in range(4): cur = w[k] for g in grid: w[k] = g s = score(w) if s > best + 1e-6: best, cur, improved = s, g, True w[k] = cur if not improved: break w = w / w.mean() if shrink > 0: w = np.exp((1 - shrink) * np.log(w)) return w / w.mean()
def prior_correct(proba: np.ndarray, train_prior: np.ndarray, target_prior: np.ndarray) -> np.ndarray: """Re-weight probabilities from one class prior to another (label shift).""" adj = proba * (np.asarray(target_prior) / np.asarray(train_prior))[None, :] return adj / np.clip(adj.sum(axis=1, keepdims=True), 1e-12, None)
def em_target_prior(proba: np.ndarray, train_prior: np.ndarray, n_iter: int = 200, tol: float = 1e-7, pin: dict | None = None, shrink: float = 0.0) -> np.ndarray: """ Saerens-Latinne-Decaestecker EM estimate of the target class prior from UNLABELLED target probabilities. Uses X_amsterdam only - no labels - so it stays inside the rules, but it only works if the model is roughly calibrated.
pin: fix some class shares to known values and renormalise the rest, e.g. {4: 0.111} - the organisers publish Amsterdam's class-4 share in the competitors' guide, so pinning it is citable, not leakage. Pinning also bounds the failure mode where EM drives a class to zero. shrink: pull the estimate back towards the training prior, q = (1-shrink)*q_EM + shrink*train_prior. EM is confident and frequently wrong under covariate shift; 0.5-0.7 is a sane default and should be chosen on the simulated-shift harness. """ train_prior = np.asarray(train_prior, dtype=float) train_prior = train_prior / train_prior.sum()
def apply_pin(p): if not pin: return p / p.sum() p = p.copy() free = [k for k in range(4) if (k + 1) not in pin] fixed_mass = sum(pin.values()) for c, v in pin.items(): p[c - 1] = v rest = p[free].sum() if rest > 0: p[free] *= (1.0 - fixed_mass) / rest else: p[free] = (1.0 - fixed_mass) / max(len(free), 1) return p
prior = apply_pin(train_prior.copy()) for _ in range(n_iter): post = proba * (prior / train_prior)[None, :] post /= np.clip(post.sum(axis=1, keepdims=True), 1e-12, None) new = apply_pin(post.mean(axis=0)) if np.max(np.abs(new - prior)) < tol: prior = new break prior = new if shrink > 0: prior = apply_pin((1 - shrink) * prior + shrink * train_prior) return prior
def logit_adjust(proba: np.ndarray, train_prior: np.ndarray, tau: float = 0.4) -> np.ndarray: """ tau-scaled logit adjustment (Menon et al. 2021): divide by the training prior raised to tau.
tau = 1 is Fisher-consistent for *balanced error rate*, i.e. macro RECALL. Macro F1 is a different metric and punishes over-predicting a rare class, so its optimum sits lower - tune tau on training-city CV and expect 0.25-0.5. Leaving tau at 1.0 reliably loses macro F1 here. """ p = np.asarray(proba, dtype=float) tp = np.asarray(train_prior, dtype=float) adj = p / np.clip(tp, 1e-12, None) ** float(tau) return adj / np.clip(adj.sum(axis=1, keepdims=True), 1e-12, None)
def macro_f1_plugin(proba: np.ndarray, prior: np.ndarray, n_iter: int = 50): """ The plug-in decision rule for macro F1 (Ramaswamy et al., "Consistent algorithms for multiclass F-measures").
argmax of a calibrated posterior maximises accuracy, not macro F1. The macro-F1-optimal rule is predict argmax_k a_k * (p_k(x) - F1_k / 2), a_k = 2 / (pi_k + q_k) where q_k is the predicted share of class k and F1_k the resulting per-class F1 - so it is a fixed point, solved by iteration. It needs the probabilities and a prior estimate, and NO target labels, which is why it is the right tool here.
Returns (labels, diagnostics). """ P = np.asarray(proba, dtype=float) pi = np.asarray(prior, dtype=float) pi = pi / pi.sum() f1 = np.zeros(4) best = None for it in range(n_iter): q = np.clip(np.bincount(np.argmax(P, axis=1), minlength=4) / len(P), 1e-6, None) \ if it == 0 else q_new a = 2.0 / np.clip(pi + q, 1e-9, None) score = a[None, :] * (P - f1[None, :] / 2.0) lab_idx = np.argmax(score, axis=1) q_new = np.clip(np.bincount(lab_idx, minlength=4) / len(P), 1e-6, None) # soft per-class F1 implied by the current assignment and the posterior tp = np.array([P[lab_idx == k, k].sum() for k in range(4)]) / len(P) f1_new = 2 * tp / np.clip(pi + q_new, 1e-9, None) obj = float(np.mean(f1_new)) if best is None or obj > best[0]: best = (obj, CLASSES[lab_idx].copy(), q_new.copy(), f1_new.copy()) if np.max(np.abs(f1_new - f1)) < 1e-6 and it > 0: f1 = f1_new break f1 = f1_new obj, labels, q, f1 = best return labels, dict(expected_macro_f1=obj, predicted_share=q, per_class_f1=f1)
def adapt_pipeline(proba, src_prior, pin=None, tau: float = 0.5, shrink: float = 0.7, use_em: bool = False, use_plugin: bool = True): """ The label-free adaptation chain: tau-logit-adjust -> (optional prior re-estimation) -> macro-F1 plug-in.
`use_em` defaults to FALSE on purpose. On the simulated-shift harness, free SLD-EM was the worst thing tested: under covariate shift it drove the prior to [0.85, 0.10, 0.04, 0.02] against a truth of [0.34, 0.32, 0.22, 0.11] and cost 0.19 macro F1 on average, 0.35 at worst. Pinning class 4 at the published 0.111 and shrinking hard towards the source prior bounds the damage but does not repair it: EM assumes pure label shift, and this problem has a large covariate shift on top. Re-run `shift_harness` on the real Madrid features before turning it on.
What survived the harness: tau-logit-adjustment at tau = 0.25-0.5 (small but positive in every regime) and the macro-F1 plug-in rule driven by the SOURCE prior (+0.033 mean, +0.038 worst case). """ src_prior = np.asarray(src_prior, dtype=float) src_prior = src_prior / src_prior.sum() p = logit_adjust(proba, src_prior, tau=tau) if tau else np.asarray(proba, float) prior = src_prior if use_em: prior = em_target_prior(p, src_prior, pin=pin, shrink=shrink) p = prior_correct(p, src_prior, prior) if use_plugin: labels, diag = macro_f1_plugin(p, prior) else: labels, diag = CLASSES[np.argmax(p, axis=1)], {} diag["prior_used"] = prior return labels, p, diag
# --------------------------------------------------------------------------- ## Spatial smoothing (stage 2): neighbouring pixels share a construction era# --------------------------------------------------------------------------- #def spatial_smooth(proba: np.ndarray, coords: np.ndarray, radius: float = 4.0, alpha: float = 0.5, n_iter: int = 1) -> np.ndarray: """ Blend each pixel's probabilities with a Gaussian-weighted average of its neighbours: p <- (1-alpha) * p + alpha * mean_neighbours(p). `radius` is in pixel units (1 unit = 30 m). Choose it on Madrid only. """ from sklearn.neighbors import NearestNeighbors
coords = np.asarray(coords, dtype=float) nn = NearestNeighbors(radius=radius * 2.0).fit(coords) dist, idx = nn.radius_neighbors(coords, radius=radius * 2.0) out = proba.copy() for _ in range(n_iter): nxt = out.copy() for i, (d, j) in enumerate(zip(dist, idx)): if len(j) <= 1: continue w = np.exp(-0.5 * (d / radius) ** 2) keep = j != i if not keep.any(): continue avg = np.average(out[j[keep]], axis=0, weights=w[keep]) nxt[i] = (1 - alpha) * out[i] + alpha * avg out = nxt / np.clip(nxt.sum(axis=1, keepdims=True), 1e-12, None) return out
# --------------------------------------------------------------------------- ## The protocol harness# --------------------------------------------------------------------------- #def draw_shots(y_tgt, n_per_class: int, rng) -> np.ndarray: """Indices of a stratified n-per-class sample of the target city.""" picks = [] for c in CLASSES: pool = np.flatnonzero(np.asarray(y_tgt) == c) if len(pool) == 0: continue take = min(n_per_class, len(pool)) picks.append(rng.choice(pool, size=take, replace=False)) return np.concatenate(picks)
def evaluate_protocol(model_create, X_src, y_src, X_tgt, y_tgt, n_list=(5, 25, 50, 100, 200), n_repeats: int = 20, seed: int = 42, decision="argmax", verbose: bool = True, eval_subsample: int | None = None): """ Run the official few-shot protocol and return {n: {"scores": [...], "mean": float, "std": float, "per_class": array}}.
`y_tgt` is touched ONLY here: to draw the n-per-class sample that the rules allow, and to score the held-out remainder. No tuning may read it. """ X_src, y_src = np.asarray(X_src), np.asarray(y_src) X_tgt, y_tgt = np.asarray(X_tgt), np.asarray(y_tgt)
# One FIXED evaluation subsample, shared by every n and every repeat. # # Scoring all 25,992 target rows on every one of 100 draws costs about 19 # seconds a draw for a 1200-tree LightGBM over ~390 features - 32 minutes # per variant, hours for a table. A fixed subsample cuts that and is also a # better experiment: the +- then reflects only the draw of the labelled # sample, and every variant is compared on identical pixels. It is a plain # random sample, so it keeps the target city's real class proportions, # which is what macro F1 must be measured against. eval_pool = np.arange(len(y_tgt)) if eval_subsample and eval_subsample < len(y_tgt): eval_pool = np.sort(np.random.default_rng(seed).choice( len(y_tgt), eval_subsample, replace=False))
results = {} pool_sizes = {int(c): int((y_tgt == c).sum()) for c in CLASSES} for n in n_list: short = {c: k for c, k in pool_sizes.items() if k <= n} if short: print(f" n={n}: only {short} pixels available in those classes - " "the draw is capped and the held-out remainder shrinks") scores, per_class = [], [] for r in range(n_repeats): rng = np.random.default_rng(seed + 1000 * n + r) shot_idx = draw_shots(y_tgt, n, rng) keep = np.setdiff1d(eval_pool, shot_idx, assume_unique=False) if len(keep) < 4 or len(np.unique(y_tgt[keep])) < 2: print(f" n={n} rep={r}: nothing left to score after drawing " "the sample - skipped") continue
fn = model_create(X_src, y_src, X_tgt, X_tgt[shot_idx], y_tgt[shot_idx]) proba = np.asarray(fn(X_tgt[keep]), dtype=float) mask = keep if callable(decision): pred = decision(proba) else: pred = CLASSES[np.argmax(proba, axis=1)] scores.append(macro_f1(y_tgt[mask], pred)) per_class.append(per_class_f1(y_tgt[mask], pred)) if not scores: results[n] = {"scores": np.array([]), "mean": float("nan"), "std": float("nan"), "per_class": np.full(4, np.nan)} continue results[n] = { "scores": np.array(scores), "mean": float(np.mean(scores)), "std": float(np.std(scores, ddof=1)) if len(scores) > 1 else 0.0, "per_class": np.mean(per_class, axis=0), } if verbose: print(f" n={n:<4d} macro F1 = {results[n]['mean']:.4f} " f"+- {results[n]['std']:.4f} per-class " f"{np.round(results[n]['per_class'], 3)}") return results
# --------------------------------------------------------------------------- ## The simulated-shift harness: choose every adaptation knob on MADRID only.## Nothing above can be tuned honestly without this. A step that helps under# pure label shift can lose 0.06-0.10 macro F1 under covariate shift, and# without a simulator there is no way to know which regime you are in.# --------------------------------------------------------------------------- #def resample_to_prior(y, prior, rng, n: int | None = None) -> np.ndarray: """Indices of a subsample of `y` whose class shares match `prior`.""" y = np.asarray(y) prior = np.asarray(prior, dtype=float) prior = prior / prior.sum() pools = {c: np.flatnonzero(y == c) for c in CLASSES} if n is None: n = int(min(len(pools[c]) / prior[i] for i, c in enumerate(CLASSES) if prior[i] > 0 and len(pools[c]))) picks = [] for i, c in enumerate(CLASSES): k = int(round(prior[i] * n)) if k and len(pools[c]): picks.append(rng.choice(pools[c], size=min(k, len(pools[c])), replace=False)) return np.concatenate(picks) if picks else np.array([], dtype=int)
def match_marginals(X_fold, X_src, X_tgt, strength: float = 1.0) -> np.ndarray: """ Quantile-map each column of `X_fold` from the source city's marginal onto the target city's marginal. Uses X_amsterdam features only, so it is legal, and it turns a held-out Madrid fold into a stand-in for Amsterdam that keeps its true labels. """ X_fold = np.asarray(X_fold, dtype=float) qs = np.linspace(0, 100, 201) gs = np.percentile(np.asarray(X_src, float), qs, axis=0) gt = np.percentile(np.asarray(X_tgt, float), qs, axis=0) out = np.empty_like(X_fold) for j in range(X_fold.shape[1]): r = np.interp(X_fold[:, j], gs[:, j], qs, left=0.0, right=100.0) out[:, j] = np.interp(r, qs, gt[:, j]) return X_fold + strength * (out - X_fold)
def shift_harness(fit_fn, X, y, blocks, X_tgt, strategies: dict, n_folds: int = 5, n_rep: int = 4, seed: int = 0, verbose: bool = True): """ For each held-out spatial block, build three versions of it: "clean" - as-is (no shift), "label" - resampled to a random Dirichlet class prior, "covariate" - feature marginals mapped onto the target city, "both" - label shift and covariate shift together, then score every decision strategy on each. A strategy is `fn(proba, src_prior) -> labels`.
Returns a DataFrame of mean and worst-case macro F1 per (strategy, regime). Ship only the strategies that are non-negative in the WORST case. """ import pandas as pd
X, y = np.asarray(X, float), np.asarray(y) uniq = np.unique(blocks) rng0 = np.random.default_rng(seed) folds = np.array_split(rng0.permutation(uniq), n_folds) rows = [] for fi, f in enumerate(folds): te = np.isin(blocks, f) tr = ~te model = fit_fn(X[tr], y[tr]) src_prior = np.array([(y[tr] == c).mean() for c in CLASSES]) Xte_clean = X[te] Xte_cov = match_marginals(Xte_clean, X[tr], X_tgt) for rep in range(n_rep): rng = np.random.default_rng(seed + 100 * fi + rep) alpha = rng.dirichlet(np.ones(4) * 1.5) sel_lab = resample_to_prior(y[te], alpha, rng) regimes = { "clean": (Xte_clean, y[te]), "label": (Xte_clean[sel_lab], y[te][sel_lab]), "covariate": (Xte_cov, y[te]), "both": (Xte_cov[sel_lab], y[te][sel_lab]), } for rname, (Xr, yr) in regimes.items(): if len(yr) == 0: continue proba = model.predict_proba(Xr) for sname, fn in strategies.items(): rows.append(dict(fold=fi, rep=rep, regime=rname, strategy=sname, macro_f1=macro_f1(yr, fn(proba, src_prior)))) df = pd.DataFrame(rows) piv = df.pivot_table(index="strategy", columns="regime", values="macro_f1", aggfunc="mean") worst = df.pivot_table(index="strategy", columns="regime", values="macro_f1", aggfunc="min") if "argmax" in piv.index: regimes_cols = list(piv.columns) piv["delta_vs_argmax_mean"] = (piv[regimes_cols].mean(axis=1) - piv.loc["argmax", regimes_cols].mean()) # PER-REGIME deltas, then the worst of them. The previous version took # each strategy's own worst cell anywhere and subtracted argmax's own # worst cell anywhere, which compares two different regimes - and two # different folds, since `worst` is a min over folds. A rule can then # look safe because its bad regime happens to be argmax's bad regime # too. What the decision actually needs is "in the regime where this # rule does worst RELATIVE to argmax, how much does it lose". dmean = piv[regimes_cols].sub(piv.loc["argmax", regimes_cols], axis=1) piv["delta_vs_argmax_worst_regime"] = dmean.min(axis=1) dworst = worst[regimes_cols].sub(worst.loc["argmax", regimes_cols], axis=1) piv["delta_vs_argmax_worst_fold"] = dworst.min(axis=1) if verbose: print(piv.round(4).to_string()) return df, piv
DEFAULT_STRATEGIES = { "argmax": lambda p, sp: CLASSES[np.argmax(p, axis=1)], "logit_adj_tau0.25": lambda p, sp: CLASSES[np.argmax(logit_adjust(p, sp, 0.25), 1)], "logit_adj_tau0.5": lambda p, sp: CLASSES[np.argmax(logit_adjust(p, sp, 0.5), 1)], "logit_adj_tau1.0": lambda p, sp: CLASSES[np.argmax(logit_adjust(p, sp, 1.0), 1)], "em_free": lambda p, sp: CLASSES[np.argmax( prior_correct(p, sp, em_target_prior(p, sp)), 1)], "em_shrunk": lambda p, sp: CLASSES[np.argmax( prior_correct(p, sp, em_target_prior(p, sp, shrink=0.7)), 1)], "em_pinned_shrunk": lambda p, sp: CLASSES[np.argmax( prior_correct(p, sp, em_target_prior(p, sp, pin={4: 0.111}, shrink=0.7)), 1)], "plugin_srcprior": lambda p, sp: macro_f1_plugin(p, sp)[0], "tau0.5_then_plugin": lambda p, sp: adapt_pipeline(p, sp, tau=0.5)[0], "tau0.5_em_plugin": lambda p, sp: adapt_pipeline(p, sp, tau=0.5, use_em=True, pin={4: 0.111}, shrink=0.7)[0],}
def summarise(results: dict) -> str: lines = ["| n per class | macro F1 | std |", "|---|---|---|"] for n, r in results.items(): lines.append(f"| {n} | {r['mean']:.4f} | {r['std']:.4f} |") means = [r["mean"] for r in results.values()] lines.append(f"\nAverage across n: {np.mean(means):.4f} peak: {np.max(means):.4f}") return "\n".join(lines)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634"""
Raw wide-format Landsat parquet -> one feature row per 30 m pixel.
Two feature sets come out of here:
* the OFFICIAL 60 - a faithful re-implementation of the organisers'
Notebook 3, so our numbers stay comparable with the published baseline;
* the EXTENDED set - physically scaled surface reflectance, correct spectral
indices, construction-event ("step") detection, per-decade means, trends
and early/late contrasts. This is what the LLM verbaliser and the strong
GBDT models actually use.
Everything is vectorised over a (n_pixels x n_years) matrix per band, so a whole
city is processed in a couple of minutes on a laptop CPU.
"""
from __future__ import annotations
import warnings
import numpy as np
import pandas as pd
from config import (BASE_BANDS, BLUE_MAX, CLASS_EVENTS, EARLY_CUTOFF,
FEATURE_COLS_60, INDEX_COLS, LATE_START, PID, SR_OFFSET,
SR_SCALE)
EPS = 1e-6
# --------------------------------------------------------------------------- #
# Stage 1 - load, label, flatten, gap-fill (official logic)
# --------------------------------------------------------------------------- #
def assign_age_class(df: pd.DataFrame) -> pd.DataFrame:
"""Bin weighted_mean_year into classes 1-4 with city-specific boundaries."""
out = df
out["age_class"] = pd.Series(pd.NA, index=out.index, dtype="Int64")
for city, ev in CLASS_EVENTS.items():
mask = (out["city"] == city).to_numpy()
if mask.any():
binned = pd.cut(out.loc[mask, "weighted_mean_year"],
bins=[-np.inf, ev, 1984, 2004, np.inf],
labels=[1, 2, 3, 4])
out.loc[mask, "age_class"] = binned.astype("Int64")
return out
def make_flat_view(df: pd.DataFrame, agg: str = "first") -> pd.DataFrame:
"""
One value per (pixel, year) per band; drop haze-contaminated rows.
agg="first" : the first QA-valid observation, exactly as the organisers do.
agg="median" : the median of all QA-valid observations in that year. With up
to three summer scenes per year, a single undetected thin
cloud moves a yearly value by more than any real surface
change, so the median is the more robust choice - use it for
our own features and keep "first" to reproduce the official
60 exactly.
"""
keep = [c for c in ["city", "year", "px_key", "py_key", "coverage",
"weighted_mean_year", "age_class"] if c in df.columns]
out = df[keep].copy()
n = len(df)
# Which satellite supplied the observation we end up using.
#
# This matters more than it looks. Reading scene_id (the dataset_* string
# column disagrees with it and is not to be trusted), the satellite chosen
# for a given year DIFFERS BETWEEN THE TWO CITIES in 11 of the 25 years
# from 2001 on: Madrid's late record is largely Landsat 7 ETM+, which has
# been SLC-off and striped since 2003, while Amsterdam's is largely
# Landsat 8/9 OLI. So part of any early-vs-late or year-to-year feature
# measures which instrument flew over, not what the building did - and that
# part is city-specific, which is the worst kind of nuisance here. Carrying
# the sensor through lets a model condition on it instead of confounding
# through it, and lets us measure how much it costs.
sat_code = np.zeros(n, dtype=np.int8) # 0 unknown, 1 TM, 2 ETM+, 3 OLI
_MAP = {"LT04": 1, "LT05": 1, "LE07": 2, "LC08": 3, "LC09": 3}
assigned = np.zeros(n, dtype=bool)
for slot in (1, 2, 3):
sc, qc = f"scene_id_{slot}", f"qa_valid_{slot}"
if sc not in df.columns or qc not in df.columns:
continue
valid = df[qc].fillna(False).to_numpy(dtype=bool)
codes = (df[sc].astype("string").str.slice(0, 4)
.map(_MAP).fillna(0).to_numpy(dtype=np.int8))
take = valid & ~assigned & (codes > 0)
sat_code[take] = codes[take]
assigned |= take
out["sat_code"] = sat_code
for band in BASE_BANDS:
if agg == "median":
stack = []
for slot in (1, 2, 3):
bc, qc = f"{band}_{slot}", f"qa_valid_{slot}"
if bc not in df.columns or qc not in df.columns:
continue
v = np.asarray(df[bc], dtype=np.float32).copy()
ok = df[qc].fillna(False).to_numpy(dtype=bool)
v[~ok] = np.nan
stack.append(v)
if stack:
with warnings.catch_warnings(): # all-NaN rows are expected
warnings.simplefilter("ignore", RuntimeWarning)
col = np.nanmedian(np.stack(stack), axis=0).astype(np.float32)
else:
col = np.full(n, np.nan, dtype=np.float32)
else:
col = np.full(n, np.nan, dtype=np.float32)
for slot in (1, 2, 3):
bc, qc = f"{band}_{slot}", f"qa_valid_{slot}"
if bc not in df.columns or qc not in df.columns:
continue
valid = df[qc].fillna(False).to_numpy(dtype=bool)
vals = np.asarray(df[bc], dtype=np.float32)
take = np.isnan(col) & valid & ~np.isnan(vals)
col[take] = vals[take]
out[band] = col
out = out.dropna(subset=BASE_BANDS)
before = len(out)
out = out[out["Blue"] <= BLUE_MAX]
removed = before - len(out)
if removed:
print(f" removed {removed:,} haze rows (Blue > {BLUE_MAX:,})")
return out
def period_coverage(flat: pd.DataFrame) -> pd.DataFrame:
"""has_early_data / has_late_data, computed on OBSERVED years (pre gap-fill)."""
pixels = flat[PID].drop_duplicates()
early = flat.loc[flat["year"] <= EARLY_CUTOFF, PID].drop_duplicates().assign(has_early_data=1.0)
late = flat.loc[flat["year"] >= LATE_START, PID].drop_duplicates().assign(has_late_data=1.0)
return (pixels.merge(early, on=PID, how="left")
.merge(late, on=PID, how="left")
.fillna({"has_early_data": 0.0, "has_late_data": 0.0}))
def to_year_matrices(flat: pd.DataFrame):
"""
Pivot the observed rows into one (n_pixels x n_years) matrix per band and
gap-fill exactly as the organisers do: linear interior, nearest at the edges.
Returns (pixel index DataFrame, years array, {band: matrix}, observed mask)
"""
years = np.arange(int(flat["year"].min()), int(flat["year"].max()) + 1)
pix = flat[PID].drop_duplicates().sort_values(PID).reset_index(drop=True)
pix_pos = pd.Series(np.arange(len(pix)), index=pd.MultiIndex.from_frame(pix))
ri = pix_pos.loc[pd.MultiIndex.from_frame(flat[PID])].to_numpy()
ci = (flat["year"].to_numpy() - years[0]).astype(np.int32)
mats = {}
observed = np.zeros((len(pix), len(years)), dtype=bool)
observed[ri, ci] = True
sat = np.zeros((len(pix), len(years)), dtype=np.int8)
if "sat_code" in flat.columns:
sat[ri, ci] = flat["sat_code"].to_numpy(dtype=np.int8)
for band in BASE_BANDS:
M = np.full((len(pix), len(years)), np.nan, dtype=np.float32)
M[ri, ci] = flat[band].to_numpy(dtype=np.float32)
M = (pd.DataFrame(M).interpolate(axis=1, method="linear")
.bfill(axis=1).ffill(axis=1).to_numpy(dtype=np.float32))
mats[band] = M
return pix, years, mats, observed, sat
# --------------------------------------------------------------------------- #
# Stage 2 - the official 60 features, from DN values
# --------------------------------------------------------------------------- #
def _indices_from(mats: dict) -> dict:
"""The organisers' five indices, exactly as their Notebook 3 defines them."""
B, G, R = mats["Blue"], mats["Green"], mats["Red"]
N, S1, S2 = mats["NIR"], mats["SWIR1"], mats["SWIR2"]
return {
"NDVI": (N - R) / (N + R + EPS),
"NDBI": (S1 - N) / (S1 + N + EPS),
"UI": (S2 - N) / (S2 + N + EPS),
"MNDWI": (G - S1) / (G + S1 + EPS),
"BSI": ((S1 + R) - (N + B)) / ((S1 + R) + (N + B) + EPS),
}
# Tasseled-cap coefficients for OLI surface reflectance (Baig et al. 2014).
# Wetness in particular separates impervious surfaces from soil better than
# any of the five indices above.
TC_COEF = {
"TCB": (0.3029, 0.2786, 0.4733, 0.5599, 0.5080, 0.1872),
"TCG": (-0.2941, -0.2430, -0.5424, 0.7276, 0.0713, -0.1608),
"TCW": (0.1511, 0.1973, 0.3283, 0.3407, -0.7117, -0.4559),
}
def _extra_indices_from(sr: dict) -> dict:
"""NBR, tasseled cap, and chromaticity (band / total brightness).
Chromaticity matters for transfer: dividing each band by the pixel's own
6-band sum removes albedo, illumination and the city-level brightness
offset entirely, and keeps only the spectral SHAPE.
"""
order = [sr[b] for b in BASE_BANDS]
total = sum(order) + EPS
out = {"NBR": (sr["NIR"] - sr["SWIR2"]) / (sr["NIR"] + sr["SWIR2"] + EPS)}
for name, coef in TC_COEF.items():
out[name] = sum(c * m for c, m in zip(coef, order))
for b in BASE_BANDS:
out[f"chrom{b}"] = sr[b] / total
return out
def _median_filter3(M: np.ndarray) -> np.ndarray:
"""
3-point running median along the time axis.
One undetected thin cloud moves a yearly value by more than any real
surface change, so the change detector runs on the filtered series while
the reported statistics stay on the raw one.
"""
a = np.pad(M, ((0, 0), (1, 1)), mode="edge")
return np.median(np.stack([a[:, :-2], a[:, 1:-1], a[:, 2:]]), axis=0)
def build_official_60(pix, years, mats, indicators) -> pd.DataFrame:
"""Reproduce the organisers' 60 features (DN units, ddof=1 std)."""
idx = _indices_from(mats)
early = years <= EARLY_CUTOFF
late = years >= LATE_START
out = {}
for b in BASE_BANDS:
M = mats[b]
out[f"{b}_mean"] = M.mean(1)
out[f"{b}_std"] = M.std(1, ddof=1)
out[f"{b}_early_mean"] = M[:, early].mean(1)
out[f"{b}_early_std"] = M[:, early].std(1, ddof=1)
out[f"{b}_late_mean"] = M[:, late].mean(1)
out[f"{b}_late_std"] = M[:, late].std(1, ddof=1)
D = np.diff(M, axis=1)
out[f"d_{b}_mean"] = D.mean(1)
out[f"d_{b}_std"] = D.std(1, ddof=1)
for i in INDEX_COLS:
out[f"{i}_mean"] = idx[i].mean(1)
out[f"{i}_std"] = idx[i].std(1, ddof=1)
df = pd.concat([pix, pd.DataFrame(out, index=pix.index)], axis=1)
df = df.merge(indicators, on=PID, how="left")
return df[PID + FEATURE_COLS_60]
# --------------------------------------------------------------------------- #
# Stage 3 - extended, physically-scaled features
# --------------------------------------------------------------------------- #
DECADES = [(1984, 1993), (1994, 2003), (2004, 2013), (2014, 2024)]
DECADE_TAGS = ["84_93", "94_03", "04_13", "14_24"]
STEP_SIGNALS = ["brightness", "SWIR1", "NDVI"]
def _slope_per_decade(M: np.ndarray, years: np.ndarray) -> np.ndarray:
"""OLS slope of each row against year, expressed per decade."""
t = (years - years.mean()).astype(np.float32)
denom = float((t * t).sum())
return (M * t).sum(1) / denom * 10.0
def _step_stats(M: np.ndarray, years: np.ndarray, win: int = 3):
"""
Construction-event detector. For every candidate break year, compare the
mean of the `win` years before with the mean of the `win` years after.
Returns (year of the largest absolute jump, signed size of that jump,
number of year-on-year jumps above 3 x MAD).
"""
n, T = M.shape
cs = np.concatenate([np.zeros((n, 1), np.float32),
np.cumsum(M, axis=1, dtype=np.float32)], axis=1)
def win_mean(a, b):
return (cs[:, b] - cs[:, a]) / np.float32(b - a)
cuts = np.arange(win, T - win + 1)
diffs = np.stack([win_mean(c, c + win) - win_mean(c - win, c) for c in cuts], axis=1)
# A two-sample t statistic, not just the raw difference.
#
# argmax over candidate years ALWAYS returns something, so a pixel that was
# never rebuilt still gets a "biggest step" - and inspection caught the
# verbaliser telling the model that a building from 1924 changed abruptly in
# 1998. What distinguishes a real construction event is the size of the step
# RELATIVE TO the scatter within the two windows being compared, which is
# exactly a t statistic. The earlier version divided by the scatter about
# the whole-series mean, which the step itself inflates, so it could not
# separate the two cases.
cs2 = np.concatenate([np.zeros((n, 1), np.float32),
np.cumsum(M.astype(np.float32) ** 2, axis=1, dtype=np.float32)],
axis=1)
def win_var(a, b):
k = np.float32(b - a)
mu = (cs[:, b] - cs[:, a]) / k
ex2 = (cs2[:, b] - cs2[:, a]) / k
return np.maximum(ex2 - mu * mu, 0.0) * (k / max(k - 1.0, 1.0))
tstats = np.empty_like(diffs)
for m_i, c in enumerate(cuts):
vb, va = win_var(c - win, c), win_var(c, c + win)
pooled = np.sqrt(np.maximum((vb + va) / 2.0, 0.0) * (2.0 / win)) + EPS
tstats[:, m_i] = diffs[:, m_i] / pooled
# The break year is chosen by the largest MAGNITUDE, not the largest t.
#
# Selecting on t was tried and was a disaster: Amsterdam's agreement with
# the true construction year fell from 69.4% within five years to 31.5%,
# and Madrid's from 44.6% to 28.3%. The t statistic is maximised wherever
# the pooled variance of a 3-year window happens to be near zero, which is
# noise, not a construction event. The magnitude is the signal.
#
# The t value at that same break is still reported as a feature, where it
# means "how large is this shift relative to the local scatter" and the
# trees can use it or ignore it. It is NOT used for any wording in the
# prompt - see the note in verbalize.render_prompt.
k = np.argmax(np.abs(diffs), axis=1)
rows = np.arange(n)
step_mag = diffs[rows, k]
step_t = np.abs(tstats[rows, k])
step_year = years[cuts[k]].astype(np.float32)
D = np.diff(M, axis=1)
mad = np.median(np.abs(D - np.median(D, axis=1, keepdims=True)), axis=1) + EPS
n_jumps = (np.abs(D) > (3.0 * mad[:, None])).sum(1).astype(np.float32)
return step_year, step_mag, n_jumps, step_t
SPIKE_SIGNALS = ["BSI", "SWIR1", "brightness"]
# Sensor eras. The early/late split at 2004 also straddles a change of
# atmospheric-correction algorithm (LEDAPS for TM/ETM+, LaSRC for OLI), and the
# artefact is latitude-dependent, so part of any early/late contrast measures
# which algorithm ran rather than what the building did. Splitting at the
# sensor boundary as well makes that confound explicit instead of hidden.
TM_ERA = (1984, 2011)
OLI_ERA = (2013, 2024)
SAT_NAMES = {1: "tm", 2: "etm", 3: "oli"}
def sensor_features(pix, years, observed, sat) -> dict:
"""
Per-pixel sensor composition: which instrument actually supplied each year.
Not a building property at all - which is the point. These columns let a
model absorb the sensor nuisance explicitly instead of attributing it to
building age, and they let us measure how much of the Madrid/Amsterdam gap
is instrument rather than architecture.
"""
early = years <= EARLY_CUTOFF
late = years >= LATE_START
out = {}
n_obs = np.clip(observed.sum(1), 1, None).astype(np.float32)
for code, nm in SAT_NAMES.items():
hit = (sat == code)
out[f"sat_share_{nm}"] = hit.sum(1) / n_obs
out[f"sat_share_{nm}_early"] = (hit & early[None, :]).sum(1) / np.clip(
(observed & early[None, :]).sum(1), 1, None)
out[f"sat_share_{nm}_late"] = (hit & late[None, :]).sum(1) / np.clip(
(observed & late[None, :]).sum(1), 1, None)
# how often the instrument changes from one observed year to the next
switches = np.zeros(len(sat), dtype=np.float32)
for i in range(sat.shape[0]):
s = sat[i][observed[i]]
s = s[s > 0]
if len(s) > 1:
switches[i] = float((s[1:] != s[:-1]).sum())
out["sat_switches"] = switches
return {k: np.asarray(v, dtype=np.float32) for k, v in out.items()}
def build_extended(pix, years, mats_dn, observed, sat=None) -> pd.DataFrame:
"""Surface-reflectance features: correct indices, trends, steps, decades."""
sr = {b: mats_dn[b] * np.float32(SR_SCALE) + np.float32(SR_OFFSET)
for b in BASE_BANDS}
idx = _indices_from(sr)
extra = _extra_indices_from(sr)
bright = np.mean(np.stack([sr[b] for b in BASE_BANDS]), axis=0, dtype=np.float32)
signals = {"brightness": bright}
signals.update(sr)
signals.update(idx)
signals.update(extra)
early = years <= EARLY_CUTOFF
late = years >= LATE_START
tm = (years >= TM_ERA[0]) & (years <= TM_ERA[1])
oli = (years >= OLI_ERA[0]) & (years <= OLI_ERA[1])
out = {}
# Full statistics for the signals worth the columns; a short set for the
# chromaticity and tasseled-cap extras, to keep the table manageable.
rich = {"brightness", *BASE_BANDS, *INDEX_COLS}
for name, M in signals.items():
out[f"sr_{name}_mean"] = M.mean(1)
out[f"sr_{name}_std"] = M.std(1, ddof=1)
out[f"sr_{name}_early_mean"] = M[:, early].mean(1)
out[f"sr_{name}_late_mean"] = M[:, late].mean(1)
out[f"sr_{name}_late_minus_early"] = (out[f"sr_{name}_late_mean"]
- out[f"sr_{name}_early_mean"])
# std scales with brightness, so a raw std is partly a city marker;
# the coefficient of variation is not.
out[f"sr_{name}_cv"] = out[f"sr_{name}_std"] / (np.abs(out[f"sr_{name}_mean"]) + EPS)
if name not in rich:
continue
out[f"sr_{name}_early_std"] = M[:, early].std(1, ddof=1)
out[f"sr_{name}_late_std"] = M[:, late].std(1, ddof=1)
out[f"sr_{name}_slope_decade"] = _slope_per_decade(M, years)
out[f"sr_{name}_min"] = M.min(1)
out[f"sr_{name}_max"] = M.max(1)
out[f"sr_{name}_tm_mean"] = M[:, tm].mean(1)
out[f"sr_{name}_oli_mean"] = M[:, oli].mean(1)
out[f"sr_{name}_oli_minus_tm"] = out[f"sr_{name}_oli_mean"] - out[f"sr_{name}_tm_mean"]
for (y0, y1), tag in zip(DECADES, DECADE_TAGS):
sel = (years >= y0) & (years <= y1)
out[f"sr_{name}_dec{tag}_mean"] = M[:, sel].mean(1)
# ---- construction events, on the cloud-filtered series -----------------
smoothed = {k: _median_filter3(signals[k]) for k in set(STEP_SIGNALS) | set(SPIKE_SIGNALS)}
for name in STEP_SIGNALS:
sy, sm, nj, st = _step_stats(smoothed[name], years)
out[f"step_{name}_year"] = sy
out[f"step_{name}_mag"] = sm
out[f"step_{name}_njumps"] = nj
out[f"step_{name}_t"] = st
resid = signals[name] - signals[name].mean(1, keepdims=True)
out[f"step_{name}_snr"] = np.abs(sm) / (resid.std(1, ddof=1) + EPS)
# ---- transient bare-soil spike: a building site is bare for 1-3 years --
for name in SPIKE_SIGNALS:
M = smoothed[name]
med = np.median(M, axis=1)
mad = np.median(np.abs(M - med[:, None]), axis=1) + EPS
k = np.argmax(M, axis=1)
out[f"spike_{name}_year"] = years[k].astype(np.float32)
out[f"spike_{name}_z"] = (M[np.arange(len(M)), k] - med) / mad
# does it come back down? a permanent rise is a new roof, a spike that
# returns to baseline is a construction site
after = np.clip(k + 3, 0, M.shape[1] - 1)
out[f"spike_{name}_returns"] = ((M[np.arange(len(M)), after] - med) / mad)
# ---- post-construction greening: street trees take decades to mature ---
ndvi = signals["NDVI"]
sy_b = out["step_brightness_year"]
slope_after = np.zeros(len(ndvi), dtype=np.float32)
years_since = np.zeros(len(ndvi), dtype=np.float32)
for i in range(len(ndvi)):
k = int(np.searchsorted(years, sy_b[i]))
seg = ndvi[i, k:]
years_since[i] = float(years[-1] - sy_b[i])
if len(seg) >= 5:
t = np.arange(len(seg), dtype=np.float32)
t -= t.mean()
slope_after[i] = float((seg * t).sum() / (t * t).sum() * 10.0)
out["post_step_NDVI_slope_decade"] = slope_after
out["years_since_step"] = years_since
# ---- what was there before the change ----------------------------------
# 0 vegetated, 1 bare, 2 already built, 3 water. For a pixel that changed
# after 2004 this separates greenfield expansion from brownfield infill and
# from land reclamation, which have completely different trajectories but
# land in the same class.
pre_ndvi = out["sr_NDVI_early_mean"]
pre_mndwi = out["sr_MNDWI_early_mean"]
pre_ndbi = out["sr_NDBI_early_mean"]
pre = np.full(len(pre_ndvi), 2.0, dtype=np.float32)
pre[pre_ndvi > 0.30] = 0.0
pre[(pre_ndvi <= 0.30) & (pre_ndbi < 0.0) & (out["sr_BSI_early_mean"] > 0.05)] = 1.0
pre[pre_mndwi > 0.10] = 3.0
out["pre_state"] = pre
if sat is not None:
out.update(sensor_features(pix, years, observed, sat))
out["n_observed_years"] = observed.sum(1).astype(np.float32)
out["first_observed_year"] = years[np.argmax(observed, axis=1)].astype(np.float32)
last = observed.shape[1] - 1 - np.argmax(observed[:, ::-1], axis=1)
out["last_observed_year"] = years[last].astype(np.float32)
return pd.concat([pix, pd.DataFrame(out, index=pix.index)], axis=1)
PRE_STATE_WORDS = {0: "vegetated - farmland, scrub or garden",
1: "bare soil or a cleared site",
2: "already built on or paved",
3: "open water (later reclaimed)"}
def add_city_geometry(df: pd.DataFrame) -> pd.DataFrame:
"""
Two purely geometric, label-free features.
`radial_frac`: distance from the city centroid, divided by the city's own
95th percentile, so it is comparable between cities. European cities share a
morphological gradient - oldest and densest in the historic core - and this
is the only transferable handle on the class 1 / class 2 split, whose
boundary year (1960 vs 1945) has no spectral correlate at all.
`dist_to_water_px`: distance to the nearest pixel that looks like open
water, which is what separates the Amsterdam canal belt from everything
else.
"""
from scipy.spatial import cKDTree
out = df.copy()
xy = out[PID].to_numpy(float)
centre = np.median(xy, axis=0)
r = np.linalg.norm(xy - centre, axis=1)
out["radial_px"] = r
out["radial_frac"] = r / (np.percentile(r, 95) + EPS)
far = float(np.percentile(r, 99) * 2.0) # sentinel: "no water anywhere near"
water = out["sr_MNDWI_max"].to_numpy(float) > 0.0 if "sr_MNDWI_max" in out else None
if water is not None and water.sum() > 0:
tree = cKDTree(xy[water])
d, _ = tree.query(xy, k=1)
out["dist_to_water_px"] = np.minimum(d, far)
else:
out["dist_to_water_px"] = far
return out
# --------------------------------------------------------------------------- #
# Fallback: start from the organisers' preprocessed_data.pkl
# --------------------------------------------------------------------------- #
def from_official_pkl(path):
"""
Load the organisers' `preprocessed_data.pkl` into the same shape
`build_city` produces, so the GBDT notebook can run without the 3 GB of raw
parquet.
What you get: the official 60 features, the labels, and the pixel
coordinates - enough for every classical model, the spatial validation, the
shift harness and the full few-shot protocol.
What you do NOT get: the extended features (true surface reflectance,
construction-event detection, per-decade means, tasseled cap,
chromaticity, building coverage) and therefore not the physical values the
verbaliser's word bands need. The pkl's X is already z-scored with Madrid's
scaler, so the numbers are unitless. Within-city RANKS still work, which is
the main transfer mechanism - so a ranks-only prompt is possible from this
file alone, just a thinner one.
Returns (madrid_df, amsterdam_df).
"""
import pickle
with open(path, "rb") as fh:
d = pickle.load(fh)
names = list(d["feature_names"])
out = []
for city in ("madrid", "amsterdam"):
X = np.asarray(d[f"X_{city}"], dtype=np.float32)
y = np.asarray(d[f"y_{city}"], dtype=int)
ids = np.asarray(d[f"pixel_ids_{city}"])
df = pd.DataFrame(X, columns=names)
df.insert(0, "px_key", ids[:, 0])
df.insert(1, "py_key", ids[:, 1])
df["age_class"] = y
df["city"] = city.capitalize()
out.append(df)
print(f"loaded {path}")
for name, df in zip(("Madrid", "Amsterdam"), out):
print(f" {name}: {len(df):,} pixels x {len(names)} official features "
f"| classes {df.age_class.value_counts().sort_index().to_dict()}")
print(" note: features are Madrid-scaled z-scores, not physical units; "
"the extended feature set is absent")
# Guard against loading the wrong file - a truncated download, a synthetic
# test fixture, or another city's export - and silently reporting numbers
# from it. The organisers' pixel counts are published in the competitors'
# guide, so they are a free integrity check.
import os
if os.environ.get("ALLOW_SYNTHETIC_PKL") == "1":
print(" WARNING: integrity check disabled by "
"ALLOW_SYNTHETIC_PKL - numbers are NOT real")
return tuple(out)
expected = {"Madrid": 76_263, "Amsterdam": 25_992}
problems = []
for name, df in zip(("Madrid", "Amsterdam"), out):
if len(df) != expected[name]:
problems.append(f"{name} has {len(df):,} pixels, expected "
f"{expected[name]:,}")
if len(names) != 60:
problems.append(f"{len(names)} feature names, expected 60")
if problems:
raise ValueError(
"This does not look like the organisers' preprocessed_data.pkl:\n "
+ "\n ".join(problems)
+ f"\nFile: {path}\nIf you meant to use a test fixture, load it "
"explicitly rather than through this function.")
print(" integrity check passed (pixel counts match the published figures)")
return tuple(out)
# --------------------------------------------------------------------------- #
# Driver
# --------------------------------------------------------------------------- #
def build_city(parquet_path, city_hint: str | None = None, verbose: bool = True,
agg: str = "median", geometry: bool = True) -> pd.DataFrame:
if verbose:
print(f"reading {parquet_path}")
df = pd.read_parquet(parquet_path)
if "city" not in df.columns and city_hint:
df["city"] = city_hint
if verbose:
print(f" {len(df):,} rows x {df.shape[1]} cols | "
f"years {df['year'].min()}-{df['year'].max()}")
df = assign_age_class(df)
flat = make_flat_view(df, agg=agg)
del df
indicators = period_coverage(flat)
meta_cols = [c for c in ["city", "coverage", "weighted_mean_year", "age_class"]
if c in flat.columns]
meta = (flat.sort_values(PID + ["year"])
.groupby(PID, as_index=False)[meta_cols].first())
pix, years, mats, observed, sat = to_year_matrices(flat)
del flat
off = build_official_60(pix, years, mats, indicators)
ext = build_extended(pix, years, mats, observed, sat)
feats = off.merge(ext, on=PID, how="left").merge(meta, on=PID, how="left")
feats = feats[feats["age_class"].notna()].reset_index(drop=True)
feats["age_class"] = feats["age_class"].astype(int)
if geometry:
feats = add_city_geometry(feats)
if verbose:
n_ext = ext.shape[1] - len(PID)
print(f" -> {len(feats):,} labelled pixels | 60 official + {n_ext} extended features")
return feats123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776"""
Model 1 and Model 2 of the submission: LightGBM and CatBoost, plus the
cross-city plumbing they share with the LLM track.
Contents
* per-city normalisation (rank / robust z) - unsupervised, no labels
* CORAL covariance alignment - unsupervised, no labels
* adversarial validation - finds city-specific features
* macro-F1 eval metrics for both libraries
* ordinal (cumulative-binary) decomposition - the classes are ordered
* several `modelCreate` adapters for the few-shot protocol
"""
from __future__ import annotations
import numpy as np
from sklearn.metrics import f1_score
CLASSES = np.array([1, 2, 3, 4])
SEED = 42
# --------------------------------------------------------------------------- #
# Per-city normalisation. Fit one of these per city on its own features; it
# needs no labels, so it is legal for Amsterdam.
# --------------------------------------------------------------------------- #
def rankable_mask(X, min_unique: int = 10, max_tie_share: float = 0.5):
"""
Which columns are safe to rank-transform, judged on the DESIGN city only.
A column is unsafe when one value dominates it. The test that matters is
the size of the biggest tie, not the number of distinct values:
`first_observed_year` has 20 distinct values but is 1984 for 98.4% of
pixels, and ranking it turned a domain AUC of 0.507 into 0.997.
"""
X = np.asarray(X, dtype=np.float64)
out = np.empty(X.shape[1], dtype=bool)
for j in range(X.shape[1]):
col = X[:, j]
vals, counts = np.unique(col, return_counts=True)
out[j] = (len(vals) >= min_unique
and counts.max() / len(col) < max_tie_share)
return out
class CityNormaliser:
"""
mode="rank" : map each feature to its within-city percentile (0-1).
Kills every city-level offset and gain, including ones no
linear method would catch. Cost: it also erases genuine
between-city differences in level, and it is distorted
when the two cities have different class proportions.
mode="robustz" : (x - median) / IQR per city. Gentler, keeps shape.
mode=None : identity. The right answer on this data (see
TREE_NORMALISE), so it has to be a real, explicit mode.
`mode=None` used to fall through `if self.mode != "rank"` in `transform`
and apply robust z anyway. Every caller that asked for no normalisation got
robust z instead, silently - `mc_refit`, whose default is `TREE_NORMALISE`
(None), was measured that way. An unrecognised mode now raises rather than
quietly becoming one of the other two.
"""
MODES = (None, "none", "robustz", "rank")
def __init__(self, mode: str | None = "robustz", n_grid: int = 1001,
min_unique: int = 10, max_tie_share: float = 0.5,
rankable=None):
if mode not in self.MODES:
raise ValueError(f"unknown normalise mode {mode!r}; "
f"expected one of {self.MODES}")
self.mode = None if mode == "none" else mode
self.n_grid = n_grid
self.min_unique = min_unique
self.max_tie_share = max_tie_share
# Which columns may be rank-transformed. This is a STRUCTURAL decision
# about the features and it MUST be identical in every city: deciding
# it per city let a column be ranked in one and z-scored in the other,
# putting them on different scales and making the two cities perfectly
# separable (domain AUC 1.000 on `n_observed_years`). So it is computed
# once on the design city and passed in here for the target.
self.rankable = rankable
def fit(self, X):
X = np.asarray(X, dtype=np.float64)
if self.mode is None:
return self
self.med_ = np.median(X, axis=0)
q75, q25 = np.percentile(X, [75, 25], axis=0)
self.iqr_ = np.where((q75 - q25) > 1e-12, q75 - q25, 1.0)
if self.mode == "rank":
self.q_ = np.linspace(0, 100, self.n_grid)
self.grid_ = np.percentile(X, self.q_, axis=0) # (n_grid, d)
# Heavily tied columns must NOT be rank-transformed.
#
# Measured on the real data: `first_observed_year` is 1984 for
# almost every pixel, and its domain AUC went from 0.507 raw to
# 0.997 after ranking - the transform CREATED a perfect city marker
# where there was none. A dominant tie makes the ECDF one long
# plateau, and the plateau sits at a slightly different quantile in
# each city, so every pixel lands on a different side of it.
#
# The test that matters is the size of the biggest tie, not the
# number of distinct values: that column has 20 distinct values and
# still breaks. Offending columns fall back to robust z.
if self.rankable is not None:
self.rankable_ = np.asarray(self.rankable, dtype=bool)
else:
self.rankable_ = rankable_mask(
X, min_unique=self.min_unique,
max_tie_share=self.max_tie_share)
return self
def transform(self, X):
X = np.asarray(X, dtype=np.float64)
if self.mode is None:
return X
if self.mode != "rank":
return (X - self.med_) / self.iqr_
out = (X - self.med_) / self.iqr_
for j in np.flatnonzero(self.rankable_):
out[:, j] = np.interp(X[:, j], self.grid_[:, j], self.q_ / 100.0,
left=0.0, right=1.0)
return out
def fit_transform(self, X):
return self.fit(X).transform(X)
def coral(X_src, X_tgt, eps: float = 1e-6):
"""
CORAL: whiten the source with its own covariance, then re-colour it with
the target covariance, so the two feature clouds have the same second-order
statistics. Uses target FEATURES only - no labels.
Returns the transformed source.
"""
Xs = np.asarray(X_src, dtype=np.float64)
Xt = np.asarray(X_tgt, dtype=np.float64)
ms, mt = Xs.mean(0), Xt.mean(0)
Cs = np.cov(Xs - ms, rowvar=False) + eps * np.eye(Xs.shape[1])
Ct = np.cov(Xt - mt, rowvar=False) + eps * np.eye(Xt.shape[1])
def _half(C, power):
w, V = np.linalg.eigh(C)
w = np.clip(w, eps, None)
return V @ np.diag(w ** power) @ V.T
A = _half(Cs, -0.5) @ _half(Ct, 0.5)
return (Xs - ms) @ A + mt
# --------------------------------------------------------------------------- #
# Adversarial validation: which features simply say "this is Madrid"?
# --------------------------------------------------------------------------- #
def adversarial_validation(X_src, X_tgt, feature_names, n_estimators: int = 300,
seed: int = SEED, max_rows: int = 30_000):
"""
Train a classifier to tell the two cities apart. An AUC near 1.0 means the
domains are trivially separable; the top-importance features are the ones
carrying the city signature rather than the age signal.
LightGBM rather than a random forest, and capped at `max_rows` per city:
this is called several times over ~380 features, and the AUC it reports
saturates long before 30k rows per city, so a forest here would dominate
the notebook's runtime for no extra information.
Returns (auc, DataFrame of importances sorted descending).
"""
import lightgbm as lgb
import pandas as pd
from sklearn.model_selection import cross_val_predict
from sklearn.metrics import roc_auc_score
rng = np.random.default_rng(seed)
def cap(A):
A = np.asarray(A, dtype=np.float32)
if len(A) > max_rows:
A = A[rng.choice(len(A), max_rows, replace=False)]
return A
Xs, Xt = cap(X_src), cap(X_tgt)
X = np.vstack([Xs, Xt])
y = np.r_[np.zeros(len(Xs)), np.ones(len(Xt))]
clf = lgb.LGBMClassifier(objective="binary", n_estimators=n_estimators,
learning_rate=0.05, num_leaves=31,
min_child_samples=50, colsample_bytree=0.7,
subsample=0.8, subsample_freq=1, max_bin=127,
n_jobs=-1, random_state=seed, verbosity=-1)
p = cross_val_predict(clf, X, y, cv=3, method="predict_proba", n_jobs=1)[:, 1]
auc = roc_auc_score(y, p)
clf.fit(X, y)
gain = clf.feature_importances_.astype(float)
imp = (pd.DataFrame({"feature": list(feature_names),
"city_importance": gain / max(gain.sum(), 1.0)})
.sort_values("city_importance", ascending=False)
.reset_index(drop=True))
return float(auc), imp
# --------------------------------------------------------------------------- #
# Macro-F1 eval metrics
# --------------------------------------------------------------------------- #
def lgb_macro_f1(y_true, y_pred):
"""lightgbm 4.x feval. y_pred arrives as (n*4,) or (n,4) depending on version."""
p = np.asarray(y_pred)
if p.ndim == 1:
p = p.reshape(len(y_true), -1, order="F") if p.size != len(y_true) else p
lab = np.argmax(p, axis=1) if p.ndim == 2 else p
return "macro_f1", float(f1_score(y_true, lab, average="macro", zero_division=0)), True
class CatMacroF1:
"""CatBoost custom eval metric (higher is better)."""
def is_max_optimal(self):
return True
def evaluate(self, approxes, target, weight):
p = np.array(approxes).T
lab = np.argmax(p, axis=1)
return float(f1_score(np.asarray(target, dtype=int), lab,
average="macro", zero_division=0)), 1.0
def get_final_error(self, error, weight):
return error
# --------------------------------------------------------------------------- #
# Default parameter sets. Tuned toward robustness, not toward the last
# 0.002 of Madrid CV: the test set is a different city.
# --------------------------------------------------------------------------- #
LGBM_PARAMS = dict(
objective="multiclass", num_class=4, learning_rate=0.03, n_estimators=1200,
num_leaves=31, max_depth=-1, min_child_samples=80, subsample=0.8,
subsample_freq=1, colsample_bytree=0.6, reg_alpha=0.5, reg_lambda=5.0,
max_bin=127, n_jobs=-1, random_state=SEED, verbosity=-1,
)
CATBOOST_PARAMS = dict(
loss_function="MultiClass", classes_count=4, iterations=2000,
learning_rate=0.03, depth=6, l2_leaf_reg=6.0, random_strength=1.5,
bootstrap_type="Bernoulli", subsample=0.8, rsm=0.7,
boosting_type="Plain", random_seed=SEED, verbose=False,
allow_writing_files=False,
)
def fit_lgbm(X, y, params=None, class_weight=None, sample_weight=None):
import lightgbm as lgb
p = dict(LGBM_PARAMS)
if params:
p.update(params)
if class_weight is not None:
p["class_weight"] = class_weight
m = lgb.LGBMClassifier(**p)
m.fit(np.asarray(X), np.asarray(y) - 1, sample_weight=sample_weight)
return m
def fit_catboost(X, y, params=None, class_weights=None, sample_weight=None):
from catboost import CatBoostClassifier
p = dict(CATBOOST_PARAMS)
if params:
p.update(params)
if class_weights is not None:
p["class_weights"] = list(class_weights)
m = CatBoostClassifier(**p)
m.fit(np.asarray(X), np.asarray(y) - 1, sample_weight=sample_weight)
return m
def balanced_class_weights(y):
y = np.asarray(y)
counts = np.array([(y == c).sum() for c in CLASSES], dtype=float)
w = len(y) / (4.0 * np.clip(counts, 1, None))
return w
# --------------------------------------------------------------------------- #
# Ordinal decomposition: the four classes are ordered age bins, so three
# cumulative binary problems ("older than X?") use that structure.
# --------------------------------------------------------------------------- #
class OrdinalGBDT:
"""P(y > k) for k = 1,2,3, then differenced into class probabilities."""
def __init__(self, fit_fn=fit_lgbm, params=None):
self.fit_fn = fit_fn
self.params = params
def fit(self, X, y, sample_weight=None):
import lightgbm as lgb
X, y = np.asarray(X), np.asarray(y)
params = dict(LGBM_PARAMS)
params.update(self.params or {})
params.pop("num_class", None) # binary problems, not 4-way
params["objective"] = "binary"
self.models_ = []
for k in (1, 2, 3):
m = lgb.LGBMClassifier(**params)
m.fit(X, (y > k).astype(int), sample_weight=sample_weight)
self.models_.append(m)
return self
def predict_proba(self, X):
X = np.asarray(X)
s = np.column_stack([m.predict_proba(X)[:, 1] for m in self.models_])
s = np.minimum.accumulate(s, axis=1) # enforce monotonicity
p1 = 1.0 - s[:, 0]
p2 = s[:, 0] - s[:, 1]
p3 = s[:, 1] - s[:, 2]
p4 = s[:, 2]
P = np.clip(np.column_stack([p1, p2, p3, p4]), 1e-9, None)
return P / P.sum(axis=1, keepdims=True)
# --------------------------------------------------------------------------- #
# Calibration on the few-shot sample
# --------------------------------------------------------------------------- #
def stratification_weights(y_shot, target_prior):
"""
The organisers hand us n labelled pixels *per class*, so the labelled sample
is balanced while the city is not. Anything fitted on it therefore inherits
a uniform class prior - which, in testing, cost class 4 almost 0.17 F1.
These weights undo the stratification: each row is weighted by
target_prior[c] / (1/4), so the weighted sample behaves like a random
sample of the city. `target_prior` must come from somewhere legal - the EM
estimate on unlabelled Amsterdam probabilities, or the organisers' own
published class shares.
"""
y = np.asarray(y_shot, dtype=int)
tp = np.asarray(target_prior, dtype=float)
tp = tp / tp.sum()
counts = np.array([(y == c).sum() for c in CLASSES], dtype=float)
share = counts / counts.sum()
w = (tp / np.clip(share, 1e-9, None))[y - 1]
return w * len(y) / w.sum()
def vector_scaling(proba_shot, y_shot, l2: float = 1.0, n_iter: int = 400,
lr: float = 0.1, sample_weight=None):
"""
Learn per-class scale a_k and bias b_k on the log-probabilities using only
the n-per-class labelled target sample: q = softmax(a * log p + b).
Eight parameters, so it survives n=5 per class.
Pass `sample_weight=stratification_weights(...)` unless you really want the
balanced prior of the shot sample baked into the output.
Returns a callable proba -> recalibrated proba.
"""
P = np.log(np.clip(np.asarray(proba_shot, dtype=np.float64), 1e-9, 1))
y = np.asarray(y_shot, dtype=int) - 1
Y = np.eye(4)[y]
sw = (np.ones(len(y)) if sample_weight is None
else np.asarray(sample_weight, dtype=float))
sw = sw / sw.sum()
a, b = np.ones(4), np.zeros(4)
for _ in range(n_iter):
z = P * a + b
z -= z.max(axis=1, keepdims=True)
q = np.exp(z)
q /= q.sum(axis=1, keepdims=True)
d = (q - Y) * sw[:, None]
ga = (d * P).sum(0) + l2 * (a - 1.0)
gb = d.sum(0) + l2 * b
a -= lr * ga
b -= lr * gb
def apply(proba):
lp = np.log(np.clip(np.asarray(proba, dtype=np.float64), 1e-9, 1))
z = lp * a + b
z -= z.max(axis=1, keepdims=True)
e = np.exp(z)
return e / e.sum(axis=1, keepdims=True)
apply.params = (a, b)
return apply
# --------------------------------------------------------------------------- #
# modelCreate adapters for evaluation.evaluate_protocol
# --------------------------------------------------------------------------- #
#: What `modelCreate` is allowed to see of the target city.
#
#: Prof. Thron's specification says Amsterdam data "may only be used to
#: EVALUATE modelCreate", and that every design decision must be made without
#: looking at Amsterdam. That rules out picking features or hyperparameters by
#: Amsterdam's score - which we never do. It leaves one genuine question open:
#: may modelCreate, as a FUNCTION applied to a new city, read that city's
#: unlabelled feature matrix at adaptation time?
#:
#: Both readings are defensible, so both are supported and both get reported.
#:
#: "transductive" - modelCreate(D^(N)_city, X_city). Per-city statistics come
#: from all the city's unlabelled pixels. This is standard unsupervised
#: domain adaptation and matches the deployment story: pointing this at
#: Baghdad, you have every Landsat pixel and merely lack labels. The
#: organisers' own Notebook 3 is transductive in spirit, though it
#: normalises Amsterdam with Madrid's scaler.
#:
#: "inductive" - modelCreate(D^(N)_city) only. Per-city statistics are
#: estimated from the N-per-class labelled sample alone. Strictly
#: compliant on the tightest reading. At N=200 that is 800 pixels, which
#: estimates a percentile well; at N=5 it is 20 and noticeably noisier.
#:
#: Ask the organisers which they intend. Until then, lead with whichever is
#: weaker and quote the other alongside it.
TARGET_ACCESS = ("transductive", "inductive")
def _target_reference(X_tgt_all, X_shot, access: str):
"""The rows a per-city statistic may be estimated from."""
if access == "inductive":
return np.asarray(X_shot, dtype=float)
return np.asarray(X_tgt_all, dtype=float)
#: Default normalisation for the TREE models: none.
#:
#: Decided on Madrid, with blocked CV in which each held-out block is
#: normalised with its own statistics exactly as a new city would be:
#: none 0.5989 +- 0.0230 | rank 0.5697 +- 0.0789 | robust z 0.5690 +- 0.0830
#: and the same ordering then held on Amsterdam (0.5928 against 0.5268).
#:
#: The reason is that the absolute level is signal, not only nuisance: building
#: era is spatially clustered, so a district's average brightness says something
#: real about when it was built, and normalising a region to its own median
#: subtracts that along with the city offset.
#:
#: DISTANCE-based methods are different and keep their normalisation. A nearest
#: neighbour over unscaled features is dominated by whichever column has the
#: largest units, which is an artefact of units rather than a statement about
#: transfer.
TREE_NORMALISE = None
DISTANCE_NORMALISE = "robustz"
def mc_zero_shot(fit=fit_lgbm, normalise: str | None = TREE_NORMALISE,
use_coral: bool = False, balanced: bool = True,
access: str = "transductive"):
"""
Train on the source city. Under "transductive" access the few-shot sample
is ignored entirely; under "inductive" it is still used, but only to
estimate the target city's feature distribution, never its labels.
"""
cache = {}
def model_create(X_src, y_src, X_tgt_all, X_shot, y_shot):
ref = _target_reference(X_tgt_all, X_shot, access)
rk = rankable_mask(X_src) if normalise == "rank" else None
nt = CityNormaliser(normalise, rankable=rk).fit(ref) if normalise else None
key = (normalise, use_coral, balanced, access)
if key not in cache:
ns = (CityNormaliser(normalise, rankable=rk).fit(X_src)
if normalise else None)
Xs = ns.transform(X_src) if ns else np.asarray(X_src, float)
if use_coral:
Xs = coral(Xs, nt.transform(ref) if nt else ref)
cw = balanced_class_weights(y_src) if balanced else None
model = (fit(Xs, y_src, class_weight=dict(zip(range(4), cw)) if cw is not None else None)
if fit is fit_lgbm else fit(Xs, y_src, class_weights=cw))
cache[key] = model
model = cache[key]
def predict(X):
return model.predict_proba(nt.transform(X) if nt else X)
return predict
return model_create
def mc_recalibrated(fit=fit_lgbm, normalise: str | None = TREE_NORMALISE,
use_coral: bool = False, balanced: bool = True,
l2: float = 1.0, correct_stratification: bool = True,
tune_decision: bool = True):
"""
Zero-shot model + vector scaling learned on the n-per-class sample, then a
macro-F1 decision rule tuned on the same sample.
`correct_stratification` reweights the shot sample towards the class prior
that EM estimates from the unlabelled target features, so neither the
calibration nor the decision rule inherits the artificial 25/25/25/25 prior
of the sample.
`tune_decision` matters more than the calibration: a well-calibrated model
maximises log-likelihood, and argmax of a calibrated posterior is NOT the
macro-F1 optimum. The shrinkage is tied to the sample size, so n=5 barely
moves the rule and n=200 moves it freely.
"""
base = mc_zero_shot(fit, normalise, use_coral, balanced)
def model_create(X_src, y_src, X_tgt_all, X_shot, y_shot):
from evaluation import em_target_prior, tune_class_weights
predict0 = base(X_src, y_src, X_tgt_all, X_shot, y_shot)
sw = None
if correct_stratification:
src_prior = np.array([(np.asarray(y_src) == c).mean() for c in CLASSES])
tgt_prior = em_target_prior(predict0(X_tgt_all), src_prior)
sw = stratification_weights(y_shot, tgt_prior)
p_shot = predict0(X_shot)
cal = vector_scaling(p_shot, y_shot, l2=l2, sample_weight=sw)
w = np.ones(4)
if tune_decision:
n_shot = len(y_shot)
shrink = float(np.clip(1.0 - n_shot / 400.0, 0.0, 0.9))
w = tune_class_weights(cal(p_shot), y_shot, sample_weight=sw,
shrink=shrink)
def predict(X):
p = cal(predict0(X)) * w[None, :]
return p / np.clip(p.sum(axis=1, keepdims=True), 1e-12, None)
return predict
return model_create
def mc_shot_weighted(fit=fit_lgbm, normalise: str | None = TREE_NORMALISE,
shot_weight: float = 30.0, balanced: bool = True):
"""
Retrain on source + the few target rows, with the target rows upweighted.
`shot_weight` must be chosen on the source city (e.g. by simulating a
held-out Madrid district as a pseudo-target), never on the target score.
"""
def model_create(X_src, y_src, X_tgt_all, X_shot, y_shot):
rk = rankable_mask(X_src) if normalise == "rank" else None
ns = CityNormaliser(normalise, rankable=rk).fit(X_src) if normalise else None
nt = (CityNormaliser(normalise, rankable=rk).fit(X_tgt_all)
if normalise else None)
Xs = ns.transform(X_src) if ns else np.asarray(X_src)
Xsh = nt.transform(X_shot) if nt else np.asarray(X_shot)
X = np.vstack([Xs, Xsh])
y = np.r_[np.asarray(y_src), np.asarray(y_shot)]
w = np.r_[np.ones(len(y_src)), np.full(len(y_shot), shot_weight)]
if balanced:
cw = balanced_class_weights(y)
w = w * cw[np.asarray(y) - 1]
model = fit(X, y, sample_weight=w)
def predict(X_):
return model.predict_proba(nt.transform(X_) if nt else X_)
return predict
return model_create
def mc_knn(normalise: str = DISTANCE_NORMALISE, k: int | None = None,
columns=None):
"""
The pure-retrieval classifier: distance-weighted k-NN over the n labelled
target pixels alone, ignoring the source city completely.
Measure this FIRST. It costs seconds and it bounds everything else: if
50-per-class k-NN already beats the reported 0.34 zero-shot Random Forest,
then the retrieval layer is the story and the source model is support, not
the other way round. It is also the baseline the retrieval features in the
LLM prompt have to beat to justify their complexity.
"""
def model_create(X_src, y_src, X_tgt_all, X_shot, y_shot):
rk = rankable_mask(X_src) if normalise == "rank" else None
nt = CityNormaliser(normalise, rankable=rk).fit(X_tgt_all)
Xs = nt.transform(X_shot)
y_shot = np.asarray(y_shot)
kk = k if k is not None else int(min(15, max(3, 3 * len(y_shot) // 4)))
# Squared distances via the (a-b)^2 = a^2 - 2ab + b^2 identity, in row
# chunks. The naive Xn[:, None, :] - Xs[None, :, :] would allocate
# n_query x n_pool x n_features floats - 63 GB for 26k queries against
# 800 labelled pixels over 380 features.
pool_sq = (Xs ** 2).sum(1)
CHUNK = 2048
def predict(X):
Xn = nt.transform(X)
P = np.zeros((len(Xn), 4))
for s in range(0, len(Xn), CHUNK):
Q = Xn[s:s + CHUNK]
d2 = (Q ** 2).sum(1)[:, None] - 2.0 * (Q @ Xs.T) + pool_sq[None, :]
d = np.sqrt(np.maximum(d2, 0.0))
idx = np.argpartition(d, kk - 1, axis=1)[:, :kk]
dd = np.take_along_axis(d, idx, axis=1)
tau = np.median(dd, axis=1, keepdims=True) + 1e-9
w = np.exp(-(dd / tau) ** 2)
lab = y_shot[idx]
for j, c in enumerate(CLASSES):
P[s:s + CHUNK, j] = (w * (lab == c)).sum(axis=1)
P = np.clip(P, 1e-9, None)
return P / P.sum(axis=1, keepdims=True)
return predict
return model_create
def mc_refit(normalise: str | None = TREE_NORMALISE, decay: float = 0.9,
balanced: bool = False):
"""
LightGBM `Booster.refit`: keep the tree STRUCTURE learned on the source city
and move only the leaf values towards the target, blended by `decay`.
This is the right shape for the problem. Tree structure is what needs tens
of thousands of rows; leaf values are a handful of numbers per tree and can
be nudged by a few hundred. Recommended from n=25 upwards; below that there
is nothing estimable and plain recalibration is safer.
"""
cache = {}
def model_create(X_src, y_src, X_tgt_all, X_shot, y_shot):
key = (normalise, balanced)
if key not in cache:
rk = rankable_mask(X_src) if normalise == "rank" else None
ns = CityNormaliser(normalise, rankable=rk).fit(X_src)
nt = CityNormaliser(normalise, rankable=rk).fit(X_tgt_all)
cw = (dict(zip(range(4), balanced_class_weights(y_src)))
if balanced else None)
cache[key] = (fit_lgbm(ns.transform(X_src), y_src, class_weight=cw), nt)
model, nt = cache[key]
Xsh = nt.transform(X_shot)
booster = model.booster_.refit(Xsh, np.asarray(y_shot) - 1,
decay_rate=decay)
def predict(X):
P = booster.predict(nt.transform(X))
P = np.asarray(P, dtype=float)
if P.ndim == 1:
P = P.reshape(-1, 4)
return P / np.clip(P.sum(axis=1, keepdims=True), 1e-12, None)
return predict
return model_create
def single_feature_domain_auc(X_src, X_tgt, feature_names):
"""
One AUC per feature for the question "which city is this?".
0.5 means the feature is domain-invariant; 1.0 means it is a pure city
marker and a Madrid-trained split on it is meaningless in Amsterdam. Run it
before and after per-city normalisation: the table of the two columns is the
most convincing single figure for the write-up, and it is the honest basis
for dropping features. Prune conservatively - drop only a feature that is
still above ~0.90 after normalisation AND carries little Madrid importance.
"""
import pandas as pd
from sklearn.metrics import roc_auc_score
Xs = np.asarray(X_src, dtype=float)
Xt = np.asarray(X_tgt, dtype=float)
y = np.r_[np.zeros(len(Xs)), np.ones(len(Xt))]
rows = []
for j, name in enumerate(feature_names):
v = np.r_[Xs[:, j], Xt[:, j]]
ok = np.isfinite(v)
if ok.sum() < 10 or np.std(v[ok]) == 0:
rows.append(dict(feature=name, domain_auc=0.5))
continue
a = roc_auc_score(y[ok], v[ok])
rows.append(dict(feature=name, domain_auc=max(a, 1 - a)))
return (pd.DataFrame(rows).sort_values("domain_auc", ascending=False)
.reset_index(drop=True))
def mc_prototype_official():
"""
The organisers' own few-shot baseline, reproduced exactly: class means of
the labelled target sample, nearest prototype by plain Euclidean distance,
on features standardised with the SOURCE city's scaler.
This is the row every other row in the table has to beat, and it is a
stronger baseline than it looks. Both the prototypes and the queries come
from the target city and receive the same transform, so any affine
difference between the cities cancels exactly in a nearest-prototype
comparison. The source scaler therefore does no harm here; it only sets the
relative weighting of features. In synthetic testing this plain version beat
a rank-normalised Mahalanobis version by 0.05 macro F1 at n=25, because the
rank transform distorts the cluster geometry that prototypes depend on.
Beat it on measurements, not on sophistication.
"""
def model_create(X_src, y_src, X_tgt_all, X_shot, y_shot):
mu_s = np.mean(X_src, axis=0)
sd_s = np.std(X_src, axis=0)
sd_s = np.where(sd_s > 1e-12, sd_s, 1.0)
Xsh = (np.asarray(X_shot, float) - mu_s) / sd_s
y_shot = np.asarray(y_shot)
present = [c for c in CLASSES if (y_shot == c).sum() > 0]
proto = np.stack([Xsh[y_shot == c].mean(0) for c in present])
def predict(X):
Xn = (np.asarray(X, float) - mu_s) / sd_s
d = np.linalg.norm(Xn[:, None, :] - proto[None, :, :], axis=2)
P = np.zeros((len(Xn), 4))
# hard nearest-prototype assignment, as in their code
for row, j in enumerate(np.argmin(d, axis=1)):
P[row, present[j] - 1] = 1.0
return np.clip(P, 1e-9, None) / np.clip(P, 1e-9, None).sum(1, keepdims=True)
return predict
return model_create
def mc_prototype(normalise: str | None = DISTANCE_NORMALISE,
metric: str = "euclidean",
shrink: float = 0.5, temperature: float = 1.0):
"""
Prototype classifier: one class mean from the n labelled target pixels,
nearest prototype wins. Needs no source model, so it is the honest floor.
`normalise` defaults to per-city robust z rather than rank. Rank mapping
forces each marginal to be uniform, which is excellent for tree splits and
bad here - it distorts the cluster shape that a distance to a class mean
depends on. Measured: rank + Mahalanobis lost 0.05 macro F1 at n=25 against
the plain version on synthetic data.
`metric`:
"euclidean" - isotropic distance.
"within" - Mahalanobis on the POOLED WITHIN-CLASS covariance of the
shots (shrunk towards diagonal). This is the statistically
right metric for prototypes, and it is not the same thing
as using the target city's total covariance, which is
dominated by the BETWEEN-class spread and therefore shrinks
exactly the directions that separate the classes.
"total" - Mahalanobis on the target city's total covariance; kept
only so the ablation table can show why it is worse.
"""
def model_create(X_src, y_src, X_tgt_all, X_shot, y_shot):
rk = rankable_mask(X_src) if normalise == "rank" else None
nt = (CityNormaliser(normalise, rankable=rk).fit(X_tgt_all)
if normalise else None)
Xt = nt.transform(X_tgt_all) if nt else np.asarray(X_tgt_all, float)
Xsh = nt.transform(X_shot) if nt else np.asarray(X_shot, float)
y_shot = np.asarray(y_shot)
present = [c for c in CLASSES if (y_shot == c).sum() > 0]
mu = np.stack([Xsh[y_shot == c].mean(0) for c in present])
d_ = Xt.shape[1]
if metric == "within":
# Pooled within-class scatter of the shots. Macro F1 on synthetic
# anisotropic data against the organisers' Euclidean prototype:
# n=5 0.719 vs 0.649, n=25 0.967 vs 0.821, n=100 0.988 vs 0.833 -
# the largest single gain of any adaptation step tried.
#
# Without the blending below it LOSES at n=5, where 20 rows cannot
# fill a 20x20 covariance, so the estimate is pulled towards the
# target city's total covariance and towards its own diagonal by how
# much data there actually is.
#
# Honest caveat: those synthetic classes are Gaussian sharing one
# anisotropic within-class covariance, i.e. exactly the model this
# metric assumes. Expect less on real Landsat features; trust the
# ORDERING of the four variants, not the absolute numbers.
parts = [Xsh[y_shot == c] - Xsh[y_shot == c].mean(0)
for c in present if (y_shot == c).sum() > 1]
resid = np.vstack(parts) if parts else np.zeros((0, d_))
n_res = len(resid)
Cw = (np.cov(resid, rowvar=False) if n_res > d_
else (np.diag(np.var(resid, axis=0) + 1e-6) if n_res
else np.eye(d_)))
Ct = np.cov(Xt, rowvar=False)
a = float(np.clip(d_ / (d_ + max(n_res, 1)), 0.0, 0.8))
C = (1 - a) * Cw + a * Ct
s = float(np.clip(shrink * d_ / (d_ + max(n_res, 1)) * 2.0, 0.1, 0.9))
C = (1 - s) * C + s * np.diag(np.diag(C) + 1e-6) + 1e-6 * np.eye(d_)
A = np.linalg.pinv(C)
elif metric == "total":
Ct = np.cov(Xt, rowvar=False)
Ct = (1 - shrink) * Ct + shrink * np.diag(np.diag(Ct)) + 1e-6 * np.eye(d_)
A = np.linalg.pinv(Ct)
else:
A = np.eye(d_)
def predict(X):
Xn = nt.transform(X) if nt else np.asarray(X, float)
d = np.stack([np.einsum("ij,jk,ik->i", Xn - m, A, Xn - m) for m in mu],
axis=1)
z = -0.5 * d / max(temperature, 1e-6)
z -= z.max(axis=1, keepdims=True)
e = np.exp(z)
e = e / e.sum(axis=1, keepdims=True)
P = np.full((len(Xn), 4), 1e-9)
for j, c in enumerate(present):
P[:, c - 1] = e[:, j]
return P / P.sum(axis=1, keepdims=True)
return predict
return model_create123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420"""The adaptation layer: retrieval over whatever labelled target pixels we aregiven, plus label-free neighbourhood features.
Three distinct channels, deliberately kept separate so their contributions canbe measured one at a time:
A. NEIGHBOURHOOD FEATURES - no labels at all. The mean feature vector of the surrounding pixels. Buildings are built in blocks, so a pixel's neighbourhood says a great deal about its era, and this works at n=0. B. SPECTRAL RETRIEVAL - the k labelled pixels in this city whose features are closest to the query. Summarised as a class histogram, and/or rendered as in-context demonstrations. C. SPATIAL RETRIEVAL - the labelled pixels physically nearest the query. Weak when only 20 pixels are labelled, strong at 800.
Leakage discipline: when these fields are built for MADRID training rows, thelabelled pool is a RANDOM n-per-class sample drawn from spatial blocks thatexclude the query pixel. That reproduces exactly the situation the model meetsin Amsterdam, and a pixel can never retrieve itself or its own neighbours."""from __future__ import annotations
import numpy as npfrom sklearn.neighbors import NearestNeighbors
CLASSES = np.array([1, 2, 3, 4])
# --------------------------------------------------------------------------- ## A. Label-free neighbourhood features# --------------------------------------------------------------------------- #def add_neighbourhood_features(df, coord_cols=("px_key", "py_key"), feature_cols=None, k: int = 8, max_radius: float = 10.0, prefix: str = "nbr_"): """ For each pixel, average a handful of feature columns over its k nearest neighbours (excluding itself). Uses no labels, so it is legal in both cities and available at n=0.
`max_radius` is in pixel units (1 = 30 m); neighbours further away are ignored and the pixel keeps its own value instead. """ import pandas as pd
if feature_cols is None: feature_cols = [c for c in ("sr_brightness_mean", "sr_NDVI_mean", "sr_SWIR1_mean", "sr_brightness_late_minus_early", "step_brightness_year", "step_brightness_mag", "sr_brightness_std") if c in df.columns] coords = df[list(coord_cols)].to_numpy(dtype=float) V = df[list(feature_cols)].to_numpy(dtype=float)
nn = NearestNeighbors(n_neighbors=min(k + 1, len(df))).fit(coords) dist, idx = nn.kneighbors(coords) dist, idx = dist[:, 1:], idx[:, 1:] # drop self ok = dist <= max_radius w = ok.astype(float) denom = np.clip(w.sum(axis=1, keepdims=True), 1e-9, None)
out = {} for j, c in enumerate(feature_cols): vals = V[idx, j] mean = (vals * w).sum(axis=1, keepdims=True) / denom mean = np.where(w.sum(axis=1, keepdims=True) > 0, mean, V[:, [j]]) out[f"{prefix}{c}"] = mean.ravel() out[f"{prefix}{c}_diff"] = V[:, j] - mean.ravel() out[f"{prefix}n_within_radius"] = ok.sum(axis=1).astype(float) return pd.concat([df, pd.DataFrame(out, index=df.index)], axis=1)
# --------------------------------------------------------------------------- ## B + C. Retrieval over a labelled pool# --------------------------------------------------------------------------- #class LabelledPool: """ A set of labelled pixels in one city (in Amsterdam: the n-per-class sample the organisers hand us; in Madrid during training: a simulated sample).
sklearn only - no FAISS - because the pool is at most a few thousand rows and the notebook must run with the internet switched off on Kaggle. """
def __init__(self, X, y, coords, rows=None): self.X = np.asarray(X, dtype=np.float64) self.y = np.asarray(y, dtype=int) self.coords = np.asarray(coords, dtype=float) self.rows = rows # for rendering shots self._nn_spec = NearestNeighbors(n_neighbors=min(16, len(self.X))).fit(self.X) self._nn_spat = NearestNeighbors(n_neighbors=min(16, len(self.X))).fit(self.coords)
def __len__(self): return len(self.X)
def spectral(self, Xq, k: int = 8): k = min(k, len(self.X)) d, i = self._nn_spec.kneighbors(np.atleast_2d(Xq), n_neighbors=k) return d, i
def spatial(self, coords_q, k: int = 4): k = min(k, len(self.coords)) d, i = self._nn_spat.kneighbors(np.atleast_2d(coords_q), n_neighbors=k) return d, i
def stratified_spectral(self, Xq, per_class: int = 1): """Closest `per_class` pool members of each class - a class-balanced set of demonstrations, so the prompt cannot be swamped by class 2.""" picks = [] for c in CLASSES: sel = np.flatnonzero(self.y == c) if len(sel) == 0: continue d = np.linalg.norm(self.X[sel] - np.asarray(Xq)[None, :], axis=1) order = np.argsort(d)[:per_class] picks += [(float(d[o]), int(sel[o])) for o in order] picks.sort() return picks
LETTERS = ["A", "B", "C", "D"]
def rag_block(pool: LabelledPool, Xq, coords_q, k_spec: int = 16, k_spat: int = 4, style: str = "compact", pixel_m: float = 30.0, max_spatial_px: float = 30.0, exclude: int | None = None) -> str: """ Turn retrieval into text.
exclude : index INTO THE POOL to leave out, for when the query pixel is itself a pool member. Without it the block states the answer: the identical row gives spectral distance 0.00 to its own class, makes itself "the single most similar known building", and shows up as "class X at 0 m". That is how the Amsterdam calibration shots were being rendered, so the per-class biases were fitted on a prompt distribution that never occurs at evaluation time. The Madrid training side avoids it structurally, by drawing each block's pool from the other blocks (`simulate_pools`, `exclude_block=`), but nothing stopped it here.
The field that carries the information is the DISTANCE TO THE NEAREST LABELLED EXAMPLE OF EACH CLASS - not a class histogram. The organisers hand out n labelled pixels *per class*, so the pool is balanced by construction and a histogram of the k nearest neighbours carries almost no signal while actively inviting the model to copy the majority. Per-class distances remove that failure mode by construction instead of patching it afterwards.
A second, independent channel reports the physically nearest labelled pixels in metres. The two are deliberately NOT fused into one tuned distance: there are no target labels to tune the weighting with, so the model is left to learn it. """ if len(pool) == 0: return "" Xq = np.asarray(Xq, dtype=float).ravel()
keep = np.ones(len(pool), dtype=bool) if exclude is not None: keep[int(exclude)] = False if not keep.any(): return "" n_kept = int(keep.sum()) lines = [f"Labelled buildings elsewhere in this city ({n_kept} of them, " f"{n_kept // 4} per age class)"]
# --- channel 1: spectral distance to the nearest example of each class --- per_class = {} for c in CLASSES: sel = np.flatnonzero((pool.y == c) & keep) if len(sel) == 0: continue d = np.linalg.norm(pool.X[sel] - Xq[None, :], axis=1) per_class[int(c)] = float(d.min()) if per_class: lines.append("- how far this pixel is from the most similar known " "building of each class (smaller = more similar): " + ", ".join(f"{LETTERS[c - 1]} {v:.2f}" for c, v in sorted(per_class.items()))) best = min(per_class, key=per_class.get) lines.append(f"- the single most similar known building is class " f"{LETTERS[best - 1]}")
# --- a soft, distance-weighted vote over the k nearest, per-class normalised # Ask for one extra neighbour when a row is excluded, so dropping it still # leaves k_spec of them. d, i = pool.spectral(Xq, k_spec + (exclude is not None)) d, i = d[0], i[0] if exclude is not None: m_keep = i != int(exclude) d, i = d[m_keep][:k_spec], i[m_keep][:k_spec] tau = float(np.median(d)) + 1e-9 w = np.exp(-(d / tau) ** 2) score = np.zeros(4) for c in CLASSES: m = pool.y[i] == c n_c = max(int(((pool.y == c) & keep).sum()), 1) score[c - 1] = w[m].sum() / n_c if score.sum() > 0: score = score / score.sum() lines.append("- similarity-weighted vote of the " f"{len(d)} most similar known buildings: " + ", ".join(f"{LETTERS[k]} {100 * score[k]:.0f}%" for k in range(4)))
# --- channel 2: physical distance --- ds, isp = pool.spatial(coords_q, k_spat + (exclude is not None)) ds, isp = ds[0], isp[0] if exclude is not None: m_keep = isp != int(exclude) ds, isp = ds[m_keep][:k_spat], isp[m_keep][:k_spat] near = ds <= max_spatial_px if near.any(): lines.append("- nearest known buildings on the ground: " + ", ".join(f"class {LETTERS[int(pool.y[j]) - 1]} at {m * pixel_m:.0f} m" for j, m in zip(isp[near], ds[near]))) else: lines.append(f"- no known building within " f"{max_spatial_px * pixel_m:.0f} m of this pixel") return "\n".join(lines)
# --------------------------------------------------------------------------- ## Metric space for retrieval# --------------------------------------------------------------------------- #def transfer_safe_columns(columns) -> list[str]: """ Columns whose *level* does not encode which city we are in.
Keep: spectral indices (a multiplicative gain cancels in a normalised ratio), every spread/std feature (an additive city offset cancels exactly in a standard deviation - the point most teams miss), year-on-year deltas, early-minus-late contrasts, slopes, chromaticity, and the change-event fields. Drop: raw band means and raw era means, which are precisely the "Madrid is brighter than Amsterdam" channel, and the data-availability flags, which encode that Amsterdam is cloudier. """ keep, drop_exact = [], {"has_early_data", "has_late_data", "n_observed_years", "first_observed_year", "last_observed_year"} # Anything that encodes WHICH INSTRUMENT took the picture. The satellite # selected for a given year differs between the two cities in 11 of the 25 # years from 2001 on, and OLI reads about 0.015 darker than TM/ETM+, so # these are city markers dressed up as physics. They stay in the feature # table so a model can absorb the nuisance, and stay out of any distance. sensor_marks = ("sat_share", "sat_switches", "_oli_minus_tm", "_oli_mean", "_tm_mean", "sat_code")
# Spectral INDEX names, matched case-sensitively on purpose. "NBR" the # index and "nbr_" the neighbourhood prefix are not the same thing, and # matching "nbr" case-insensitively conflated them: every single one of the # 15 `nbr_*` neighbourhood columns was admitted to the metric, including # `nbr_sr_brightness_mean` (city AUC 0.966), `nbr_sr_SWIR1_mean` (0.957) # and `nbr_n_within_radius`, a pure urban-density marker. That is exactly # the "Madrid is brighter than Amsterdam" channel this function exists to # remove, let in through the one clause meant to keep a burn ratio. INDEX_NAMES = ("NDVI", "NDBI", "_UI_", "MNDWI", "BSI", "NBR", "_TCG", "_TCW", "chrom")
def judge(name: str) -> bool: """Is this column's LEVEL free of city identity?""" lc = name.lower() is_index = any(ix in name for ix in INDEX_NAMES) or "chrom" in lc # Offset- and gain-cancelling shapes. `_diff` is a pixel minus its own # neighbourhood, so any city-wide offset cancels in it. safe = ("_std" in lc or lc.startswith("d_") or "_minus_" in lc or "_slope" in lc or "chrom" in lc or lc.startswith("step_") or "_cv" in lc or lc.endswith("_diff") or is_index) # A raw level dressed up as a mean. A difference of two levels is fine. unsafe = ("_mean" in lc and not ("_minus_" in lc or "_cv" in lc or lc.endswith("_diff")) and not is_index) return safe and not unsafe
for c in columns: if c in drop_exact or any(s in c for s in sensor_marks): continue # A neighbourhood aggregate inherits the transfer safety of whatever it # aggregates: the mean of a raw band over a 7x7 window is still a raw # band level, and the mean of NDVI is still a ratio. inner = c[4:] if c.lower().startswith("nbr_") else c if judge(inner): keep.append(c) return keep
class WhitenedMetric: """ PCA-whitening fitted on the TARGET city's own unlabelled features.
Plain Euclidean distance over these features triple-counts absolute brightness, because `Blue_mean`, `Blue_early_mean` and `Blue_late_mean` are near-duplicates. Whitening on the target city removes that redundancy and is the cheap stand-in for a learned metric. """
def __init__(self, n_components: int = 24): self.n_components = n_components
def fit(self, X): from sklearn.decomposition import PCA from sklearn.preprocessing import QuantileTransformer X = np.asarray(X, dtype=float) self.qt_ = QuantileTransformer(output_distribution="normal", n_quantiles=min(1000, len(X)), random_state=0).fit(X) k = min(self.n_components, X.shape[1], len(X)) self.pca_ = PCA(n_components=k, whiten=True, random_state=0) self.pca_.fit(self.qt_.transform(X)) return self
def transform(self, X): return self.pca_.transform(self.qt_.transform(np.asarray(X, dtype=float)))
def fit_transform(self, X): return self.fit(X).transform(X)
def window_stats(df, coord_cols=("px_key", "py_key"), feature_cols=None, windows=(1, 3), prefix="win"): """ Mean / std of a few features over square pixel windows around each pixel (radius 1 = 3x3, radius 3 = 7x7), plus the pixel-minus-window contrast.
Label-free, so it works at n = 0, and it is a local contrast rather than an absolute level, which is exactly the kind of quantity that survives the jump to another city. """ import pandas as pd from scipy.spatial import cKDTree
if feature_cols is None: feature_cols = [c for c in ("sr_brightness_mean", "sr_NDVI_mean", "sr_SWIR1_mean", "step_brightness_year", "sr_brightness_late_minus_early") if c in df.columns] coords = df[list(coord_cols)].to_numpy(float) V = df[list(feature_cols)].to_numpy(float) n, F = V.shape tree = cKDTree(coords) out = {} for r in windows: groups = tree.query_ball_point(coords, r=r * 1.4143, p=2) # One pass over pixels, all features at once. Looping per feature as # well would be F times as many Python iterations - 760k instead of # 152k on the real 76k-pixel city. mu = np.empty((n, F)) sd = np.empty((n, F)) cnt = np.empty(n) for i, g in enumerate(groups): block = V[g, :] mu[i] = block.mean(axis=0) sd[i] = block.std(axis=0, ddof=0) cnt[i] = len(g) w = 2 * r + 1 for j, c in enumerate(feature_cols): out[f"{prefix}{w}_{c}_mean"] = mu[:, j] out[f"{prefix}{w}_{c}_std"] = sd[:, j] out[f"{prefix}{w}_{c}_contrast"] = V[:, j] - mu[:, j] out[f"{prefix}{w}_n"] = cnt return pd.concat([df, pd.DataFrame(out, index=df.index)], axis=1)
def shots_block(pool: LabelledPool, Xq, render_fn, per_class: int = 1, max_shots: int = 4) -> str: """ In-context demonstrations: the nearest labelled pixel of each class, rendered with the same verbaliser and ending in its true answer. Class-balanced on purpose; majority-label bias is a real failure mode. """ if len(pool) == 0 or pool.rows is None: return "" picks = pool.stratified_spectral(Xq, per_class=per_class)[:max_shots] parts = ["Worked examples from this city:"] for _, j in picks: parts.append(render_fn(pool.rows.iloc[j], int(pool.y[j]))) return "\n\n".join(parts)
# --------------------------------------------------------------------------- ## Simulating the adaptation regime inside the training city# --------------------------------------------------------------------------- #def spatial_blocks(coords, n_blocks: int = 20) -> np.ndarray: """ Tile the city into roughly equal-area blocks by coordinate quantiles. Blocks, not random folds: neighbouring pixels share an era, so a random split would let a pixel retrieve its own back garden. """ coords = np.asarray(coords, dtype=float) side = int(np.ceil(np.sqrt(n_blocks))) bx = np.digitize(coords[:, 0], np.quantile(coords[:, 0], np.linspace(0, 1, side + 1)[1:-1])) by = np.digitize(coords[:, 1], np.quantile(coords[:, 1], np.linspace(0, 1, side + 1)[1:-1])) return bx * side + by
def simulate_pools(y, blocks, n_per_class: int, rng, exclude_block, allowed_blocks=None): """ Draw an n-per-class labelled pool from blocks other than the query's own.
exclude_block : one block id, or any iterable of them. allowed_blocks : if given, the pool may ONLY come from these blocks. Used to keep the spatial validation holdout out of the pool: without it, `exclude_block=b` alone still let a training block's retrieval text quote the labels of validation-block pixels, which is the one thing the holdout exists to prevent. """ y = np.asarray(y) blocks = np.asarray(blocks) excl = ({int(exclude_block)} if np.isscalar(exclude_block) else {int(b) for b in exclude_block}) ok = ~np.isin(blocks, list(excl)) if allowed_blocks is not None: ok &= np.isin(blocks, list({int(b) for b in allowed_blocks})) avail = np.flatnonzero(ok) picks = [] for c in CLASSES: pool_c = avail[y[avail] == c] if len(pool_c) == 0: continue picks.append(rng.choice(pool_c, size=min(n_per_class, len(pool_c)), replace=False)) return np.concatenate(picks) if picks else np.array([], dtype=int)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159"""Score notebook 3's two headline variants on ALL of Amsterdam.
Notebook 3 scored every variant on a fixed random subsample of Amsterdam to keepthe table affordable. This re-runs the two variants that win a prize categorywith the same labelled-sample draws, and scores every fitted model three ways:
full all 25,992 pixels minus the drawn shots <- the number to report sub2000 the fixed 2,000-pixel subsample <- reproduces the table sub8000 the fixed 8,000-pixel subsample <- what nb 3 now uses
The subsample columns are a fidelity check: if they reproduce the publishedtable, the full column was produced by the same models on the same draws.
Everything mirrors `evaluation.evaluate_protocol` as notebook 3 calls it:seed 42, shots drawn with rng(42 + 1000 n + r), shots removed from everyevaluation set, and the decision rule (tau 0.5 then the macro-F1 plug-in, withthe Madrid prior) applied to each evaluation set on its own, because theplug-in rule depends on the batch it is given.
`y_amsterdam` is read for exactly two things, as in the protocol: drawing thepermitted n-per-class sample and scoring.
python -I tools/full_score.py prototype results/full_score_prototype.json python -I tools/full_score.py upweighted results/full_score_upweighted.json"""from __future__ import annotations
import jsonimport osimport sysimport timefrom pathlib import Path
ROOT = Path(__file__).resolve().parent.parentsys.path.insert(0, str(ROOT / "src"))os.chdir(ROOT)
import numpy as npimport pandas as pd
import config as Cimport evaluation as Eimport gbdt as G
SEED = 42 # evaluate_protocol's default; notebook 3 keeps itN_LIST = (5, 25, 50, 100, 200)CHEAP_LGB = dict(n_estimators=400, learning_rate=0.06) # notebook 3, verbatim
VARIANTS = { "prototype": ("prototype, robust z + within-class Mahalanobis", lambda: G.mc_prototype(metric="within"), 12), "upweighted": ("upweighted shots, retrained", lambda: G.mc_shot_weighted( normalise="robustz", fit=lambda X, y, **kw: G.fit_lgbm(X, y, params=CHEAP_LGB, **kw)), 5),}
def load(): madrid = pd.read_parquet(C.PROC_DIR / "madrid_features.parquet") amsterdam = pd.read_parquet(C.PROC_DIR / "amsterdam_features.parquet") drop = {"px_key", "py_key", "age_class", "weighted_mean_year", "city"} feats = [c for c in madrid.columns if c not in drop and madrid[c].dtype.kind in "fiu"] dead = [c for c in feats if madrid[c].std() == 0 or amsterdam[c].std() == 0] feats = [c for c in feats if c not in dead] # notebook 3's "everything" return (madrid[feats].to_numpy(float), madrid["age_class"].to_numpy(), amsterdam[feats].to_numpy(float), amsterdam["age_class"].to_numpy(), feats, dead)
def main(): key, out_path = sys.argv[1], Path(sys.argv[2]) name, make, n_repeats = VARIANTS[key] X_mad, y_mad, X_ams, y_ams, feats, dead = load() print(f"{name}: {len(feats)} features, dead {dead}, " f"Madrid {X_mad.shape}, Amsterdam {X_ams.shape}", flush=True) assert len(feats) == 393, len(feats)
src_prior = np.array([(y_mad == c).mean() for c in E.CLASSES])
def decide(p): return E.adapt_pipeline(p, src_prior, tau=0.5)[0] # tau0.5_then_plugin
pools = {"full": np.arange(len(y_ams))} for k in (2000, 8000): pools[f"sub{k}"] = np.sort(np.random.default_rng(SEED).choice( len(y_ams), k, replace=False))
mc = make() draws = [] # Resume: every draw is fixed by (n, rep), so draws saved by an interrupted # run are exactly what a fresh run would recompute. if out_path.exists(): prev = json.loads(out_path.read_text()) if prev.get("key") == key and prev.get("seed") == SEED: draws = prev["draws"] print(f"resuming: {len(draws)} draws already saved", flush=True) done = {(d["n"], d["rep"]) for d in draws} t_all = time.time() for n in N_LIST: for r in range(n_repeats): if (n, r) in done: continue t0 = time.time() rng = np.random.default_rng(SEED + 1000 * n + r) shot_idx = E.draw_shots(y_ams, n, rng) fn = mc(X_mad, y_mad, X_ams, X_ams[shot_idx], y_ams[shot_idx]) P_all = np.asarray(fn(X_ams), dtype=float)
rec = dict(n=n, rep=r, n_shots=int(len(shot_idx))) for pname, pool in pools.items(): keep = np.setdiff1d(pool, shot_idx) if pname == "sub2000" and not draws: # Predicting all rows then indexing must equal predicting # the subset directly, as evaluate_protocol does. direct = np.asarray(fn(X_ams[keep]), dtype=float) assert np.allclose(direct, P_all[keep], atol=1e-10), \ "predictions are not row-wise" pred = decide(P_all[keep]) rec[pname] = float(E.macro_f1(y_ams[keep], pred)) rec[f"{pname}_n_scored"] = int(len(keep)) rec[f"{pname}_per_class"] = [ float(x) for x in E.per_class_f1(y_ams[keep], pred)] rec["seconds"] = round(time.time() - t0, 1) draws.append(rec) print(f"n={n:<4d} rep={r:<2d} full={rec['full']:.4f} " f"sub2000={rec['sub2000']:.4f} sub8000={rec['sub8000']:.4f} " f"({rec['seconds']}s)", flush=True) out_path.write_text(json.dumps( dict(variant=name, key=key, seed=SEED, n_repeats=n_repeats, complete=False, draws=draws), indent=1))
df = pd.DataFrame(draws) summary = {} for pname in pools: g = df.groupby("n")[pname] summary[pname] = {int(n): dict(mean=float(g.mean()[n]), std=float(g.std(ddof=1)[n])) for n in N_LIST} means = [summary[pname][n]["mean"] for n in N_LIST] summary[pname]["average"] = float(np.mean(means)) summary[pname]["peak"] = float(np.max(means)) out_path.write_text(json.dumps( dict(variant=name, key=key, seed=SEED, n_repeats=n_repeats, complete=True, minutes=round((time.time() - t_all) / 60, 1), summary=summary, draws=draws), indent=1)) print("\n" + pd.DataFrame({p: {n: summary[p][n]["mean"] for n in N_LIST} for p in pools}).round(4).to_string()) for p in pools: print(f"{p:8s} average {summary[p]['average']:.4f} " f"peak {summary[p]['peak']:.4f}") print(f"done in {(time.time() - t_all) / 60:.1f} min", flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277"""The two winning models from our Hack4Dev building-age entry, self-contained.
Needs only numpy, pandas, pyarrow, scikit-learn and lightgbm - none of theproject's src/ code. Every function here is a line-for-line port of the codethat produced the reported numbers (src/gbdt.py, src/evaluation.py); theexport script checked that the ports give identical results.
ZERO-SHOT LightGBM trained on Madrid only. Never sees an Amsterdam label. Load it from models/zero_shot_lgbm.txt, or retrain it. RETRAINED A fresh LightGBM on all of Madrid plus the n labelled Amsterdam pixels per class that the protocol hands you, those pixels weighted 30x. Refit for every draw of labelled pixels, so there is no single saved model - models/retrained_*.txt are two example draws, saved so you can inspect one.
Both use the same decision rule: tau = 0.5 logit adjustment by the Madrid classprior, then the macro-F1 plug-in rule. Chosen on Madrid alone.
Command line (run from this folder):
python winners.py zero-shot # score the saved model python winners.py retrained --n 25 --rep 0 # one draw, as reported python winners.py protocol --model retrained --reps 5 python winners.py protocol --model zero-shot --reps 3
Python:
import winners as W d = W.load_data() model = W.load_zero_shot() labels = W.decide(W.predict(model, d["X_ams"]), d["madrid_prior"])"""from __future__ import annotations
import argparseimport jsonfrom pathlib import Path
import numpy as npimport pandas as pd
HERE = Path(__file__).resolve().parentDATA = HERE / "data" / "processed"MODELS = HERE / "models"
CLASSES = np.array([1, 2, 3, 4]) # 1 = oldest ... 4 = newest; see READMESEED = 42
# Full-strength LightGBM (src/gbdt.py LGBM_PARAMS) - used by the zero-shot model.LGBM_PARAMS = dict( objective="multiclass", num_class=4, learning_rate=0.03, n_estimators=1200, num_leaves=31, max_depth=-1, min_child_samples=80, subsample=0.8, subsample_freq=1, colsample_bytree=0.6, reg_alpha=0.5, reg_lambda=5.0, max_bin=127, n_jobs=-1, random_state=SEED, verbosity=-1,)# The retrained variant was measured with notebook 3's cheaper settings,# because it refits on every draw. Same params otherwise.RETRAIN_OVERRIDES = dict(n_estimators=400, learning_rate=0.06)SHOT_WEIGHT = 30.0
# --------------------------------------------------------------------------- ## Data# --------------------------------------------------------------------------- #def feature_names() -> list[str]: return json.loads((MODELS / "meta.json").read_text())["feature_names"]
def load_data(data_dir: Path | str = DATA) -> dict: """Madrid and Amsterdam feature matrices in the exact training column order.""" data_dir = Path(data_dir) feats = feature_names() mad = pd.read_parquet(data_dir / "madrid_features.parquet") ams = pd.read_parquet(data_dir / "amsterdam_features.parquet") y_mad = mad["age_class"].to_numpy() return dict( X_mad=mad[feats].to_numpy(float), y_mad=y_mad, X_ams=ams[feats].to_numpy(float), y_ams=ams["age_class"].to_numpy(), coords_ams=ams[["px_key", "py_key"]].to_numpy(float), madrid_prior=np.array([(y_mad == c).mean() for c in CLASSES]), feature_names=feats, )
# --------------------------------------------------------------------------- ## Decision rule: tau-logit adjustment, then the macro-F1 plug-in# --------------------------------------------------------------------------- #def logit_adjust(proba, train_prior, tau=0.5): p = np.asarray(proba, dtype=float) adj = p / np.clip(np.asarray(train_prior, float), 1e-12, None) ** float(tau) return adj / np.clip(adj.sum(axis=1, keepdims=True), 1e-12, None)
def macro_f1_plugin(proba, prior, n_iter=50): """Ramaswamy et al.'s plug-in rule for macro F1. Uses no target labels, but it does look at the predicted class shares of the batch it is given, so call it on the whole set you want labelled, not row by row.""" P = np.asarray(proba, dtype=float) pi = np.asarray(prior, dtype=float) pi = pi / pi.sum() f1 = np.zeros(4) best = None for it in range(n_iter): q = np.clip(np.bincount(np.argmax(P, axis=1), minlength=4) / len(P), 1e-6, None) \ if it == 0 else q_new a = 2.0 / np.clip(pi + q, 1e-9, None) lab_idx = np.argmax(a[None, :] * (P - f1[None, :] / 2.0), axis=1) q_new = np.clip(np.bincount(lab_idx, minlength=4) / len(P), 1e-6, None) tp = np.array([P[lab_idx == k, k].sum() for k in range(4)]) / len(P) f1_new = 2 * tp / np.clip(pi + q_new, 1e-9, None) obj = float(np.mean(f1_new)) if best is None or obj > best[0]: best = (obj, CLASSES[lab_idx].copy()) if np.max(np.abs(f1_new - f1)) < 1e-6 and it > 0: break f1 = f1_new return best[1]
def decide(proba, madrid_prior, tau=0.5): """Class labels (1-4) from probabilities. Plain argmax would be CLASSES[proba.argmax(1)]; this rule was worth about +0.01 on Madrid.""" src = np.asarray(madrid_prior, float) src = src / src.sum() return macro_f1_plugin(logit_adjust(proba, src, tau), src)
def macro_f1(y_true, y_pred) -> float: from sklearn.metrics import f1_score return float(f1_score(y_true, y_pred, labels=CLASSES, average="macro", zero_division=0))
# --------------------------------------------------------------------------- ## Models# --------------------------------------------------------------------------- #def balanced_class_weights(y): y = np.asarray(y) counts = np.array([(y == c).sum() for c in CLASSES], dtype=float) return len(y) / (4.0 * np.clip(counts, 1, None))
def _fit_lgbm(X, y, params, class_weight=None, sample_weight=None): import lightgbm as lgb p = dict(params) if class_weight is not None: p["class_weight"] = class_weight m = lgb.LGBMClassifier(**p) m.fit(np.asarray(X), np.asarray(y) - 1, sample_weight=sample_weight) return m
def train_zero_shot(X_mad, y_mad): """Madrid only, class-balanced, raw features (no per-city scaling).""" cw = balanced_class_weights(y_mad) return _fit_lgbm(X_mad, y_mad, LGBM_PARAMS, class_weight=dict(zip(range(4), cw)))
def robustz_fit(X): X = np.asarray(X, dtype=np.float64) med = np.median(X, axis=0) q75, q25 = np.percentile(X, [75, 25], axis=0) iqr = np.where((q75 - q25) > 1e-12, q75 - q25, 1.0) return med, iqr
def robustz(X, stats): med, iqr = stats return (np.asarray(X, dtype=np.float64) - med) / iqr
def train_retrained(X_mad, y_mad, X_ams_all, X_shot, y_shot, shot_weight=SHOT_WEIGHT): """ Retrain on Madrid + the labelled Amsterdam shots, shots upweighted.
Each city is robust-z scaled with its OWN median/IQR. Amsterdam's are taken from its whole unlabelled feature matrix (features only, no labels) - the protocol passes that in, and the organisers' baseline does the same. Returns (model, amsterdam_stats); predict with predict_retrained(). """ mad_stats = robustz_fit(X_mad) ams_stats = robustz_fit(X_ams_all) X = np.vstack([robustz(X_mad, mad_stats), robustz(X_shot, ams_stats)]) y = np.r_[np.asarray(y_mad), np.asarray(y_shot)] w = np.r_[np.ones(len(y_mad)), np.full(len(y_shot), shot_weight)] w = w * balanced_class_weights(y)[y - 1] model = _fit_lgbm(X, y, {**LGBM_PARAMS, **RETRAIN_OVERRIDES}, sample_weight=w) return model, ams_stats
def predict(model, X): """Class probabilities, columns = classes 1..4. Accepts a fitted LGBMClassifier or a lightgbm.Booster loaded from models/*.txt.""" if hasattr(model, "predict_proba"): return model.predict_proba(np.asarray(X)) return model.predict(np.asarray(X))
def predict_retrained(model, ams_stats, X): return predict(model, robustz(X, ams_stats))
def load_zero_shot(): import lightgbm as lgb return lgb.Booster(model_file=str(MODELS / "zero_shot_lgbm.txt"))
def load_retrained_example(n: int): """One saved retrained model (draw rep 0 at this n) and its Amsterdam stats.""" import lightgbm as lgb booster = lgb.Booster(model_file=str(MODELS / f"retrained_n{n}_rep0_lgbm.txt")) z = np.load(MODELS / "amsterdam_robustz_stats.npz") return booster, (z["median"], z["iqr"])
# --------------------------------------------------------------------------- ## The official few-shot protocol# --------------------------------------------------------------------------- #def draw_shots(y_tgt, n_per_class, rng): """Stratified n-per-class sample - identical to src/evaluation.draw_shots.""" picks = [] for c in CLASSES: pool = np.flatnonzero(np.asarray(y_tgt) == c) if len(pool): picks.append(rng.choice(pool, size=min(n_per_class, len(pool)), replace=False)) return np.concatenate(picks)
def shots_for(y_ams, n, rep): """The exact draw we reported for (n, rep).""" return draw_shots(y_ams, n, np.random.default_rng(SEED + 1000 * n + rep))
def score_draw(d, model_name, n, rep, zero_shot_model=None): """Macro F1 on all of Amsterdam minus this draw's labelled pixels.""" shot = shots_for(d["y_ams"], n, rep) keep = np.setdiff1d(np.arange(len(d["y_ams"])), shot) if model_name == "zero-shot": m = zero_shot_model or load_zero_shot() P = predict(m, d["X_ams"][keep]) else: m, st = train_retrained(d["X_mad"], d["y_mad"], d["X_ams"], d["X_ams"][shot], d["y_ams"][shot]) P = predict_retrained(m, st, d["X_ams"][keep]) return macro_f1(d["y_ams"][keep], decide(P, d["madrid_prior"]))
def main(): ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("what", choices=["zero-shot", "retrained", "protocol"]) ap.add_argument("--model", choices=["zero-shot", "retrained"], default="retrained") ap.add_argument("--n", type=int, default=25) ap.add_argument("--rep", type=int, default=0) ap.add_argument("--reps", type=int, default=5) a = ap.parse_args() d = load_data() if a.what == "zero-shot": P = predict(load_zero_shot(), d["X_ams"]) print(f"zero-shot, all {len(P):,} Amsterdam pixels: macro F1 " f"{macro_f1(d['y_ams'], decide(P, d['madrid_prior'])):.4f}") elif a.what == "retrained": print(f"retrained, n={a.n} rep={a.rep}: macro F1 " f"{score_draw(d, 'retrained', a.n, a.rep):.4f}") else: zs = load_zero_shot() if a.model == "zero-shot" else None for n in (5, 25, 50, 100, 200): s = [score_draw(d, a.model, n, r, zs) for r in range(a.reps)] print(f"{a.model} n={n:<4d} macro F1 {np.mean(s):.4f} " f"+- {np.std(s, ddof=1) if len(s) > 1 else 0:.4f}", flush=True)
if __name__ == "__main__": main().gitattributes+2
README.mdAdded+296
data/processed/amsterdam_features.parquetAdded+3
data/processed/madrid_features.parquetAdded+3
models/amsterdam_robustz_stats.npzAdded+3
models/meta.jsonAdded+430
models/retrained_example_shot_indices.jsonAdded+1
models/retrained_n200_rep0_lgbm.txtAdded
models/retrained_n25_rep0_lgbm.txtAdded
models/zero_shot_lgbm.txtAdded+3
notebooks/01_build_features.ipynbAdded+437
notebooks/03_gbdt_models.ipynbAdded+747
notebooks/src/01_build_features.pyAdded+290
notebooks/src/03_gbdt_models.pyAdded+574
notebooks/src/winners_demo.pyAdded+171
notebooks/winners_demo.ipynbAdded
results/f1_vs_n_full_city.pngAdded

Large File Pointer Details
- SHA256: 8347ddf331b7ff0a40da5a9e24865a8774d5fbc59d89b1155a939e3097026422
- Pointer size: 131 Bytes
- Size of remote file: 118 kB
results/full_score_prototype.jsonAdded+1884
results/full_score_upweighted.jsonAdded+834
results/llm_protocol_results_colab.mdAdded+74
results/logs/01_build_features.logAdded+129
results/logs/03_gbdt_models.logAdded+305
results/logs/03_gbdt_models_fullscore_run.logAdded+192
results/logs/full_score_prototype.logAdded+74
results/logs/full_score_upweighted.logAdded+37
results/protocol_results.csvAdded+31
results/shift_harness.csvAdded+11
src/config.pyAdded+111
src/evaluation.pyAdded+519
src/features.pyAdded+634
src/gbdt.pyAdded+776
src/retrieval.pyAdded+420
tools/full_score.pyAdded+159
winners.pyAdded+277