""" STER — Few-shot baseline landscape. The clean full-data matcher hits F1 ~0.95, but collapses to 0.41-0.56 at K<=10 labels (see headroom_diagnostic). Here we map how much of that gap is capturable by STANDARD few-shot techniques, to set the bar the novel method must beat. Compares, at K in {5,10,20,50,100} positive pairs (+2K neg), averaged over 10 random label draws: Bagging (repo baseline), LogReg-L2, RandomForest(shallow), kNN, NearestCentroid(prototype), SVM-RBF, MLP, + LogReg on features standardised with ALL unlabeled candidate pairs. No crawl needed (uses cached property dicts + partition pairs). """ import os, json, warnings, numpy as np, joblib warnings.filterwarnings("ignore") from sklearn.ensemble import BaggingClassifier, RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier, NearestCentroid from sklearn.svm import SVC from sklearn.neural_network import MLPClassifier from sklearn.preprocessing import StandardScaler from sklearn.pipeline import make_pipeline from sklearn.metrics import f1_score SEED = 1 PROP = "data/property_dicts" TRAIN_PD = f"{PROP}/Hague_130425_train_matching_small_neg_samples_num=2_vector_normalization=True_seed=1.joblib" TEST_PD = f"{PROP}/Hague_130425_test_matching_small_neg_samples_num=2_vector_normalization=True_seed=1.joblib" PART = "data/dataset_partitions/Hague_seed1.pkl" MAX_RATIO = 1000.0 train_pd = joblib.load(TRAIN_PD); test_pd = joblib.load(TEST_PD); part = joblib.load(PART) PROPS = list(train_pd.keys()) train_pairs = part['train']['blocking-based']['small'][2] test_pairs = part['test']['matching']['blocking-based']['small'][2] def build_xy(pairs, pd): X, y = [], [] for c, i in pairs: row, ok = [], True for p in PROPS: try: cv, iv = pd[p]['cands'][c], pd[p]['index'][i] row.append(min(MAX_RATIO, round(cv / iv, 3)) if iv != 0 else MAX_RATIO) except KeyError: ok = False; break if ok: X.append(row); y.append(1 if c == i else 0) return np.array(X), np.array(y) Xtr, ytr = build_xy(train_pairs, train_pd) Xte, yte = build_xy(test_pairs, test_pd) print(f"train X={Xtr.shape} pos={ytr.sum()} | test X={Xte.shape} pos={yte.sum()}", flush=True) # feature scaler fit on ALL unlabeled train pairs (no labels used) scaler_all = StandardScaler().fit(Xtr) def make_models(): return { "Bagging(repo)": BaggingClassifier(n_estimators=30, random_state=SEED), "LogReg-L2": make_pipeline(StandardScaler(), LogisticRegression(C=1.0, max_iter=500)), "RF-shallow": RandomForestClassifier(n_estimators=100, max_depth=4, random_state=SEED), "kNN": make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=3)), "Prototype(NC)": make_pipeline(StandardScaler(), NearestCentroid()), "SVM-RBF": make_pipeline(StandardScaler(), SVC(C=1.0, gamma="scale")), "MLP": make_pipeline(StandardScaler(), MLPClassifier((32,), max_iter=800, random_state=SEED)), } def make_models_unsup_scaler(): # LogReg on features standardised with ALL unlabeled data statistics class Pre: def __init__(s, m): s.m = m def fit(s, X, y): s.m.fit(scaler_all.transform(X), y); return s def predict(s, X): return s.m.predict(scaler_all.transform(X)) return {"LogReg+unsupScaler": Pre(LogisticRegression(C=1.0, max_iter=500))} Ks = [5, 10, 20, 50, 100] N_DRAWS = 10 pos_idx = np.where(ytr == 1)[0]; neg_idx = np.where(ytr == 0)[0] report = {} for K in Ks: if K > len(pos_idx): break per_model = {name: [] for name in list(make_models()) + list(make_models_unsup_scaler())} for rep in range(N_DRAWS): r = np.random.RandomState(200 + rep) ps = r.choice(pos_idx, K, replace=False) ns = r.choice(neg_idx, min(2 * K, len(neg_idx)), replace=False) idx = np.concatenate([ps, ns]) models = {**make_models(), **make_models_unsup_scaler()} for name, clf in models.items(): try: clf.fit(Xtr[idx], ytr[idx]) per_model[name].append(f1_score(yte, clf.predict(Xte), zero_division=0)) except Exception: per_model[name].append(0.0) report[K] = {name: dict(f1=round(float(np.mean(v)), 4), std=round(float(np.std(v)), 4)) for name, v in per_model.items()} print(f"\n=== K={K} (avg over {N_DRAWS} draws) ===", flush=True) for name, s in sorted(report[K].items(), key=lambda kv: -kv[1]['f1']): print(f" {name:22s} F1={s['f1']:.4f} ±{s['std']:.4f}", flush=True) os.makedirs("../../experiments/fewshot", exist_ok=True) with open("../../experiments/fewshot/fewshot_baselines.json", "w") as f: json.dump(report, f, indent=2) print("\nSaved -> experiments/fewshot/fewshot_baselines.json", flush=True)