Download proj2rep/lesion.py from markjiang1/Proj2Rep-CTFM: direct link, hf CLI and curl.
- Browser
- Download file 2.24 kB
-
https://huggingface.co/markjiang1/Proj2Rep-CTFM/resolve/main/proj2rep/lesion.py
- Command line
-
hf download hf://markjiang1/Proj2Rep-CTFM/proj2rep/lesion.py
-
curl -L -o lesion.py https://huggingface.co/markjiang1/Proj2Rep-CTFM/resolve/main/proj2rep/lesion.py
2.24 kB
| """Score lung nodule or liver lesion localization on CT-FM v12 regional features. | |
| python -m proj2rep lesion --task nodule --input embeddings/scan.npz --out scan_nodule.npz | |
| """ | |
| import argparse | |
| from pathlib import Path | |
| import numpy as np | |
| from scipy.special import expit | |
| def local_scores(regions, weights): | |
| """Apply the training standardization and logistic head; output rows and columns follow the encoder grid.""" | |
| grid = int(weights["grid"]) | |
| if regions.ndim != 3 or regions.shape[1:] != (grid**2, len(weights["coef"])): | |
| raise ValueError(f"Expected (slabs, {grid**2}, {len(weights['coef'])}) CT-FM features; encode with --grid {grid}") | |
| if not np.isfinite(regions).all(): | |
| raise ValueError("The scan contains missing or non-finite regional embeddings") | |
| x = regions.astype(np.float32, copy=True) | |
| x -= weights["mean"] | |
| x /= weights["scale"] | |
| logits = x.reshape(-1, x.shape[-1]) @ weights["coef"] + weights["intercept"] | |
| return expit(logits).reshape(len(x), grid, grid) | |
| def main(argv=None): | |
| parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| parser.add_argument("--task", choices=("nodule", "liver"), required=True) | |
| parser.add_argument("--input", type=Path, required=True, help="one scan produced by proj2rep encode --grid 8") | |
| parser.add_argument("--out", type=Path, required=True, help="output NPZ with slab positions and regional scores") | |
| args = parser.parse_args(argv) | |
| path = Path(__file__).parent / "weights" / f"{args.task}_grid8.npz" | |
| with np.load(path) as weights, np.load(args.input) as scan: | |
| scores = local_scores(scan["regions"], weights) | |
| z0 = scan["z0"] | |
| if z0.shape != (len(scores),) or not np.isfinite(z0).all(): | |
| raise ValueError("Expected one finite z0 coordinate per slab") | |
| if args.out.resolve() == args.input.resolve(): | |
| raise ValueError("Use a separate file for the output scores") | |
| with args.out.open("wb") as file: | |
| np.savez_compressed(file, z0=z0, scores=scores, task=args.task, grid=int(weights["grid"])) | |
| print(f"Scored {len(scores)} slabs for {args.task} localization") | |
| if __name__ == "__main__": | |
| main() | |