Download example.py from rigel08/secondsite-xray-ensemble: direct link, hf CLI and curl.
- Browser
- Download file 1.86 kB
-
https://huggingface.co/rigel08/secondsite-xray-ensemble/resolve/main/example.py
- Command line
-
hf download hf://rigel08/secondsite-xray-ensemble/example.py
-
curl -L -o example.py https://huggingface.co/rigel08/secondsite-xray-ensemble/resolve/main/example.py
1.86 kB
| """One X-ray through the SecondSite pipeline: ensemble probability, uncertainty, shift score, referral.""" | |
| import json | |
| import numpy as np | |
| import onnxruntime as ort | |
| from PIL import Image | |
| from huggingface_hub import hf_hub_download | |
| REPO = "rigel08/secondsite-xray-ensemble" | |
| cfg = json.load(open(hf_hub_download(REPO, "config.json"))) | |
| sess = ort.InferenceSession(hf_hub_download(REPO, "ensemble5_int8.onnx")) | |
| shift = np.fromfile(hf_hub_download(REPO, "shift.f32"), np.float32) | |
| D, K = 512, cfg["n_means"] | |
| means, prec = shift[:K * D].reshape(K, D), shift[K * D:].reshape(D, D) | |
| g = np.asarray(Image.open(hf_hub_download(REPO, "pneumonia_caught_test102.png")).convert("L").resize((128, 128)), np.float32) / 255 | |
| mean, std = np.array([0.485, 0.456, 0.406]), np.array([0.229, 0.224, 0.225]) | |
| x = ((np.repeat(g[None], 3, 0) - mean[:, None, None]) / std[:, None, None]).astype(np.float32)[None] | |
| logits, feats = sess.run(["member_logits", "features"], {"x": x}) | |
| z = logits[0, :, 1] - logits[0, :, 0] # each member's log-odds | |
| p_members = 1 / (1 + np.exp(-z)) | |
| p = p_members.mean() # ensemble probability | |
| pooled = np.log(p) - np.log1p(-p) | |
| entropy = -(p * np.log(p) + (1 - p) * np.log(1 - p)) | |
| d = feats[0] - means | |
| maha = min(float(v @ prec @ v) for v in d) # distance to nearest class mean | |
| flag = pooled >= cfg["threshold_log_odds"] | |
| refer = entropy > cfg["referral_entropy_cutoff"] or maha > cfg["shift_cutoff"] | |
| print(f"members: {np.round(p_members, 3)}") | |
| print(f"ensemble p(pneumonia) = {p:.3f} -> {'FLAG' if flag else 'no flag'}") | |
| print(f"uncertainty (entropy) = {entropy:.3f} (refer above {cfg['referral_entropy_cutoff']:.3f})") | |
| print(f"shift score = {maha:.0f} (warn above {cfg['shift_cutoff']:.0f})") | |
| print("REFER TO A HUMAN" if refer else "no referral") | |