STER / code /ster_noisy.py
eduzrh's picture
Full autonomous run: 8 proposals with real results (few-shot WM wins K<=10; zero-shot via multi-LoD 0.67; noisy/cross-LoD solved by baseline) + all code, results, derived data
99f65bd verified
Raw
History Blame Contribute Delete
4.67 kB
"""
STER — Noisy / cross-representation ER via cross-LoD matching (GPU).
The clean Hague sources are both high-quality, so 'noise' there is mild. The genuine
noisy / cross-representation regime is CROSS-LoD matching: candidate = LoD1.2 (coarse
block, ~6 faces) vs index = LoD2.2 (detailed roof, many faces) of the SAME building —
a large, systematic geometric distortion. With HARD negatives (nearest LoD2.2 in
property space) this is a real challenge.
positives: (b.LoD12, b.LoD22) ; negatives: (b.LoD12, nn(b).LoD22) [top-k hard]
split buildings 60/40. Compare baseline vs WM vs flow.
"""
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_noisy_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"]; DIM=lod12.shape[1]; N=lod12.shape[0]
sc=StandardScaler().fit(np.vstack([lod12,lod22])); L12s,L22s=sc.transform(lod12),sc.transform(lod22)
def T(x): return torch.tensor(x,dtype=torch.float32,device=DEV)
nbrs=NearestNeighbors(n_neighbors=6).fit(L22s); _,knn=nbrs.kneighbors(L12s)
perm=np.random.permutation(N); tr_ids,te_ids=set(perm[:int(.6*N)]),set(perm[int(.6*N):])
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(ids):
Xr,P,Y=[],[],[]
for i in ids:
Xr.append(ratio(lod12[i],lod22[i])); P.append((i,i)); Y.append(1)
for j in knn[i][1:3]:
if j!=i: Xr.append(ratio(lod12[i],lod22[j])); P.append((i,j)); Y.append(0)
return np.array(Xr),np.array(P),np.array(Y)
Xr_tr,P_tr,Y_tr=make(list(tr_ids)); Xr_te,P_te,Y_te=make(list(te_ids))
print(f"cross-LoD train={Xr_tr.shape}({Y_tr.sum()}+) test={Xr_te.shape}({Y_te.sum()}+) dev={DEV}",flush=True)
report={}
# baseline
clf=BaggingClassifier(n_estimators=100,random_state=1).fit(Xr_tr,Y_tr); pred=clf.predict(Xr_te)
report["baseline_ratio_bagging"]=dict(f1=round(f1_score(Y_te,pred,zero_division=0),4),
precision=round(precision_score(Y_te,pred,zero_division=0),4),recall=round(recall_score(Y_te,pred,zero_division=0),4))
# WM (2B-style: identity encoder trained on the SAME cross-LoD train pairs, supervised contrastive)
class Enc(nn.Module):
def __init__(s,d):
super().__init__(); s.net=nn.Sequential(nn.Linear(d,64),nn.GELU(),nn.Linear(64,64),nn.GELU(),nn.Linear(64,32))
def forward(s,x): return F.normalize(s.net(x),dim=-1)
def info_nce(a,b,tau=0.1):
lg=a@b.t()/tau; lab=torch.arange(a.size(0),device=a.device); return .5*(F.cross_entropy(lg,lab)+F.cross_entropy(lg.t(),lab))
pos_tr=P_tr[Y_tr==1]
a=T(L12s[pos_tr[:,0]]); b=T(L22s[pos_tr[:,1]])
enc=Enc(DIM).to(DEV); opt=torch.optim.Adam(enc.parameters(),1e-3,weight_decay=1e-5)
for ep in range(500):
p=torch.randperm(a.size(0),device=DEV)
for i in range(0,a.size(0),256):
idx=p[i:i+256]
if idx.numel()<8: continue
loss=info_nce(enc(a[idx]),enc(b[idx])); opt.zero_grad(); loss.backward(); opt.step()
enc.eval()
with torch.no_grad(): e12=enc(T(L12s)).cpu().numpy(); e22=enc(T(L22s)).cpu().numpy()
cos_te=np.sum(e12[P_te[:,0]]*e22[P_te[:,1]],1); cos_tr=np.sum(e12[P_tr[:,0]]*e22[P_tr[:,1]],1)
thr=float(np.median([np.quantile(cos_tr[Y_tr==1],.2),np.quantile(cos_tr[Y_tr==0],.8)]))
report["wm_cross_lod_cos"]=dict(thr=round(thr,3),f1=round(f1_score(Y_te,(cos_te>=thr).astype(int),zero_division=0),4),
precision=round(precision_score(Y_te,(cos_te>=thr).astype(int),zero_division=0),4),
recall=round(recall_score(Y_te,(cos_te>=thr).astype(int),zero_division=0),4))
# hybrid: raw + wm cos -> bagging
hyb_tr=np.concatenate([Xr_tr,cos_tr[:,None]],1); hyb_te=np.concatenate([Xr_te,cos_te[:,None]],1)
clf2=BaggingClassifier(n_estimators=100,random_state=1).fit(hyb_tr,Y_tr); pred2=clf2.predict(hyb_te)
report["hybrid_ratio_plus_wm_bagging"]=dict(f1=round(f1_score(Y_te,pred2,zero_division=0),4),
precision=round(precision_score(Y_te,pred2,zero_division=0),4),recall=round(recall_score(Y_te,pred2,zero_division=0),4))
print("\n=== NOISY / CROSS-LoD (LoD1.2 vs LoD2.2, hard negs) ===",flush=True)
for k,s in sorted(report.items(),key=lambda kv:-kv[1]['f1']): print(f" {k:32s} 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)