OPE-means / benchmarks /ope_dev.py
Nabidnur's picture
OPE-means v5: code, results, technical report, figures, notebooks, tests
f640c46 verified
Raw History Blame Contribute Delete
2.65 kB
"""OPE-means development runs on the robust benchmark (single thread by default).
Usage: python benchmarks/ope_dev.py DATA_DIR DATASET [DATASET...] --variant name '{json}' ..."""
import argparse, json, os, sys, time
import numpy as np, faiss
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from aries.opemeans import ope_means # noqa: E402
SEEDS = [42, 123, 456, 789, 1024, 1337, 2048, 3141, 4200, 5318] # the OKMeans paper's seeds
ap = argparse.ArgumentParser(); ap.add_argument("data"); ap.add_argument("datasets", nargs="+")
ap.add_argument("--variant", nargs=2, action="append", default=[]); ap.add_argument("--threads", type=int, default=1)
ap.add_argument("--seeds", type=int, nargs="+", default=SEEDS); ap.add_argument("--out")
a = ap.parse_args(); faiss.omp_set_num_threads(a.threads)
def exact_cost(X, C, z, chunk=262144, mask=None):
"""The benchmark's metric in float64 (as the authors' cost_colorless): squared distance to the nearest centre,
z largest dropped, on the original float64 rows. With `mask` (true outliers) also returns the precision,
recall and F1 of the z dropped rows, as the authors' benchmark reports them."""
C = np.asarray(C, dtype=np.float64)
d = np.concatenate([((X[s:s + chunk, None, :] - C[None]) ** 2).sum(2).min(1) for s in range(0, len(X), chunk)])
cost = float(np.partition(d, len(d) - z - 1)[:len(d) - z].sum()) if z > 0 else float(d.sum())
if mask is None:
return cost
pred = np.zeros(len(d), bool)
if z > 0:
pred[np.argsort(-d, kind="stable")[:z]] = True
tp = int((pred & mask).sum()); p_ = tp / max(1, pred.sum()); r_ = tp / max(1, mask.sum())
return cost, dict(precision=p_, recall=r_, f1=2 * p_ * r_ / max(1e-12, p_ + r_))
variants = a.variant or [("default", "{}")]
for ds in a.datasets:
f = np.load(os.path.join(a.data, ds + ".npz")); X = f["data"]; z = int(f["outlier_mask"].sum()); k = int(f["k"])
for name, js in variants:
costs, secs = [], []
for s in a.seeds:
t = time.time(); Cs, c_alg, info = ope_means(X, k, z, seed=s, **json.loads(js)); secs.append(time.time() - t)
c, od = exact_cost(X, Cs, z, mask=f["outlier_mask"]); costs.append(c); info = dict(info, cost_alg=c_alg, **od)
if a.out:
with open(a.out, "a") as fo:
fo.write(json.dumps(dict(dataset=ds, variant=name, kwargs=json.loads(js), seed=s, cost=c, seconds=secs[-1], threads=a.threads, **info)) + "\n")
print(f"{ds:8s} {name:18s} best {min(costs):.4e} mean {np.mean(costs):.4e} ± {np.std(costs):.2e} {np.mean(secs):.1f}s", flush=True)