Karar-git commited on
Commit
fe9543f
·
verified ·
1 Parent(s): 2c2dd6c

Add FINAL-2 pipeline, overnight search scripts and results (11 Nov 2026)

Browse files
README.md CHANGED
@@ -51,6 +51,10 @@ fixed decision rule:
51
  Then apply our decision rule: tau = 0.5 logit adjustment with the Madrid
52
  class prior, then the macro-F1 plug-in. The rule was chosen on Madrid.
53
 
 
 
 
 
54
  Macro F1 on all of Amsterdam, on draws 5–11 (seven per n). These draws were
55
  never used to choose anything.
56
 
@@ -124,8 +128,10 @@ From Python: `model_create(shot_idx, shot_labels).predict()` in
124
  hyper-parameters and the smoothing radius are copied, not re-tuned here, and
125
  this repo cannot show how they were chosen.
126
  - **The anchor ships as cached Amsterdam probabilities**
127
- (`data/processed/zeroshot_xgb_dann_ams.npz`). The code that builds it
128
- follows the teammate's code and is not in this repo.
 
 
129
  - **Fresh draws are not a fresh city.** They are new labelled pixels in the
130
  same Amsterdam.
131
  - **The neural networks use one seed.**
@@ -244,6 +250,7 @@ python tools/nnlab/model_create2.py --n 25 --rep 6 # FINAL-2, 1-2 min
244
  ```
245
 
246
  The neural and metric-learning scripts in `tools/nnlab/` also need `torch`.
 
247
 
248
  Expected output, from the verification run on our machine:
249
 
@@ -451,6 +458,8 @@ tools/nnlab/ the overnight search (11 November)
451
  classical.py SVM, logistic regression, kNN, LDA
452
  ts_nn.py networks on the raw yearly series (needs the hackathon raw data)
453
  transductive.py, ensemble.py, baselines.py, confirm.py, plot_confirm.py, model_create.py, lpft_steps.py
 
 
454
  tools/build_official60_first.py builds the 60-feature tables (needs the hackathon raw data)
455
  results/ per-draw JSON, logs of every run, the LLM results (first release)
456
  reports/nnlab/ results of the overnight search
 
51
  Then apply our decision rule: tau = 0.5 logit adjustment with the Madrid
52
  class prior, then the macro-F1 plug-in. The rule was chosen on Madrid.
53
 
54
+ The XGBoost + DANN anchor and the neighbour smoothing are a teammate's
55
+ design. Their functions are in `tools/compare_teammate.py`, published with
56
+ their agreement.
57
+
58
  Macro F1 on all of Amsterdam, on draws 5–11 (seven per n). These draws were
59
  never used to choose anything.
60
 
 
128
  hyper-parameters and the smoothing radius are copied, not re-tuned here, and
129
  this repo cannot show how they were chosen.
130
  - **The anchor ships as cached Amsterdam probabilities**
131
+ (`data/processed/zeroshot_xgb_dann_ams.npz`). `python
132
+ tools/full_score_combo.py zeroshot` rebuilds it in six to thirteen minutes and
133
+ needs xgboost and torch. On our CPU the rebuild is identical to the shipped
134
+ file.
135
  - **Fresh draws are not a fresh city.** They are new labelled pixels in the
136
  same Amsterdam.
137
  - **The neural networks use one seed.**
 
250
  ```
251
 
252
  The neural and metric-learning scripts in `tools/nnlab/` also need `torch`.
253
+ Rebuilding the zero-shot anchor needs `torch` and `xgboost`.
254
 
255
  Expected output, from the verification run on our machine:
256
 
 
458
  classical.py SVM, logistic regression, kNN, LDA
459
  ts_nn.py networks on the raw yearly series (needs the hackathon raw data)
460
  transductive.py, ensemble.py, baselines.py, confirm.py, plot_confirm.py, model_create.py, lpft_steps.py
461
+ tools/compare_teammate.py the teammate's XGBoost, DANN and smoothing functions
462
+ tools/full_score_combo.py `zeroshot` mode rebuilds the anchor cache
463
  tools/build_official60_first.py builds the 60-feature tables (needs the hackathon raw data)
