File size: 7,789 Bytes
99f65bd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 | """
STER — Zero-shot Geospatial ER (GPU).
TRUE zero-shot: train ONLY on free 3DBAG multi-LoD self-supervision (same building's
LoD1.2 vs LoD2.2). NO Hague labels are ever used — even the decision threshold is
calibrated on a held-out multi-LoD split. Then transfer to the Hague CityModel<->3DBAG
test set (hard negatives). Tests whether transformation/identity structure learned on
the LoD gap transfers to the (unseen) source gap.
Methods:
base_raw_transfer_bagging : Bagging on multi-LoD ratio pairs (hard negs) -> Hague
base_raw_cos : cosine of raw std property vecs, thr from multi-LoD
wm_zeroshot_cos : InfoNCE identity encoder cosine, thr from multi-LoD (WM)
flow_zeroshot : Conditional Flow Matching residual score, thr from ML (4B)
"""
import os, json, numpy as np, torch, torch.nn as nn, torch.nn.functional as F
from sklearn.ensemble import BaggingClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import NearestNeighbors
from sklearn.metrics import f1_score, precision_score, recall_score
NPZ = "/root/ster/data/ster_wm_vectors.npz"
OUT = "/root/ster/exp/ster_zeroshot_results.json"
DEV = "cuda" if torch.cuda.is_available() else "cpu"
torch.manual_seed(1); np.random.seed(1)
z = np.load(NPZ, allow_pickle=True)
lod12, lod22 = z["lod12_X"], z["lod22_X"]
candX, indexX = z["cand_X"], z["index_X"]
teP, teY = z["test_pairs"], z["test_y"]
N = lod12.shape[0]; DIM = lod12.shape[1]
print(f"multiLoD={lod12.shape} Hague test={teP.shape} pos={teY.sum()} dev={DEV}", flush=True)
scaler = StandardScaler().fit(np.vstack([lod12, lod22, candX, indexX]))
def T(x): return torch.tensor(scaler.transform(x), dtype=torch.float32, device=DEV)
L12t, L22t = T(lod12), T(lod22)
CANDt, INDEXt = T(candX), T(indexX)
L12s, L22s = scaler.transform(lod12), scaler.transform(lod22)
CANDs, INDEXs = scaler.transform(candX), scaler.transform(indexX)
# split multi-LoD into train / calib (for thresholds) — no Hague labels used
idx = np.random.permutation(N); ntr = int(0.8 * N)
mtr, mcal = idx[:ntr], idx[ntr:]
# ---- build multi-LoD ratio pairs with HARD negatives (top-k NN among LoD22) ----
nn = NearestNeighbors(n_neighbors=6).fit(L22s)
_, knn = nn.kneighbors(L12s) # for each LoD12, nearest LoD22 buildings
def ratio(a, b):
with np.errstate(divide='ignore', invalid='ignore'):
r = np.where(b != 0, a / b, 1000.0)
return np.clip(np.round(r, 3), None, 1000.0)
def make_ml_pairs(ids):
Xr, Y = [], []
for i in ids:
Xr.append(ratio(L12s[i], L22s[i])); Y.append(1)
for j in knn[i][1:3]:
if j != i:
Xr.append(ratio(L12s[i], L22s[j])); Y.append(0)
return np.array(Xr), np.array(Y)
Xr_tr, Yr_tr = make_ml_pairs(mtr)
# Hague test raw ratio features
Xr_te = ratio(candX[teP[:, 0]], indexX[teP[:, 1]])
# calibration pairs (multi-LoD held out): scores for pos and hard-neg
def ml_calib_scores(score_fn):
pos, neg = [], []
for i in mcal:
pos.append(score_fn(i, i, kind='ml'))
for j in knn[i][1:3]:
if j != i:
neg.append(score_fn(i, j, kind='ml'))
return np.array(pos), np.array(neg)
def thr_from(pos, neg):
return float(np.median([np.quantile(pos, 0.2), np.quantile(neg, 0.8)]))
report = {}
# 1) raw transfer Bagging
clf = BaggingClassifier(n_estimators=100, random_state=1).fit(Xr_tr, Yr_tr)
pred = clf.predict(Xr_te)
report["base_raw_transfer_bagging"] = dict(
f1=round(f1_score(teY, pred, zero_division=0), 4),
precision=round(precision_score(teY, pred, zero_division=0), 4),
recall=round(recall_score(teY, pred, zero_division=0), 4))
# 2) raw cosine
def raw_cos(a, b): return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-8))
pcos = np.array([raw_cos(L12s[i], L22s[i]) for i in mcal])
ncos = np.array([raw_cos(L12s[i], L22s[j]) for i in mcal for j in knn[i][1:3] if j != i])
thr = thr_from(pcos, ncos)
cos_te = np.array([raw_cos(CANDs[c], INDEXs[d]) for c, d in teP])
report["base_raw_cos"] = dict(thr=round(thr, 3),
f1=round(f1_score(teY, (cos_te >= thr).astype(int), zero_division=0), 4))
# 3) WM InfoNCE encoder
class Enc(nn.Module):
def __init__(s, din, d=32):
super().__init__(); s.net = nn.Sequential(nn.Linear(din, 64), nn.GELU(), nn.Linear(64, 64), nn.GELU(), nn.Linear(64, d))
def forward(s, x): return F.normalize(s.net(x), dim=-1)
def info_nce(za, zb, tau=0.1):
lg = za @ zb.t() / tau; lab = torch.arange(za.size(0), device=za.device)
return 0.5 * (F.cross_entropy(lg, lab) + F.cross_entropy(lg.t(), lab))
enc = Enc(DIM).to(DEV); opt = torch.optim.Adam(enc.parameters(), 1e-3, weight_decay=1e-5)
A, B = L12t[mtr], L22t[mtr]
for ep in range(500):
p = torch.randperm(A.size(0), device=DEV)
for i in range(0, A.size(0), 256):
b = p[i:i+256]
if b.numel() < 8: continue
loss = info_nce(enc(A[b]), enc(B[b])); opt.zero_grad(); loss.backward(); opt.step()
enc.eval()
with torch.no_grad():
e12 = enc(L12t).cpu().numpy(); e22 = enc(L22t).cpu().numpy()
ecand = enc(CANDt).cpu().numpy(); eindex = enc(INDEXt).cpu().numpy()
pe = np.array([np.dot(e12[i], e22[i]) for i in mcal])
ne = np.array([np.dot(e12[i], e22[j]) for i in mcal for j in knn[i][1:3] if j != i])
thrw = thr_from(pe, ne)
wcos_te = np.sum(ecand[teP[:, 0]] * eindex[teP[:, 1]], axis=1)
report["wm_zeroshot_cos"] = dict(thr=round(thrw, 3),
f1=round(f1_score(teY, (wcos_te >= thrw).astype(int), zero_division=0), 4),
precision=round(precision_score(teY, (wcos_te >= thrw).astype(int), zero_division=0), 4),
recall=round(recall_score(teY, (wcos_te >= thrw).astype(int), zero_division=0), 4))
# 4) Conditional Flow Matching (4B)
class VNet(nn.Module):
def __init__(s, din):
super().__init__(); s.net = nn.Sequential(nn.Linear(din + 1, 128), nn.GELU(),
nn.Linear(128, 128), nn.GELU(), nn.Linear(128, din))
def forward(s, x, t): return s.net(torch.cat([x, t], -1))
vnet = VNet(DIM).to(DEV); optf = torch.optim.Adam(vnet.parameters(), 1e-3, weight_decay=1e-5)
x0, x1 = L12t[mtr], L22t[mtr]
for ep in range(600):
p = torch.randperm(x0.size(0), device=DEV)
for i in range(0, x0.size(0), 256):
b = p[i:i+256]
if b.numel() < 8: continue
a0, a1 = x0[b], x1[b]
t = torch.rand(a0.size(0), 1, device=DEV)
xt = (1 - t) * a0 + t * a1
loss = F.mse_loss(vnet(xt, t), a1 - a0)
optf.zero_grad(); loss.backward(); optf.step()
vnet.eval()
@torch.no_grad()
def flow_resid(a, b):
a = torch.tensor(a, dtype=torch.float32, device=DEV); b = torch.tensor(b, dtype=torch.float32, device=DEV)
if a.dim() == 1: a = a[None]; b = b[None]
t = torch.full((a.size(0), 1), 0.5, device=DEV)
xt = 0.5 * (a + b)
v = vnet(xt, t)
return (-(v - (b - a)).pow(2).mean(1)).cpu().numpy() # higher = more consistent
pf = flow_resid(L12s[mcal], L22s[mcal])
nf = np.concatenate([flow_resid(L12s[[i]], L22s[[j]]) for i in mcal for j in knn[i][1:3] if j != i])
thrf = thr_from(pf, nf)
flow_te = flow_resid(CANDs[teP[:, 0]], INDEXs[teP[:, 1]])
report["flow_zeroshot"] = dict(thr=round(float(thrf), 3),
f1=round(f1_score(teY, (flow_te >= thrf).astype(int), zero_division=0), 4),
precision=round(precision_score(teY, (flow_te >= thrf).astype(int), zero_division=0), 4),
recall=round(recall_score(teY, (flow_te >= thrf).astype(int), zero_division=0), 4))
print("\n=== ZERO-SHOT (train on multi-LoD, 0 Hague labels) ===", flush=True)
for k, s in sorted(report.items(), key=lambda kv: -kv[1]['f1']):
print(f" {k:28s} F1={s['f1']:.4f}", flush=True)
os.makedirs(os.path.dirname(OUT), exist_ok=True)
json.dump(report, open(OUT, "w"), indent=2)
print("Saved ->", OUT, flush=True)
|