| """ |
| STER-GI Idea 1: Detail-Spectrum Imagination (细节谱想象) |
| ========================================================= |
| Conditional diffusion: p(x_target | x_source, τ) where τ ∈ [0,1] is detail level. |
| - Source A (cand) and Source B (index) = two views at different "detail levels" |
| - Train conditional diffusion to interpolate between them |
| - Generate views at intermediate τ → diverse positive pairs |
| - Contrastive learning → zero-shot matching |
| """ |
|
|
| import numpy as np, joblib, pickle as pkl, torch, torch.nn as nn, torch.nn.functional as F, time, os, argparse, sys |
| from torch.utils.data import DataLoader, TensorDataset |
| from sklearn.preprocessing import StandardScaler |
| from sklearn.metrics import precision_score, recall_score, f1_score |
|
|
| PROPS = ["bounding_box_width","bounding_box_length","area","perimeter","perimeter_ind", |
| "volume","convex_hull_area","convex_hull_volume","ave_centroid_distance","height_diff", |
| "num_floors","axes_symmetry","compactness_2d","compactness_3d","density","elongation", |
| "shape_ind","hemisphericality","fractality","cubeness","circumference", |
| "aligned_bounding_box_width","aligned_bounding_box_length","aligned_bounding_box_height","num_vertices"] |
|
|
| |
| def get_vecs(prop_dict, source): |
| ids = list(prop_dict[PROPS[0]][source].keys()) |
| X = np.zeros((len(ids), len(PROPS)), dtype=np.float32) |
| for i, bid in enumerate(ids): |
| for j, pn in enumerate(PROPS): |
| v = prop_dict[pn][source].get(bid, None) |
| X[i,j] = float(v) if v is not None and not (isinstance(v,float) and np.isnan(v)) else 0.0 |
| return X, ids |
|
|
| def load_all(seed): |
| tp = f"data/property_dicts/Hague_allmodels_v1_train_matching_medium_neg_samples_num=2_vector_normalization=True_seed={seed}.joblib" |
| ep = f"data/property_dicts/Hague_allmodels_v1_test_matching_medium_neg_samples_num=2_vector_normalization=True_seed={seed}.joblib" |
| trp = joblib.load(tp); epd = joblib.load(ep) |
| Xtc, id_tc = get_vecs(trp, 'cands'); Xti, id_ti = get_vecs(trp, 'index') |
| Xec, id_ec = get_vecs(epd, 'cands'); Xei, id_ei = get_vecs(epd, 'index') |
| X_all = np.concatenate([Xtc, Xti, Xec, Xei], axis=0) |
| print(f"Buildings: {len(X_all)}", flush=True) |
|
|
| |
| cand_all, idx_all = {}, {} |
| for sp, ids in [(trp,id_tc),(epd,id_ec)]: |
| for bid in ids: |
| if bid not in cand_all: |
| cand_all[bid] = np.array([float(sp[pn]['cands'].get(bid,0) or 0) for pn in PROPS], dtype=np.float32) |
| for sp, ids in [(trp,id_ti),(epd,id_ei)]: |
| for bid in ids: |
| if bid not in idx_all: |
| idx_all[bid] = np.array([float(sp[pn]['index'].get(bid,0) or 0) for pn in PROPS], dtype=np.float32) |
|
|
| common = sorted(set(cand_all.keys()) & set(idx_all.keys())) |
| src_views = np.array([cand_all[bid] for bid in common], dtype=np.float32) |
| tgt_views = np.array([idx_all[bid] for bid in common], dtype=np.float32) |
| print(f"Paired views: {len(common)}", flush=True) |
|
|
| |
| part = pkl.load(open(f"data/dataset_partitions/Hague_seed{seed}.pkl", 'rb')) |
| all_pairs = list(part['train']['negative_sampling']['medium'][2]) + list(part['test']['matching']['negative_sampling']['medium'][2]) |
| cv, iv, lbs = [], [], [] |
| for cid, iid in all_pairs: |
| if cid in cand_all and iid in idx_all: |
| cv.append(cand_all[cid]); iv.append(idx_all[iid]); lbs.append(1 if cid == iid else 0) |
| cv, iv, lbs = np.array(cv,dtype=np.float32), np.array(iv,dtype=np.float32), np.array(lbs,dtype=np.int32) |
| print(f"Eval pairs: {len(lbs)} ({lbs.sum()} pos, {(1-lbs).sum()} neg)", flush=True) |
| return X_all, src_views, tgt_views, cv, iv, lbs |
|
|
| |
| class CondDiffMLP(nn.Module): |
| """Predicts noise given (noisy_x, condition_x, tau, t)""" |
| def __init__(self,d,h=256,L=4): |
| super().__init__() |
| self.te = nn.Sequential(nn.Linear(1,h),nn.SiLU(),nn.Linear(h,h)) |
| self.tau_embed = nn.Sequential(nn.Linear(1,h),nn.SiLU(),nn.Linear(h,h)) |
| |
| net = [nn.Linear(2*d + 2*h, h), nn.SiLU()] |
| for _ in range(L-1): net += [nn.Linear(h,h), nn.SiLU()] |
| net.append(nn.Linear(h,d)); self.net = nn.Sequential(*net) |
|
|
| def forward(self, xt, x_cond, tau, t): |
| te = self.te(t.unsqueeze(-1).float()) |
| taue = self.tau_embed(tau.unsqueeze(-1).float()) |
| return self.net(torch.cat([xt, x_cond, te, taue], -1)) |
|
|
| class DiffSched: |
| def __init__(self,S=1000): |
| self.S=S; self.b=torch.linspace(1e-4,0.02,S); self.a=1-self.b; self.ab=torch.cumprod(self.a,0) |
| def noise(self,x0,t): |
| ab=self.ab[t].view(-1,1); eps=torch.randn_like(x0) |
| return torch.sqrt(ab)*x0+torch.sqrt(1-ab)*eps, eps |
| @torch.no_grad() |
| def step(self,m,xt,x_cond,tau,t): |
| a=self.a[t].view(-1,1); ab=self.ab[t].view(-1,1); b_=self.b[t].view(-1,1) |
| e=m(xt,x_cond,tau,t.float()); x0h=(xt-torch.sqrt(1-ab)*e)/torch.sqrt(a) |
| if t.min()==0: return x0h |
| abp=self.ab[t-1].view(-1,1) |
| mu=torch.sqrt(abp)*b_/(1-ab)*x0h+torch.sqrt(a)*(1-abp)/(1-ab)*xt |
| return mu+torch.sqrt(b_*(1-abp)/(1-ab))*torch.randn_like(xt) |
| @torch.no_grad() |
| def sample(self,m,x_cond,tau,dev): |
| """Generate x_target given x_cond at detail level tau""" |
| n=x_cond.shape[0]; xt=torch.randn(n,x_cond.shape[1]).to(dev) |
| for t in range(self.S-1,-1,-1): |
| tb=torch.full((n,),t,device=dev,dtype=torch.long) |
| tau_b=tau if isinstance(tau,torch.Tensor) else torch.full((n,),tau,device=dev,dtype=torch.float) |
| xt=self.step(m,xt,x_cond,tau_b,tb) |
| return xt |
|
|
| |
| class Encoder(nn.Module): |
| def __init__(self,d,h=128,o=64): |
| super().__init__() |
| self.net=nn.Sequential(nn.Linear(d,h),nn.BatchNorm1d(h),nn.ReLU(), |
| nn.Linear(h,h),nn.BatchNorm1d(h),nn.ReLU(),nn.Linear(h,o)) |
| def forward(self,x): |
| z=self.net(x); return z/(torch.norm(z,dim=-1,keepdim=True).clamp(min=1e-8)) |
|
|
| def infonce(emb,temp=0.07): |
| n=emb.shape[0]//2; sim=emb@emb.T/temp |
| sim=sim.masked_fill(torch.eye(2*n,device=emb.device,dtype=torch.bool),-1e9) |
| return F.cross_entropy(sim,torch.arange(2*n,device=emb.device)^1) |
|
|
| |
| def eval_pairs(encoder, cv, iv, lbs, dev, tag=""): |
| encoder.eval() |
| with torch.no_grad(): |
| ce = encoder(torch.FloatTensor(cv).to(dev)).cpu().numpy() |
| ie = encoder(torch.FloatTensor(iv).to(dev)).cpu().numpy() |
| sims = np.sum(ce * ie, axis=1) |
| best_f1, best_th = 0, 0 |
| for th in np.arange(0.3, 1.0, 0.02): |
| pred = (sims >= th).astype(np.int32) |
| f = f1_score(lbs, pred, zero_division=0) |
| if f > best_f1: best_f1, best_th = f, th |
| p = precision_score(lbs, (sims>=best_th).astype(np.int32), zero_division=0) |
| r = recall_score(lbs, (sims>=best_th).astype(np.int32), zero_division=0) |
| print(f" {tag}: P={p:.4f} R={r:.4f} F1={best_f1:.4f} (th={best_th:.2f})", flush=True) |
| return best_f1 |
|
|
| def baseline_raw(cv, iv, lbs): |
| cn = cv/(np.linalg.norm(cv,axis=1,keepdims=True)+1e-8) |
| i_n = iv/(np.linalg.norm(iv,axis=1,keepdims=True)+1e-8) |
| sims = np.sum(cn * i_n, axis=1) |
| best_f1, best_th = 0, 0 |
| for th in np.arange(0.3, 1.0, 0.02): |
| pred = (sims >= th).astype(np.int32) |
| f = f1_score(lbs, pred, zero_division=0) |
| if f > best_f1: best_f1, best_th = f, th |
| p = precision_score(lbs, (sims>=best_th).astype(np.int32), zero_division=0) |
| r = recall_score(lbs, (sims>=best_th).astype(np.int32), zero_division=0) |
| print(f" Baseline Raw: P={p:.4f} R={r:.4f} F1={best_f1:.4f} (th={best_th:.2f})", flush=True) |
| return best_f1 |
|
|
| |
| def main(): |
| a = argparse.ArgumentParser() |
| a.add_argument('--seed',type=int,default=1); a.add_argument('--diff_ep',type=int,default=100) |
| a.add_argument('--enc_ep',type=int,default=100); a.add_argument('--tau',type=float,default=0.5) |
| a.add_argument('--skip_diff',action='store_true'); a.add_argument('--skip_enc',action='store_true') |
| args = a.parse_args() |
| dev = 'cpu' |
| print(f"Device: {dev} | tau: {args.tau} | Seed: {args.seed}", flush=True) |
|
|
| X_all, src, tgt, cv, iv, lbs = load_all(args.seed) |
| sc = StandardScaler(); Xs = sc.fit_transform(X_all) |
| src_s = sc.transform(src); tgt_s = sc.transform(tgt) |
| cv_s, iv_s = sc.transform(cv), sc.transform(iv) |
|
|
| print("\n=== Baseline ===", flush=True) |
| b_raw = baseline_raw(cv_s, iv_s, lbs) |
|
|
| |
| diff_path = f"saved_model_files/condiff_i1_s{args.seed}.pt" |
|
|
| if args.skip_diff and os.path.exists(diff_path): |
| print(f"Loading cached cond diffusion: {diff_path}", flush=True) |
| ck = torch.load(diff_path, map_location=dev) |
| model = CondDiffMLP(Xs.shape[1]).to(dev); model.load_state_dict(ck['m']) |
| sched = DiffSched(); [setattr(sched,x,getattr(sched,x).to(dev)) for x in ['b','a','ab']] |
| else: |
| print(f"\n=== Conditional Diffusion ({args.diff_ep} epochs) ===", flush=True) |
| model = CondDiffMLP(Xs.shape[1]).to(dev); sched = DiffSched() |
| [setattr(sched,x,getattr(sched,x).to(dev)) for x in ['b','a','ab']] |
| opt = torch.optim.Adam(model.parameters(), lr=1e-3) |
|
|
| |
| |
| pairs = [] |
| for i in range(len(src_s)): |
| pairs.append((src_s[i], tgt_s[i], 1.0)) |
| pairs.append((tgt_s[i], src_s[i], 0.0)) |
| X_cond = np.array([p[0] for p in pairs], dtype=np.float32) |
| X_tgt = np.array([p[1] for p in pairs], dtype=np.float32) |
| Taus = np.array([p[2] for p in pairs], dtype=np.float32) |
|
|
| ds = TensorDataset(torch.FloatTensor(X_tgt), torch.FloatTensor(X_cond), torch.FloatTensor(Taus)) |
| dl = DataLoader(ds, batch_size=256, shuffle=True) |
|
|
| model.train(); t0_t = time.time() |
| for ep in range(args.diff_ep): |
| tot = 0 |
| for x_tgt, x_cond, tau in dl: |
| x_tgt, x_cond, tau = x_tgt.to(dev), x_cond.to(dev), tau.to(dev) |
| bs = x_tgt.shape[0] |
| t = torch.randint(0, 1000, (bs,), device=dev) |
| xt, noise = sched.noise(x_tgt, t) |
| loss = F.mse_loss(model(xt, x_cond, tau, t.float()), noise) |
| opt.zero_grad(); loss.backward(); opt.step(); tot += loss.item()*bs |
| if (ep+1)%10==0: print(f" Diff ep {ep+1}/{args.diff_ep}: loss={tot/len(ds):.6f} t={time.time()-t0_t:.0f}s", flush=True) |
| print(f" Done: loss={tot/len(ds):.6f}", flush=True) |
| torch.save({'m':model.state_dict()}, diff_path) |
|
|
| |
| gen_path = f"saved_model_files/gen_i1_s{args.seed}_tau{args.tau}.npz" |
| if os.path.exists(gen_path): |
| d = np.load(gen_path); gens = d['gens'] |
| print(f"Loaded cached generated views: {len(gens)}", flush=True) |
| else: |
| print(f"\n=== Generating Views at τ={args.tau} ===", flush=True) |
| model.eval(); gens = [] |
| with torch.no_grad(): |
| for i in range(0, len(Xs), 256): |
| xb = torch.FloatTensor(Xs[i:i+256]).to(dev) |
| for _ in range(2): |
| tau_b = torch.full((xb.shape[0],), args.tau, device=dev) |
| gen = sched.sample(model, xb, tau_b, dev) |
| gens.append(gen.cpu().numpy()) |
| gens = np.concatenate(gens) |
| print(f" Generated {len(gens)} views", flush=True) |
| np.savez_compressed(gen_path, gens=gens) |
|
|
| |
| enc_path = f"saved_model_files/enc_i1_s{args.seed}_tau{args.tau}.pt" |
| if args.skip_enc and os.path.exists(enc_path): |
| print(f"Loading cached encoder: {enc_path}", flush=True) |
| ck = torch.load(enc_path, map_location=dev) |
| encoder = Encoder(Xs.shape[1]).to(dev); encoder.load_state_dict(ck['e']) |
| else: |
| print(f"\n=== Contrastive Encoder ({args.enc_ep} epochs) ===", flush=True) |
| encoder = Encoder(Xs.shape[1]).to(dev) |
| opt = torch.optim.Adam(encoder.parameters(), lr=1e-4) |
| n_g = len(gens); idx = np.random.permutation(min(n_g, len(Xs))) |
| data = np.zeros((len(idx)*2, Xs.shape[1]), dtype=np.float32) |
| data[0::2] = Xs[idx]; data[1::2] = gens[idx] |
| ds = TensorDataset(torch.FloatTensor(data)); dl = DataLoader(ds, batch_size=1024, shuffle=False) |
| encoder.train(); t0_t = time.time() |
| for ep in range(args.enc_ep): |
| tot = 0 |
| for (xb,) in dl: |
| xb = xb.to(dev); emb = encoder(xb); loss = infonce(emb, 0.07) |
| opt.zero_grad(); loss.backward() |
| torch.nn.utils.clip_grad_norm_(encoder.parameters(), 1.0) |
| opt.step(); tot += loss.item()*xb.shape[0] |
| if (ep+1)%10==0: print(f" Enc ep {ep+1}/{args.enc_ep}: loss={tot/len(ds):.4f} t={time.time()-t0_t:.0f}s", flush=True) |
| print(f" Done: loss={tot/len(ds):.4f}", flush=True) |
| torch.save({'e':encoder.state_dict()}, enc_path) |
|
|
| |
| print("\n=== RESULTS ===", flush=True) |
| f1_i1 = eval_pairs(encoder, cv_s, iv_s, lbs, dev, f"Idea1 (τ={args.tau})") |
| print(f"\n Baseline (raw): F1={b_raw:.4f}") |
| print(f" Idea1 (detail-spec): F1={f1_i1:.4f}") |
| print(f" Supervised XGBoost: F1=0.982") |
| print(f" Δ over baseline: {f1_i1-b_raw:+.4f}", flush=True) |
|
|
| if __name__=='__main__': main() |
|
|