464
  results/ per-draw JSON, logs of every run, the LLM results (first release)
465
  reports/nnlab/ results of the overnight search
reports/nnlab/OVERNIGHT_RESULTS.md CHANGED
@@ -199,7 +199,7 @@ Caveats that belong next to any headline number:
199
  ## Reproducing
200
 
201
  ```
202
- python -I tools/full_score_combo.py zeroshot # teammate's zero-shot cache (once; this script is not in the published repo, the cache is)
203
  python tools/nnlab/baselines.py all # references + retrained LightGBM per draw
204
  python tools/nnlab/lgbm_var.py # LightGBM variants, incl. lgbm_feda
205
  python tools/nnlab/ensemble.py e12 --zs zs_xgb_dann --shot lgbm_feda # FINAL-2
 
199
  ## Reproducing
200
 
201
  ```
202
+ python -I tools/full_score_combo.py zeroshot # teammate's zero-shot cache (once)
203
  python tools/nnlab/baselines.py all # references + retrained LightGBM per draw
204
  python tools/nnlab/lgbm_var.py # LightGBM variants, incl. lgbm_feda
205
  python tools/nnlab/ensemble.py e12 --zs zs_xgb_dann --shot lgbm_feda # FINAL-2
tools/compare_teammate.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Head-to-head: a teammate's pipeline against ours, on two common yardsticks.
3
+
4
+ NOTE FOR THIS BUNDLE. This file is here because tools/full_score_combo.py imports
5
+ it to rebuild the zero-shot anchor of FINAL-2 (its XGBoost, DANN, region
6
+ normalisation and smoothing functions). The head-to-head in main() needs the
7
+ teammate's lockbox block list, which is not in this repo, so main() cannot be run
8
+ from the bundle.
9
+
10
+ lockbox their own Madrid test: train on their 80% dev blocks, score once on
11
+ their 29 locked 2 km blocks (15,157 px). Rebuilt from our pixel keys
12
+ with their block rule. Their own lockbox scores, which are not in
13
+ this repo, were the fidelity check.
14
+ amsterdam train on ALL of Madrid, score ALL 25,992 Amsterdam pixels with no
15
+ Amsterdam labels used except to score (zero-shot: the setting their
16
+ pipeline was built for).
17
+
18
+ The functions here are adapted from the teammate's code and published with their
19
+ agreement. One difference: XGBoost and the DANN run
20
+ on CPU because this PC has no CUDA (different random streams; their DANN seeds
21
+ vary by 0.002-0.004). Their features are the official 60 on the same pixels:
22
+ pass `first` as the third argument to use the organisers' exact construction
23
+ (tools/build_official60_first.py); the default is our median-per-year rebuild.
24
+
25
+ Every model is scored under two decision rules:
26
+ argmax what their pipeline uses
27
+ tau+plugin ours: tau=0.5 logit adjustment then the macro-F1 plug-in, Madrid prior
28
+ and with/without their neighbour smoothing (r = 6 px = 180 m, alpha 0.5).
29
+
30
+ python -I tools/compare_teammate.py <lockbox_blocks.json> reports/teammate_compare.csv
31
+ """
32
+ from __future__ import annotations
33
+
34
+ import json
35
+ import os
36
+ import sys
37
+ import time
38
+ from pathlib import Path
39
+
40
+ ROOT = Path(__file__).resolve().parent.parent
41
+ sys.path.insert(0, str(ROOT / "src"))
42
+ os.chdir(ROOT)
43
+
44
+ import numpy as np
45
+ import pandas as pd
46
+ import torch
47
+ import torch.nn as nn
48
+ from lightgbm import LGBMClassifier
49
+ from scipy.spatial import cKDTree
50
+ from sklearn.ensemble import RandomForestClassifier
51
+ from sklearn.utils.class_weight import compute_sample_weight
52
+ from xgboost import XGBClassifier
53
+
54
+ import config as C
55
+ import evaluation as E
56
+ import gbdt as G
57
+
58
+ torch.set_num_threads(max(1, (os.cpu_count() or 4) - 2))
59
+ DEV = torch.device("cpu")
60
+ BLOCK = 67
61
+ SMOOTH_ALPHA = 0.5
62
+ R_PX = 6
63
+ XGB_PARAMS = {"n_estimators": 500, "learning_rate": 0.08, "max_depth": 8,
64
+ "min_child_weight": 3.0, "subsample": 0.8, "colsample_bytree": 1.0,
65
+ "reg_lambda": 10.0, "gamma": 1.0} # their best_config.json
66
+ DANN_EPOCHS, DANN_SEEDS = 40, (0, 1, 2)
67
+
68
+
69
+ # ---- copied from their compare_models.py ---------------------------------- #
70
+ def block_ids(pid):
71
+ return (pid[:, 0] // BLOCK) * 100000 + (pid[:, 1] // BLOCK)
72
+
73
+
74
+ def region_norm(X):
75
+ mu, sd = X.mean(0), X.std(0)
76
+ sd[sd == 0] = 1
77
+ return (X - mu) / sd
78
+
79
+
80
+ def smooth(P, coords, r):
81
+ tree = cKDTree(coords)
82
+ nbrs = tree.query_ball_point(coords, r=r)
83
+ out = np.empty_like(P)
84
+ for i, nb in enumerate(nbrs):
85
+ out[i] = SMOOTH_ALPHA * P[i] + (1 - SMOOTH_ALPHA) * P[nb].mean(0)
86
+ return out
87
+
88
+
89
+ # ---- copied from their dann.py --------------------------------------------- #
90
+ class GradReverse(torch.autograd.Function):
91
+ @staticmethod
92
+ def forward(ctx, x, lam):
93
+ ctx.lam = lam
94
+ return x.view_as(x)
95
+
96
+ @staticmethod
97
+ def backward(ctx, g):
98
+ return -ctx.lam * g, None
99
+
100
+
101
+ class DANN(nn.Module):
102
+ def __init__(self, d_in=60, h=256, z=64):
103
+ super().__init__()
104
+ self.feat = nn.Sequential(nn.Linear(d_in, h), nn.BatchNorm1d(h), nn.ReLU(), nn.Dropout(0.2),
105
+ nn.Linear(h, h), nn.BatchNorm1d(h), nn.ReLU(), nn.Dropout(0.2),
106
+ nn.Linear(h, z), nn.ReLU())
107
+ self.age = nn.Sequential(nn.Linear(z, 64), nn.ReLU(), nn.Linear(64, 4))
108
+ self.city = nn.Sequential(nn.Linear(z, 64), nn.ReLU(), nn.Linear(64, 1))
109
+
110
+ def forward(self, x, lam=0.0):
111
+ f = self.feat(x)
112
+ return self.age(f), self.city(GradReverse.apply(f, lam)), f
113
+
114
+
115
+ def train_dann(Xs, ys, Xt, epochs, adversarial=True, seed=0):
116
+ torch.manual_seed(seed)
117
+ np.random.seed(seed)
118
+ net = DANN(Xs.shape[1]).to(DEV)
119
+ opt = torch.optim.AdamW(net.parameters(), lr=1e-3, weight_decay=1e-4)
120
+ counts = np.bincount(ys, minlength=5)[1:]
121
+ w = torch.tensor(len(ys) / (4 * counts), dtype=torch.float32, device=DEV)
122
+ ce, bce = nn.CrossEntropyLoss(weight=w), nn.BCEWithLogitsLoss()
123
+ S, Y = torch.tensor(Xs, dtype=torch.float32, device=DEV), torch.tensor(ys - 1, device=DEV)
124
+ T = torch.tensor(Xt, dtype=torch.float32, device=DEV)
125
+ bs, steps = 512, int(np.ceil(len(S) / 512))
126
+ for ep in range(epochs):
127
+ net.train()
128
+ perm_s = torch.randperm(len(S), device=DEV)
129
+ for k in range(steps):
130
+ p = (ep * steps + k) / (epochs * steps)
131
+ lam = (2 / (1 + np.exp(-10 * p)) - 1) if adversarial else 0.0
132
+ i = perm_s[k * bs:(k + 1) * bs]
133
+ j = torch.randint(0, len(T), (len(i),), device=DEV)
134
+ ya, cs, _ = net(S[i], lam)
135
+ _, ct, _ = net(T[j], lam)
136
+ loss = ce(ya, Y[i])
137
+ if adversarial:
138
+ loss = loss + bce(cs.squeeze(1), torch.zeros(len(i), device=DEV)) \
139
+ + bce(ct.squeeze(1), torch.ones(len(j), device=DEV))
140
+ opt.zero_grad()
141
+ loss.backward()
142
+ opt.step()
143
+ net.eval()
144
+ return net
145
+
146
+
147
+ @torch.no_grad()
148
+ def dann_proba(net, X):
149
+ a, _, _ = net(torch.tensor(X, dtype=torch.float32, device=DEV))
150
+ return torch.softmax(a, 1).cpu().numpy()
151
+
152
+
153
+ # ---- their tree models (final_lockbox.py / tune_boosting.py) --------------- #
154
+ def their_trees(Xtr, ytr, Xte):
155
+ sw = compute_sample_weight("balanced", ytr)
156
+ xgb = XGBClassifier(objective="multi:softprob", tree_method="hist", device="cpu",
157
+ eval_metric="mlogloss", random_state=42, **XGB_PARAMS)
158
+ xgb.fit(Xtr, ytr - 1, sample_weight=sw)
159
+ lgb = LGBMClassifier(n_estimators=600, learning_rate=0.05, num_leaves=63, subsample=0.8,
160
+ subsample_freq=1, colsample_bytree=0.8, class_weight="balanced",
161
+ n_jobs=6, random_state=42, verbose=-1).fit(Xtr, ytr)
162
+ rf = RandomForestClassifier(n_estimators=300, class_weight="balanced", n_jobs=6,
163
+ random_state=42).fit(Xtr, ytr)
164
+ return {"T: XGBoost (tuned)": xgb.predict_proba(Xte),
165
+ "T: LightGBM": lgb.predict_proba(Xte),
166
+ "T: Random Forest": rf.predict_proba(Xte)}
167
+
168
+
169
+ # ---- ours ------------------------------------------------------------------ #
170
+ def our_lgbm(Xtr, ytr, Xte):
171
+ """notebook 3's 'zero-shot, no normalisation': full LGBM_PARAMS, balanced."""
172
+ cw = G.balanced_class_weights(ytr)
173
+ m = G.fit_lgbm(Xtr, ytr, class_weight=dict(zip(range(4), cw)))
174
+ return m.predict_proba(Xte)
175
+
176
+
177
+ def load(official: str = "median"):
178
+ mad = pd.read_parquet(C.PROC_DIR / "madrid_features.parquet")
179
+ ams = pd.read_parquet(C.PROC_DIR / "amsterdam_features.parquet")
180
+ drop = {"px_key", "py_key", "age_class", "weighted_mean_year", "city"}
181
+ feats = [c for c in mad.columns if c not in drop and mad[c].dtype.kind in "fiu"]
182
+ feats = [c for c in feats if not (mad[c].std() == 0 or ams[c].std() == 0)]
183
+ assert len(feats) == 393, len(feats)
184
+ f60 = list(C.FEATURE_COLS_60) # all 60, as their pkl has
185
+ if official == "first":
186
+ # The organisers' exact construction (first QA-valid observation per
187
+ # year), from tools/build_official60_first.py, aligned row by row.
188
+ def aligned(city, ref):
189
+ o = pd.read_parquet(C.PROC_DIR / f"{city}_official60_first.parquet")
190
+ has_label = "age_class" in o.columns # the published tables carry no label
191
+ o = ref[C.PID + ["age_class"]].merge(o, on=C.PID, how="left",
192
+ suffixes=("", "_o"))
193
+ assert o[f60].notna().all().all() and len(o) == len(ref)
194
+ assert not has_label or (o["age_class"] == o["age_class_o"]).all()
195
+ return o[f60].to_numpy(float)
196
+ Xm60, Xa60 = aligned("madrid", mad), aligned("amsterdam", ams)
197
+ else:
198
+ Xm60, Xa60 = mad[f60].to_numpy(float), ams[f60].to_numpy(float)
199
+ print(f"official 60 built with agg={official}", flush=True)
200
+ return dict(
201
+ Xm60=Xm60, Xa60=Xa60,
202
+ Xm=mad[feats].to_numpy(float), Xa=ams[feats].to_numpy(float),
203
+ ym=mad["age_class"].to_numpy().astype(int), ya=ams["age_class"].to_numpy().astype(int),
204
+ pm=mad[C.PID].to_numpy().astype(np.int64), pa=ams[C.PID].to_numpy().astype(np.int64))
205
+
206
+
207
+ def run_setting(name, d, tr, te_X60, te_X, te_y, te_xy, Xadv60):
208
+ """Fit every model on Madrid rows `tr`, score on the given test set."""
209
+ t0 = time.time()
210
+ Xtr60, Xtr, ytr = d["Xm60"][tr], d["Xm"][tr], d["ym"][tr]
211
+ prior = np.array([(ytr == c).mean() for c in E.CLASSES])
212
+ P = their_trees(Xtr60, ytr, te_X60)
213
+ print(f"[{name}] their trees done {time.time() - t0:.0f}s", flush=True)
214
+ P["O: LightGBM, 393 features (our zero-shot)"] = our_lgbm(Xtr, ytr, te_X)
215
+ P["O: LightGBM, official 60 (our params)"] = our_lgbm(Xtr60, ytr, te_X60)
216
+ print(f"[{name}] our LightGBM done {time.time() - t0:.0f}s", flush=True)
217
+ seeds = {}
218
+ Xtr_n, Xte_n, Xadv_n = region_norm(Xtr60), region_norm(te_X60), region_norm(Xadv60)
219
+ for s in DANN_SEEDS:
220
+ net = train_dann(Xtr_n, ytr, Xadv_n, DANN_EPOCHS, adversarial=True, seed=s)
221
+ Pd = dann_proba(net, Xte_n)
222
+ seeds[s] = {"T: DANN": Pd,
223
+ "T: XGBoost + DANN (their FINAL)": (P["T: XGBoost (tuned)"] + Pd) / 2}
224
+ print(f"[{name}] DANN seed {s} done {time.time() - t0:.0f}s", flush=True)
225
+
226
+ coords = te_xy.astype(float)
227
+ rows = []
228
+
229
+ def score(model, seed, PP):
230
+ for sm in (False, True):
231
+ Q = smooth(PP, coords, R_PX) if sm else PP
232
+ for rule in ("argmax", "tau+plugin"):
233
+ lab = (np.array(E.CLASSES)[Q.argmax(1)] if rule == "argmax"
234
+ else E.adapt_pipeline(Q, prior, tau=0.5)[0])
235
+ pc = E.per_class_f1(te_y, lab)
236
+ rows.append(dict(setting=name, model=model, seed=seed, smooth=sm, rule=rule,
237
+ macro_f1=E.macro_f1(te_y, lab),
238
+ **{f"f1_c{c}": float(v) for c, v in zip(E.CLASSES, pc)},
239
+ n_test=len(te_y)))
240
+
241
+ for k, PP in P.items():
242
+ score(k, 0, PP)
243
+ for s, dd in seeds.items():
244
+ for k, PP in dd.items():
245
+ score(k, s, PP)
246
+ print(f"[{name}] scored, {time.time() - t0:.0f}s total", flush=True)
247
+ return rows
248
+
249
+
250
+ def main():
251
+ lock_json, out_csv = Path(sys.argv[1]), Path(sys.argv[2])
252
+ d = load(sys.argv[3] if len(sys.argv) > 3 else "median")
253
+ g = block_ids(d["pm"])
254
+ lock = np.isin(g, json.loads(lock_json.read_text())["blocks"])
255
+ print(f"lockbox pixels {lock.sum():,} (theirs: 15,157); dev {(~lock).sum():,} "
256
+ f"(theirs: 61,106)", flush=True)
257
+ assert lock.sum() == 15157 and (~lock).sum() == 61106
258
+
259
+ rows = []
260
+ dev, lk = np.flatnonzero(~lock), np.flatnonzero(lock)
261
+ rows += run_setting("lockbox", d, dev, d["Xm60"][lk], d["Xm"][lk], d["ym"][lk],
262
+ d["pm"][lk], d["Xa60"])
263
+ pd.DataFrame(rows).to_csv(out_csv, index=False)
264
+ allm = np.arange(len(d["ym"]))
265
+ rows += run_setting("amsterdam", d, allm, d["Xa60"], d["Xa"], d["ya"], d["pa"], d["Xa60"])
266
+ df = pd.DataFrame(rows)
267
+ df.to_csv(out_csv, index=False)
268
+
269
+ summ = (df.groupby(["setting", "model", "smooth", "rule"])["macro_f1"]
270
+ .agg(["mean", "std", "size"]).round(4).reset_index())
271
+ for st in ("lockbox", "amsterdam"):
272
+ t = summ[summ.setting == st].pivot_table(index="model", columns=["rule", "smooth"],
273
+ values="mean")
274
+ print(f"\n=== {st} (macro F1; DANN rows = mean of 3 seeds) ===")
275
+ print(t.sort_values(("argmax", True), ascending=False).to_string())
276
+
277
+
278
+ if __name__ == "__main__":
279
+ main()
tools/full_score_combo.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ NOTE FOR THIS BUNDLE. Only one mode of this script is used here:
3
+
4
+ python tools/full_score_combo.py zeroshot
5
+
6
+ It rebuilds data/processed/zeroshot_xgb_dann_ams.npz, the zero-shot anchor of the
7
+ FINAL-2 pipeline (tools/nnlab/model_create2.py): a teammate's XGBoost and DANN on
8
+ the official 60 features, from tools/compare_teammate.py. It needs xgboost and
9
+ torch and takes six to thirteen minutes on a 12-thread CPU. The combination described
10
+ below is NOT FINAL-2, and its numbers are not quoted anywhere in this bundle.
11
+
12
+ Our few-shot winners combined with the teammate's DANN and neighbour smoothing,
13
+ scored on ALL of Amsterdam under the official protocol.
14
+
15
+ Intended as the primary model when this script was written (2026-11-10). This
16
+ bundle holds no time-stamped record of that, and Amsterdam scores of its
17
+ ingredients (the upweighted LightGBM, the teammate's zero-shot pipeline) had
18
+ already been seen. The primary model is
19
+ "upweighted + DANN + smooth":
20
+ p = (P_upweighted_lgbm + P_dann) / 2 -> neighbour smoothing (6 px) -> our rule
21
+ Every ingredient was chosen on Madrid, not Amsterdam:
22
+ * upweighted retrained LightGBM - notebook 3's design, 393 features;
23
+ * DANN (60 official features, adversary on UNLABELLED Amsterdam) and the
24
+ 50/50 probability average with a tree model - teammate's design, +0.014 on
25
+ their Madrid lockbox;
26
+ * neighbour smoothing r = 6 px, alpha 0.5 - teammate's choice on Madrid
27
+ (+0.025 on their CV); ours (r = 2) also gained on Madrid;
28
+ * decision rule tau 0.5 then the macro-F1 plug-in with the Madrid prior -
29
+ chosen on Madrid by the shift harness.
30
+ The other rows are ablations that show what each ingredient contributes. Some
31
+ were added after Amsterdam results had been seen.
32
+
33
+ One deliberate change from the teammate: the 3 DANN seeds are averaged into one
34
+ probability (their lockbox reported seeds separately), so a protocol draw does not
35
+ depend on which seed was used.
36
+
37
+ Protocol: identical to tools/full_score.py. Seed 42, shots drawn with
38
+ rng(42 + 1000 n + rep), shots removed from the scored set, and every draw scored on
39
+ all remaining Amsterdam pixels. Smoothing uses only the scored pixels as
40
+ neighbours (no shot, no label), as in the teammate's code. Amsterdam labels are
41
+ read only to draw the shots and to score.
42
+
43
+ python -I tools/full_score_combo.py zeroshot # cache XGB + DANN
44
+ python -I tools/full_score_combo.py upweighted reports/combo_upweighted.json
45
+ python -I tools/full_score_combo.py prototype reports/combo_prototype.json
46
+ """
47
+ from __future__ import annotations
48
+
49
+ import json
50
+ import sys
51
+ import time
52
+ from pathlib import Path
53
+
54
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
55
+ import compare_teammate as CT # noqa: E402 (also puts src/ on the path, chdirs to root)
56
+ import full_score as FS # noqa: E402
57
+
58
+ import numpy as np # noqa: E402
59
+ import pandas as pd # noqa: E402
60
+
61
+ import config as C # noqa: E402
62
+ import evaluation as E # noqa: E402
63
+
64
+ SEED, N_LIST, R_PX = 42, (5, 25, 50, 100, 200), 6
65
+ CACHE = C.PROC_DIR / "zeroshot_xgb_dann_ams.npz"
66
+
67
+
68
+ def build_cache(d):
69
+ """Zero-shot parts: they never see a shot, so they are fitted once."""
70
+ t0 = time.time()
71
+ sw = CT.compute_sample_weight("balanced", d["ym"])
72
+ xgb = CT.XGBClassifier(objective="multi:softprob", tree_method="hist", device="cpu",
73
+ eval_metric="mlogloss", random_state=42, **CT.XGB_PARAMS)
74
+ xgb.fit(d["Xm60"], d["ym"] - 1, sample_weight=sw)
75
+ P_xgb = xgb.predict_proba(d["Xa60"])
76
+ Xm_n, Xa_n = CT.region_norm(d["Xm60"]), CT.region_norm(d["Xa60"])
77
+ P_d = []
78
+ for s in CT.DANN_SEEDS:
79
+ net = CT.train_dann(Xm_n, d["ym"], Xa_n, CT.DANN_EPOCHS, adversarial=True, seed=s)
80
+ P_d.append(CT.dann_proba(net, Xa_n))
81
+ print(f"DANN seed {s} done {time.time() - t0:.0f}s", flush=True)
82
+ np.savez(CACHE, P_xgb=P_xgb, P_dann_seeds=np.stack(P_d), pa=d["pa"])
83
+ print(f"cached -> {CACHE}", flush=True)
84
+
85
+
86
+ def main():
87
+ mode = sys.argv[1]
88
+ d = CT.load("first")
89
+ if mode == "zeroshot":
90
+ build_cache(d)
91
+ return
92
+ out_path = Path(sys.argv[2])
93
+ z = np.load(CACHE)
94
+ assert (z["pa"] == d["pa"]).all()
95
+ P_dann = z["P_dann_seeds"].mean(0) # seed-averaged
96
+ P_final = (z["P_xgb"] + P_dann) / 2 # teammate's FINAL, zero-shot
97
+
98
+ name, make, n_repeats = FS.VARIANTS[mode]
99
+ X_mad, y_mad, X_ams, y_ams = d["Xm"], d["ym"], d["Xa"], d["ya"]
100
+ src_prior = np.array([(y_mad == c).mean() for c in E.CLASSES])
101
+ coords = d["pa"].astype(float)
102
+ base = "upweighted" if mode == "upweighted" else "prototype"
103
+
104
+ def rules(P, y):
105
+ out = {}
106
+ out["argmax"] = E.macro_f1(y, np.array(E.CLASSES)[P.argmax(1)])
107
+ out["tau+plugin"] = E.macro_f1(y, E.adapt_pipeline(P, src_prior, tau=0.5)[0])
108
+ return out
109
+
110
+ draws = []
111
+ if out_path.exists():
112
+ prev = json.loads(out_path.read_text())
113
+ if prev.get("key") == mode:
114
+ draws = prev["draws"]
115
+ print(f"resuming: {len(draws)} draws already saved", flush=True)
116
+ done = {(r["n"], r["rep"]) for r in draws}
117
+ mc = make()
118
+ t_all = time.time()
119
+ for n in N_LIST:
120
+ for r in range(n_repeats):
121
+ if (n, r) in done:
122
+ continue
123
+ t0 = time.time()
124
+ rng = np.random.default_rng(SEED + 1000 * n + r)
125
+ shot_idx = E.draw_shots(y_ams, n, rng)
126
+ keep = np.setdiff1d(np.arange(len(y_ams)), shot_idx)
127
+ fn = mc(X_mad, y_mad, X_ams, X_ams[shot_idx], y_ams[shot_idx])
128
+ Pb = np.asarray(fn(X_ams[keep]), dtype=float)
129
+ ck, yk = coords[keep], y_ams[keep]
130
+ combos = {
131
+ f"{base}": Pb,
132
+ f"{base} + smooth": CT.smooth(Pb, ck, R_PX),
133
+ f"{base} + DANN": (Pb + P_dann[keep]) / 2,
134
+ f"{base} + DANN + smooth": CT.smooth((Pb + P_dann[keep]) / 2, ck, R_PX),
135
+ }
136
+ if mode == "upweighted": # zero-shot references, cheap, scored per draw
137
+ combos["their FINAL (zero-shot)"] = P_final[keep]
138
+ combos["their FINAL + smooth (zero-shot)"] = CT.smooth(P_final[keep], ck, R_PX)
139
+ rec = dict(n=n, rep=r, n_scored=int(len(keep)))
140
+ for k, P in combos.items():
141
+ for rule, v in rules(P, yk).items():
142
+ rec[f"{k} | {rule}"] = float(v)
143
+ rec["seconds"] = round(time.time() - t0, 1)
144
+ draws.append(rec)
145
+ print(f"n={n:<4d} rep={r:<2d} " + " ".join(
146
+ f"{k}={rec[k + ' | tau+plugin']:.4f}" for k in combos) +
147
+ f" ({rec['seconds']}s)", flush=True)
148
+ out_path.write_text(json.dumps(dict(key=mode, variant=name, seed=SEED,
149
+ complete=False, draws=draws), indent=1))
150
+
151
+ df = pd.DataFrame(draws)
152
+ cols = [c for c in df.columns if " | " in c]
153
+ g = df.groupby("n")[cols]
154
+ summ = {c: {**{int(n): dict(mean=float(g.mean().loc[n, c]), std=float(g.std(ddof=1).loc[n, c]))
155
+ for n in N_LIST},
156
+ "average": float(g.mean()[c].mean()), "peak": float(g.mean()[c].max())}
157
+ for c in cols}
158
+ out_path.write_text(json.dumps(dict(key=mode, variant=name, seed=SEED, complete=True,
159
+ minutes=round((time.time() - t_all) / 60, 1),
160
+ summary=summ, draws=draws), indent=1))
161
+ tbl = pd.DataFrame({c: {**{n: summ[c][n]["mean"] for n in N_LIST},
162
+ "avg": summ[c]["average"]} for c in cols}).T
163
+ print("\n" + tbl.round(4).to_string(), flush=True)
164
+
165
+
166
+ if __name__ == "__main__":
167
+ main()
tools/nnlab/tab_nn.py CHANGED
@@ -10,7 +10,7 @@ wd 1e-4, batch 512, seeds 0,1,2):
10
  BN-ReLU -> Linear(64)-ReLU -> Linear(64,4)
11
  dann mlp + domain head (Lin(64,64)-ReLU-Lin(64,1)) on the first 64-d features through
12
  gradient reversal, lambda = 2/(1+exp(-10p))-1, adversary vs UNLABELLED Amsterdam rows
13
- (as in the teammate's DANN; Madrid and Amsterdam batches go through
14
  the net separately)
15
  coral mlp + deep-CORAL loss (weight 1.0) between the penultimate features of a Madrid
16
  batch and an unlabelled Amsterdam batch
 
10
  BN-ReLU -> Linear(64)-ReLU -> Linear(64,4)
11
  dann mlp + domain head (Lin(64,64)-ReLU-Lin(64,1)) on the first 64-d features through
12
  gradient reversal, lambda = 2/(1+exp(-10p))-1, adversary vs UNLABELLED Amsterdam rows
13
+ (as tools/compare_teammate.py train_dann; Madrid and Amsterdam batches go through
14
  the net separately)
15
  coral mlp + deep-CORAL loss (weight 1.0) between the penultimate features of a Madrid
16
  batch and an unlabelled Amsterdam batch