File size: 4,707 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
"""
STER — few-shot SCORE FUSION (GPU).

Observation: WM cosine (self-supervised identity, multi-LoD) is strong at K=5
(F1~0.48) but flat; raw-ratio Bagging is weak at K=5 but scales. Fuse them by
rank-averaging so the combined matcher traces the upper envelope across K,
without letting weak features corrupt the tree (no feature concat).

Reports at K in {5,10,20,50}:
  bar_raw_bagging      baseline
  wm_pre_cos           WM cosine (frozen pretrain), thr from K labels
  fusion_rank          0.5*rank(bagging_prob) + 0.5*rank(wm_cos), thr from K labels
  fusion_max           elementwise max of the two rank scores
"""
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.metrics import f1_score
from scipy.stats import rankdata

NPZ = "/root/ster/data/ster_wm_vectors.npz"
OUT = "/root/ster/exp/ster_fusion_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, candX, indexX = z["lod12_X"], z["lod22_X"], z["cand_X"], z["index_X"]
trP, trY, teP, teY = z["train_pairs"], z["train_y"], z["test_pairs"], z["test_y"]
DIM = lod12.shape[1]
scaler = StandardScaler().fit(np.vstack([lod12, lod22, candX, indexX]))
def T(x): return torch.tensor(scaler.transform(x), dtype=torch.float32, device=DEV)
L12, L22, CAND, INDEX = T(lod12), T(lod22), T(candX), T(indexX)

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 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)
for ep in range(400):
    p=torch.randperm(L12.size(0),device=DEV)
    for i in range(0,L12.size(0),256):
        b=p[i:i+256]
        if b.numel()<8: continue
        loss=info_nce(enc(L12[b]),enc(L22[b])); opt.zero_grad(); loss.backward(); opt.step()
enc.eval()
with torch.no_grad():
    ec=enc(CAND).cpu().numpy(); ei=enc(INDEX).cpu().numpy()

def ratio(P):
    a,b=candX[P[:,0]],indexX[P[:,1]]
    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)
raw_tr,raw_te=ratio(trP),ratio(teP)
cos_tr=np.sum(ec[trP[:,0]]*ei[trP[:,1]],1); cos_te=np.sum(ec[teP[:,0]]*ei[teP[:,1]],1)

def thr_from(scores, y):
    return float(np.median([np.quantile(scores[y==1],0.2) if (y==1).any() else .5,
                            np.quantile(scores[y==0],0.8) if (y==0).any() else .5]))

Ks,NDRAW=[5,10,20,50],15
pos=np.where(trY==1)[0]; neg=np.where(trY==0)[0]
report={}
for K in Ks:
    acc={k:[] for k in ["bar_raw_bagging","wm_pre_cos","fusion_rank","fusion_max"]}
    for rep in range(NDRAW):
        r=np.random.RandomState(300+rep)
        pidx=r.choice(pos,K,replace=False); nidx=r.choice(neg,min(2*K,len(neg)),replace=False)
        idx=np.concatenate([pidx,nidx]); y=trY[idx]
        clf=BaggingClassifier(n_estimators=50,random_state=1).fit(raw_tr[idx],y)
        prob_te=clf.predict_proba(raw_te)[:,1]; prob_tr=clf.predict_proba(raw_tr[idx])[:,1]
        acc["bar_raw_bagging"].append(f1_score(teY,(prob_te>=0.5).astype(int),zero_division=0))
        tcos=thr_from(cos_tr[idx],y)
        acc["wm_pre_cos"].append(f1_score(teY,(cos_te>=tcos).astype(int),zero_division=0))
        # rank-fusion on test set
        rb=rankdata(prob_te)/len(prob_te); rc=rankdata(cos_te)/len(cos_te)
        fr=0.5*rb+0.5*rc; fm=np.maximum(rb,rc)
        # thresholds for fused scores from the K training pairs
        rb_tr=rankdata(prob_tr)/len(prob_tr)
        # map train cos to test-rank scale via quantile of cos among test
        rc_tr=np.array([ (cos_te<cv).mean() for cv in cos_tr[idx] ])
        fr_tr=0.5*rb_tr+0.5*rc_tr; fm_tr=np.maximum(rb_tr,rc_tr)
        acc["fusion_rank"].append(f1_score(teY,(fr>=thr_from(fr_tr,y)).astype(int),zero_division=0))
        acc["fusion_max"].append(f1_score(teY,(fm>=thr_from(fm_tr,y)).astype(int),zero_division=0))
    report[K]={k:dict(f1=round(float(np.mean(v)),4),std=round(float(np.std(v)),4)) for k,v in acc.items()}
    print(f"\n=== K={K} ===",flush=True)
    for k,s in sorted(report[K].items(),key=lambda kv:-kv[1]['f1']):
        print(f"   {k:20s} F1={s['f1']:.4f} ±{s['std']:.4f}",flush=True)
os.makedirs(os.path.dirname(OUT),exist_ok=True); json.dump(report,open(OUT,"w"),indent=2)
print("\nSaved ->",OUT,flush=True)