"""Compare methods on a fixed 500-row He–Song–Xu-inspired mediation example. Requires NumPy and the sibling generate_example.py. The MediPFN option also uses the release's requirements-research.txt and downloads its pinned weights. """ import argparse import csv import json from pathlib import Path import sys import numpy as np from generate_example import generate def linear_baseline(x, a, m, y): """Product of adjusted OLS coefficients for this additive, linear DGP.""" mediator_design = np.column_stack((np.ones(len(a)), a, x)) outcome_design = np.column_stack((mediator_design, m)) def estimate(indices): alpha = np.linalg.lstsq(mediator_design[indices], m[indices], rcond=None)[0][1] beta = np.linalg.lstsq(outcome_design[indices], y[indices], rcond=None)[0][-1] return float(alpha * beta) point = estimate(np.arange(len(a))) rng = np.random.default_rng(1729) draws = [estimate(rng.integers(len(a), size=len(a))) for _ in range(1000)] return point, np.quantile(draws, [0.025, 0.975]) def medipfn(x, a, m, y, device): from huggingface_hub import hf_hub_download, snapshot_download from huggingface_hub.constants import HF_HUB_OFFLINE revision = '315046cf9838ebcf2b920dad0f87e95bbb5bbc04' # The bundled predictor locates its runtime relative to its resolved Python file. snapshot = snapshot_download( 'shibo769/MediPFN', revision=revision, local_dir=Path('medipfn_hf') / revision, allow_patterns=['arena_n500/**'], ignore_patterns=['arena_n500/MODEL_CARD.md'], local_files_only=HF_HUB_OFFLINE, ) model_dir = Path(snapshot) / 'arena_n500' sys.path.insert(0, str(model_dir)) from predict import Predictor backbones = [hf_hub_download( 'Prior-Labs/tabpfn_3', filename=f'tabpfn-v3-{role}-v3_default.ckpt', revision='e923ba9be85784206c9e2f43b0035c84d5fd5747', local_files_only=HF_HUB_OFFLINE, ) for role in ('classifier', 'regressor')] predictor = Predictor(*backbones, device=device, threads=4) observed = dict(x=x, a=a, m=m[:, None], y=y, x_types=np.array(['continuous', 'binary']), mediator_types=np.array(['continuous'])) prediction = predictor(observed, fold_seed=18031) return prediction['estimate'], prediction['intervals']['95'] def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--method', choices=('linear', 'medipfn', 'both', 'arena-rf'), default='linear', help='both runs the quick linear baseline and MediPFN; arena-rf runs the official RF baseline') parser.add_argument('--device', choices=('cpu', 'cuda'), default='cpu') parser.add_argument('--save-table', type=Path, help='Write the observed CSV to a new file') args = parser.parse_args() rows = generate(500, 1729) if args.save_table: with args.save_table.open('x', newline='', encoding='utf-8') as f: writer = csv.DictWriter(f, fieldnames=['X1', 'X2', 'A', 'M', 'Y'], lineterminator='\n') writer.writeheader() writer.writerows(rows) x = np.array([[r['X1'], r['X2']] for r in rows], dtype=float) a = np.array([r['A'] for r in rows], dtype=np.int64) m = np.array([r['M'] for r in rows], dtype=float) y = np.array([r['Y'] for r in rows], dtype=float) results = {} if args.method in ('linear', 'both'): results['Linear product baseline'] = linear_baseline(x, a, m, y) if args.method in ('medipfn', 'both'): results['MediPFN (released two-fold checkpoint)'] = medipfn(x, a, m, y, args.device) if args.method == 'arena-rf': from arena_rf_reference import run_table output = run_table(dict(x=x, a=a, m=m[:, None], y=y), fold_seed=18031, bootstrap_seed=1729, replicates=50) results['Arena random forest (five folds)'] = output['estimate'], output['interval_95'] truth = 0.04 report = {'n': len(rows), 'data_seed': 1729, 'true_nie': truth, 'methods': {}} for name, (point, (lower, upper)) in results.items(): report['methods'][name] = { 'estimate': round(float(point), 4), 'ci95': [round(float(lower), 4), round(float(upper), 4)], 'absolute_error': round(abs(float(point) - truth), 4), 'contains_truth': bool(lower <= truth <= upper), } print(json.dumps(report, indent=2, allow_nan=False)) if __name__ == '__main__': main()