Download src/experiments.py from MarxistLeninist/repro-selecting-samples-on-graphs-bundle: direct link, hf CLI and curl.
- Browser
- Download file 9.31 kB
-
https://huggingface.co/datasets/MarxistLeninist/repro-selecting-samples-on-graphs-bundle/resolve/main/src/experiments.py
- Command line
-
hf download hf://datasets/MarxistLeninist/repro-selecting-samples-on-graphs-bundle/src/experiments.py
-
curl -L -o experiments.py https://huggingface.co/datasets/MarxistLeninist/repro-selecting-samples-on-graphs-bundle/resolve/main/src/experiments.py
9.31 kB
| """ | |
| Experiment runners for UGIES reproduction. | |
| """ | |
| import numpy as np | |
| import json | |
| import os | |
| from typing import Dict, List | |
| import sys | |
| import os | |
| sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| from src.ugies import ( | |
| UGIESPruner, | |
| compute_intrinsic_entropy, | |
| cosine_distance_matrix, | |
| g_sigmoid_nonpositive, | |
| g_linear_nonpositive, | |
| g_positive_violation, | |
| verify_submodularity, | |
| exact_mwcp_solver, | |
| compute_objective, | |
| ) | |
| def generate_synthetic_data( | |
| n_samples: int = 200, | |
| n_features: int = 10, | |
| n_classes: int = 5, | |
| seed: int = 42, | |
| ) -> tuple: | |
| """Generate synthetic classification data.""" | |
| np.random.seed(seed) | |
| data = np.random.randn(n_samples, n_features) | |
| labels = np.random.randint(0, n_classes, n_samples) | |
| # Add class structure | |
| for c in range(n_classes): | |
| mask = labels == c | |
| data[mask] += np.random.randn(n_features) * 2 | |
| return data, labels | |
| def experiment_a_submodularity() -> Dict: | |
| """Experiment A: Verify submodularity property computationally.""" | |
| print("=" * 60) | |
| print("EXPERIMENT A: Submodularity Verification") | |
| print("=" * 60) | |
| data, labels = generate_synthetic_data(n_samples=100, n_features=10, n_classes=5) | |
| # Compute intrinsic importance (use random values for generality) | |
| probs = np.random.dirichlet(np.ones(5), size=100) | |
| intrinsic = compute_intrinsic_entropy(probs) | |
| distances = cosine_distance_matrix(data, data) | |
| results = {} | |
| # Test 1: Valid conditions (sigmoid non-positive) | |
| print("\n[Test 1] Valid conditions: g(z) = sigmoid(z) - 1") | |
| passed, rate, violations = verify_submodularity( | |
| intrinsic, distances, alpha=1.0, g_fn=g_sigmoid_nonpositive, n_trials=100 | |
| ) | |
| print("\n[Test 1] Valid conditions: g(z) = sigmoid(z) - 1") | |
| passed, rate, violations = verify_submodularity( | |
| intrinsic, distances, alpha=1.0, g_fn=g_sigmoid_nonpositive, n_trials=200 | |
| ) | |
| print(f" Pass rate: {rate*100:.1f}%") | |
| print(f" Result: {'PASS' if passed else 'FAIL'}") | |
| results['valid_sigmoid'] = {'passed': passed, 'pass_rate': rate, 'n_violations': len(violations)} | |
| # Test 2: Valid conditions (linear non-positive) | |
| print("\n[Test 2] Valid conditions: g(z) = -z / max_dist") | |
| passed, rate, violations = verify_submodularity( | |
| intrinsic, distances, alpha=1.0, g_fn=lambda d: g_linear_nonpositive(d, max_dist=2.0), n_trials=100 | |
| ) | |
| print("\n[Test 2] Valid conditions: g(z) = -z / max_dist") | |
| passed, rate, violations = verify_submodularity( | |
| intrinsic, distances, alpha=1.0, g_fn=lambda d: g_linear_nonpositive(d, max_dist=2.0), n_trials=200 | |
| ) | |
| print(f" Pass rate: {rate*100:.1f}%") | |
| print(f" Result: {'PASS' if passed else 'FAIL'}") | |
| results['valid_linear'] = {'passed': passed, 'pass_rate': rate, 'n_violations': len(violations)} | |
| # Test 3: Invalid conditions (positive mapping - negative control) | |
| print("\n[Test 3] INVALID conditions: g(z) = +0.5 (should FAIL)") | |
| passed, rate, violations = verify_submodularity( | |
| intrinsic, distances, alpha=1.0, g_fn=g_positive_violation, n_trials=100 | |
| ) | |
| print("\n[Test 3] INVALID conditions: g(z) = +0.5 (should FAIL)") | |
| passed, rate, violations = verify_submodularity( | |
| intrinsic, distances, alpha=1.0, g_fn=g_positive_violation, n_trials=200 | |
| ) | |
| print(f" Pass rate: {rate*100:.1f}%") | |
| print(f" Result: {'PASS (unexpected!)' if passed else 'FAIL (expected)'}") | |
| results['invalid_positive'] = {'passed': passed, 'pass_rate': rate, 'n_violations': len(violations)} | |
| # Overall result | |
| results['overall_pass'] = ( | |
| results['valid_sigmoid']['passed'] and | |
| results['valid_linear']['passed'] and | |
| not results['invalid_positive']['passed'] | |
| ) | |
| print(f"\n{'='*60}") | |
| print(f"OVERALL: {'PASS' if results['overall_pass'] else 'FAIL'}") | |
| print(f"{'='*60}") | |
| return results | |
| def experiment_b_greedy_quality() -> Dict: | |
| """Experiment B: Greedy solver approximation quality vs exact solution.""" | |
| print("\n" + "=" * 60) | |
| print("EXPERIMENT B: Greedy Solver Approximation Quality") | |
| print("=" * 60) | |
| results = {'instances': []} | |
| for seed in [42, 123, 456, 789, 101112]: | |
| np.random.seed(seed) | |
| N = 15 # Small enough for brute force | |
| n_classes = 3 | |
| data = np.random.randn(N, 8) | |
| labels = np.random.randint(0, n_classes, N) | |
| probs = np.random.dirichlet(np.ones(n_classes), size=N) | |
| intrinsic = compute_intrinsic_entropy(probs) | |
| distances = cosine_distance_matrix(data, data) | |
| b = N // 2 | |
| alpha = 1.0 | |
| g_fn = g_sigmoid_nonpositive | |
| # Exact solution | |
| exact_subset, exact_obj = exact_mwcp_solver(intrinsic, distances, alpha, g_fn, b) | |
| # Greedy solution | |
| pruner = UGIESPruner( | |
| intrinsic_fn=lambda d: intrinsic, | |
| distance_fn=cosine_distance_matrix, | |
| g_fn=g_fn, | |
| alpha=alpha, | |
| use_sparsification=False, | |
| ) | |
| # Manually run greedy | |
| edge_weights = g_fn(distances) | |
| selected = [] | |
| remaining = set(range(N)) | |
| extrinsic_sum = np.zeros(N) | |
| for _ in range(b): | |
| unified = np.full(N, -np.inf) | |
| for i in remaining: | |
| unified[i] = alpha * intrinsic[i] + extrinsic_sum[i] | |
| best_idx = int(np.argmax(unified)) | |
| selected.append(best_idx) | |
| remaining.remove(best_idx) | |
| for i in remaining: | |
| extrinsic_sum[i] += edge_weights[i, best_idx] | |
| greedy_subset = np.array(selected) | |
| greedy_obj = compute_objective(greedy_subset, intrinsic, distances, alpha, g_fn) | |
| ratio = greedy_obj / exact_obj if exact_obj > 0 else 0.0 | |
| theoretical_bound = 1.0 - 1.0 / np.e | |
| print(f"\n Instance seed={seed}:") | |
| print(f" Exact objective: {exact_obj:.4f}") | |
| print(f" Greedy objective: {greedy_obj:.4f}") | |
| print(f" Ratio: {ratio:.4f}") | |
| print(f" Theoretical bound:{theoretical_bound:.4f}") | |
| print(f" Meets bound: {'YES' if ratio >= theoretical_bound - 1e-6 else 'NO'}") | |
| results['instances'].append({ | |
| 'seed': seed, | |
| 'N': N, | |
| 'b': b, | |
| 'exact_obj': float(exact_obj), | |
| 'greedy_obj': float(greedy_obj), | |
| 'ratio': float(ratio), | |
| 'meets_bound': bool(ratio >= theoretical_bound - 1e-6), | |
| }) | |
| all_meet = all(inst['meets_bound'] for inst in results['instances']) | |
| results['overall_pass'] = all_meet | |
| print(f"\n{'='*60}") | |
| print(f"OVERALL: {'PASS' if all_meet else 'FAIL'}") | |
| print(f"{'='*60}") | |
| return results | |
| def experiment_d_toy_scale() -> Dict: | |
| """Experiment D: Toy-scale pruning on synthetic data.""" | |
| print("\n" + "=" * 60) | |
| print("EXPERIMENT D: Toy-Scale Pruning Verification") | |
| print("=" * 60) | |
| np.random.seed(42) | |
| N = 50 | |
| n_features = 8 | |
| n_classes = 3 | |
| data = np.random.randn(N, n_features) | |
| labels = np.random.randint(0, n_classes, N) | |
| # Add class structure | |
| for c in range(n_classes): | |
| mask = labels == c | |
| data[mask] += np.random.randn(n_features) * 2 | |
| # Intrinsic: entropy of pseudo-probabilities | |
| probs = np.random.dirichlet(np.ones(n_classes), size=N) | |
| def intrinsic_fn(d): | |
| return compute_intrinsic_entropy(probs) | |
| pruner = UGIESPruner( | |
| intrinsic_fn=intrinsic_fn, | |
| distance_fn=cosine_distance_matrix, | |
| g_fn=g_sigmoid_nonpositive, | |
| alpha=1.0, | |
| n_clusters=2, | |
| use_sparsification=True, | |
| ) | |
| pruning_ratios = [0.3, 0.5, 0.7] | |
| results = {'pruning_ratios': {}} | |
| for p in pruning_ratios: | |
| selected = pruner.prune(data, labels, pruning_ratio=p) | |
| print(f"\n Pruning ratio {p*100:.0f}%:") | |
| print(f" Selected {len(selected)} / {N} samples") | |
| print(f" Class distribution in selected: {dict(zip(*np.unique(labels[selected], return_counts=True)))}") | |
| results['pruning_ratios'][f'{int(p*100)}%'] = { | |
| 'n_selected': int(len(selected)), | |
| 'n_total': int(N), | |
| 'class_distribution': {int(k): int(v) for k, v in zip(*np.unique(labels[selected], return_counts=True))}, | |
| } | |
| results['overall_pass'] = True | |
| print(f"\n{'='*60}") | |
| print(f"OVERALL: PASS") | |
| print(f"{'='*60}") | |
| return results | |
| def run_all_experiments(): | |
| """Run all CPU-scale experiments.""" | |
| os.makedirs('outputs', exist_ok=True) | |
| results = {} | |
| results['A_submodularity'] = experiment_a_submodularity() | |
| results['B_greedy_quality'] = experiment_b_greedy_quality() | |
| results['D_toy_scale'] = experiment_d_toy_scale() | |
| # Save results | |
| with open('outputs/cpu_experiments.json', 'w') as f: | |
| json.dump(results, f, indent=2) | |
| print("\n" + "=" * 60) | |
| print("ALL CPU EXPERIMENTS COMPLETE") | |
| print("=" * 60) | |
| print(f"Results saved to: outputs/cpu_experiments.json") | |
| return results | |
| if __name__ == '__main__': | |
| run_all_experiments() | |