File size: 6,379 Bytes
a525891
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
STER — Difficulty / Headroom Diagnostic.

Goal: the CLEAN Hague matching baseline is ~F1 0.95 (near-solved), so we must find
WHERE the ratio+classifier baseline actually breaks, i.e. which scenarios have room
for a new method. Uses ONLY cached property dicts + partition pairs (no crawl).

Measures:
  (0) Baseline   : full-train Bagging on full test  -> confirms ~0.95
  (1) Few-shot   : train on K positive pairs (+2K neg) -> F1(K) curve
  (2) Long-tail  : split TEST by candidate size (volume) into head/tail -> F1 per stratum
  (3) Discrepancy: split TEST by cross-source geometric discrepancy -> F1 per bin
                   (proxy for the 'noisy' regime without needing multi-LoD crawl)
"""
import os, json, warnings, numpy as np, joblib
warnings.filterwarnings("ignore")
from sklearn.ensemble import BaggingClassifier
from sklearn.metrics import f1_score, precision_score, recall_score

SEED = 1
PROP_DIR = "data/property_dicts"
PART = "data/dataset_partitions/Hague_seed1.pkl"
TRAIN_PD = f"{PROP_DIR}/Hague_130425_train_matching_small_neg_samples_num=2_vector_normalization=True_seed=1.joblib"
TEST_PD = f"{PROP_DIR}/Hague_130425_test_matching_small_neg_samples_num=2_vector_normalization=True_seed=1.joblib"
MAX_RATIO = 1000.0
rng = np.random.RandomState(SEED)

print("Loading cached property dicts + partition ...", flush=True)
train_pd = joblib.load(TRAIN_PD)
test_pd = joblib.load(TEST_PD)
part = joblib.load(PART)
PROPS = list(train_pd.keys())
print(f"  {len(PROPS)} properties")

train_pairs = part['train']['blocking-based']['small'][2]
test_pairs = part['test']['matching']['blocking-based']['small'][2]


def build_xy(pairs, pd):
    """Return X (ratio features), y (label = cand_id==index_id), and cand raw log-size."""
    X, y = [], []
    cand_size, discrepancy = [], []
    for c, i in pairs:
        row = []
        logdev = []
        ok = True
        for p in PROPS:
            try:
                cv = pd[p]['cands'][c]; iv = pd[p]['index'][i]
                r = min(MAX_RATIO, round(cv / iv, 3)) if iv != 0 else MAX_RATIO
            except KeyError:
                ok = False; break
            row.append(r)
            # discrepancy in log-space: |log(cv)-log(iv)| approximated by |cv-iv| (already log1p'd)
            logdev.append(abs(cv - iv))
        if not ok:
            continue
        X.append(row); y.append(1 if c == i else 0)
        cand_size.append(pd['volume']['cands'][c])         # log1p volume of candidate
        discrepancy.append(float(np.mean(logdev)))         # mean per-prop log-discrepancy
    return (np.array(X), np.array(y), np.array(cand_size), np.array(discrepancy))


print("Building feature matrices ...", flush=True)
Xtr, ytr, _, _ = build_xy(train_pairs, train_pd)
Xte, yte, size_te, disc_te = build_xy(test_pairs, test_pd)
print(f"  train X={Xtr.shape} pos={ytr.sum()} | test X={Xte.shape} pos={yte.sum()}", flush=True)


def fit_eval(Xtr, ytr, Xte, yte, n_estimators=50):
    clf = BaggingClassifier(n_estimators=n_estimators, random_state=SEED)
    clf.fit(Xtr, ytr)
    pred = clf.predict(Xte)
    return dict(precision=round(precision_score(yte, pred, zero_division=0), 4),
                recall=round(recall_score(yte, pred, zero_division=0), 4),
                f1=round(f1_score(yte, pred, zero_division=0), 4))


report = {}

# (0) Baseline
print("\n[0] Baseline (full train -> full test)", flush=True)
base = fit_eval(Xtr, ytr, Xte, yte)
print("   ", base, flush=True)
report['baseline_full'] = base

# (1) Few-shot: K positive pairs + 2K negatives
print("\n[1] Few-shot curve", flush=True)
pos_idx = np.where(ytr == 1)[0]; neg_idx = np.where(ytr == 0)[0]
fewshot = {}
for K in [1, 3, 5, 10, 20, 50, 100]:
    if K > len(pos_idx):
        break
    accs = []
    for rep in range(5):  # average over 5 random label sets
        r = np.random.RandomState(100 + 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])
        accs.append(fit_eval(Xtr[idx], ytr[idx], Xte, yte, n_estimators=30)['f1'])
    fewshot[K] = dict(f1_mean=round(float(np.mean(accs)), 4), f1_std=round(float(np.std(accs)), 4))
    print(f"    K={K:3d} -> F1={fewshot[K]['f1_mean']:.4f} ±{fewshot[K]['f1_std']:.4f}", flush=True)
report['few_shot'] = fewshot

# (2) Long-tail: split test by candidate volume (rare large buildings = tail)
print("\n[2] Long-tail (test split by candidate volume)", flush=True)
clf = BaggingClassifier(n_estimators=50, random_state=SEED).fit(Xtr, ytr)
pred_te = clf.predict(Xte)
q_hi = np.quantile(size_te, 0.90)   # top 10% largest = tail
q_lo = np.quantile(size_te, 0.10)
longtail = {}
for name, mask in [('head_common_mid', (size_te > q_lo) & (size_te <= q_hi)),
                   ('tail_large_top10', size_te > q_hi),
                   ('tail_small_bot10', size_te <= q_lo)]:
    if mask.sum() == 0:
        continue
    longtail[name] = dict(n=int(mask.sum()),
                          f1=round(f1_score(yte[mask], pred_te[mask], zero_division=0), 4),
                          recall=round(recall_score(yte[mask], pred_te[mask], zero_division=0), 4))
    print(f"    {name:20s} n={mask.sum():5d} F1={longtail[name]['f1']:.4f}", flush=True)
report['long_tail'] = longtail

# (3) Discrepancy-stratified: F1 vs cross-source geometric discrepancy
print("\n[3] Discrepancy-stratified (test split by cand-index geometric gap)", flush=True)
bins = np.quantile(disc_te, [0, 0.25, 0.5, 0.75, 0.9, 1.0])
disc = {}
for b in range(len(bins) - 1):
    lo, hi = bins[b], bins[b + 1]
    mask = (disc_te >= lo) & (disc_te <= hi if b == len(bins) - 2 else disc_te < hi)
    if mask.sum() == 0:
        continue
    disc[f"q{b}"] = dict(range=[round(float(lo), 3), round(float(hi), 3)], n=int(mask.sum()),
                         f1=round(f1_score(yte[mask], pred_te[mask], zero_division=0), 4),
                         recall=round(recall_score(yte[mask], pred_te[mask], zero_division=0), 4))
    print(f"    q{b} disc∈[{lo:.2f},{hi:.2f}] n={mask.sum():5d} F1={disc[f'q{b}']['f1']:.4f}", flush=True)
report['discrepancy'] = disc

os.makedirs("../../experiments/diagnostic", exist_ok=True)
with open("../../experiments/diagnostic/headroom_diagnostic.json", "w") as f:
    json.dump(report, f, indent=2)
print("\nSaved -> experiments/diagnostic/headroom_diagnostic.json", flush=True)